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/app/controllers/Statistiques.java b/app/controllers/Statistiques.java
index c2f262f..ca09678 100644
--- a/app/controllers/Statistiques.java
+++ b/app/controllers/Statistiques.java
@@ -1,142 +1,142 @@
package controllers;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import models.Journee;
import models.Matche;
import models.PointsJournee;
import models.PointsSaison;
import models.Pronostique;
import models.Saison;
import models.Sys_parameter;
import models.Utilisateur;
import play.api.mvc.MultipartFormData;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Security.Authenticated;
import views.html.inscription;
import views.html.membres;
import views.html.profilUtilisateur;
import views.html.statistiques;
@Authenticated(Secured.class)
public class Statistiques extends Controller {
public static Result getStat(String id) {
Long idLong;
Date maintenant = new Date();
Sys_parameter system = Sys_parameter.find.byId((long) 1);
Saison saison = system.getSaisonEnCours();
Journee premiereJournee = saison.getPremiereJournee();
Journee derniereJournee= saison.getDerniereJournee();
List<Journee> journeesPassees = Journee.find.where().le("id", derniereJournee.getId()).ge("id", premiereJournee.getId()).lt("dateJournee", maintenant).orderBy().desc("dateJournee").findList();
if (id.equalsIgnoreCase("0")) {
idLong = journeesPassees.get(0).id;
} else {
idLong = Long.parseLong(id);
}
Utilisateur user = Utilisateur.findByPseudo(request().username());
Journee journee = Journee.find.byId(idLong);
Integer points = PointsSaison.find.where().eq("saison", saison).eq("user", user).findList().get(0).pointsTotalSaison;
// Meilleur pronostiqueur de la journée
List<PointsJournee> classementPronostiqueurJournee = PointsJournee.find.where().eq("journee", journee).orderBy().desc("points").findList();
Integer i=1;
Integer scorePremier = classementPronostiqueurJournee.get(0).getPoints();
List<PointsJournee> meilleurPronostiqueurs = new ArrayList<PointsJournee>();
meilleurPronostiqueurs.add(classementPronostiqueurJournee.get(0));
while (classementPronostiqueurJournee.size()!=i && classementPronostiqueurJournee.get(i).getPoints()==scorePremier) {
PointsJournee egalite = classementPronostiqueurJournee.get(i);
meilleurPronostiqueurs.add(egalite);
i++;
}
// Plus mauvais de la journée
List<PointsJournee> classementPronostiqueurAscJournee = PointsJournee.find.where().eq("journee", journee).orderBy().asc("points").findList();
i=1;
Integer scoreDernier = classementPronostiqueurAscJournee.get(0).getPoints();
List<PointsJournee> mauvaisPronostiqueurs = new ArrayList<PointsJournee>();
mauvaisPronostiqueurs.add(classementPronostiqueurAscJournee.get(0));
while (classementPronostiqueurAscJournee.size()!=i && classementPronostiqueurAscJournee.get(i).getPoints()==scoreDernier) {
PointsJournee egalite = classementPronostiqueurAscJournee.get(i);
mauvaisPronostiqueurs.add(egalite);
i++;
}
// Scores corrects journée
List<PointsJournee> classementPointsCorrectsJournee = PointsJournee.find.where().eq("journee", journee).orderBy().desc("scoresCorrects").findList();
i=1;
Integer scoreCorrectsJournee = classementPointsCorrectsJournee.get(0).getScoresCorrects();
List<PointsJournee> pointsCorrectsJournee = new ArrayList<PointsJournee>();
pointsCorrectsJournee.add(classementPointsCorrectsJournee.get(0));
while (classementPointsCorrectsJournee.size()!=i && classementPointsCorrectsJournee.get(i).getScoresCorrects()==scoreCorrectsJournee) {
PointsJournee egalite = classementPointsCorrectsJournee.get(i);
pointsCorrectsJournee.add(egalite);
i++;
}
// Plus grand nombre de scores corrects au total
List<PointsSaison> classementScoresCorrectsTotal = PointsSaison.find.where().eq("saison", saison).orderBy().desc("totalScoresCorrects").findList();
i=1;
Integer maxScoreCorrects = classementScoresCorrectsTotal.get(0).getTotalScoresCorrects();
List<PointsSaison> scoreCorrectsTotal = new ArrayList<PointsSaison>();
scoreCorrectsTotal.add(classementScoresCorrectsTotal.get(0));
while (classementScoresCorrectsTotal.size()!=i && classementScoresCorrectsTotal.get(i).getTotalScoresCorrects()==maxScoreCorrects) {
PointsSaison egalite = classementScoresCorrectsTotal.get(i);
scoreCorrectsTotal.add(egalite);
i++;
}
// Plus grand nombre de scores corrects en une journée
List<PointsJournee> classementScoreCorrectsUneJournee = PointsJournee.find.where().ge("journee",saison.getPremiereJournee()).
le("journee", saison.getDerniereJournee()).orderBy().desc("scoresCorrects").findList();
i=1;
Integer maxScoreCorrectsUneJournee = classementScoreCorrectsUneJournee.get(0).getScoresCorrects();
List<PointsJournee> scoresCorrectsUneJournee = new ArrayList<PointsJournee>();
scoresCorrectsUneJournee.add(classementScoreCorrectsUneJournee.get(0));
while (classementScoreCorrectsUneJournee.size()!=i && classementScoreCorrectsUneJournee.get(i).getScoresCorrects()==maxScoreCorrectsUneJournee) {
PointsJournee egalite = classementScoreCorrectsUneJournee.get(i);
scoresCorrectsUneJournee.add(egalite);
i++;
}
// Meilleur score en une journée
List<PointsJournee> classementPointsUneJournee = PointsJournee.find.where().ge("journee",saison.getPremiereJournee()).
le("journee", saison.getDerniereJournee()).orderBy().desc("points").findList();
i=1;
Integer maxPointsUneJournee = classementPointsUneJournee.get(0).getPoints();
List<PointsJournee> pointsUneJournee = new ArrayList<PointsJournee>();
pointsUneJournee.add(classementPointsUneJournee.get(0));
while (classementPointsUneJournee.size()!=i && classementPointsUneJournee.get(i).getPoints()==maxPointsUneJournee) {
PointsJournee egalite = classementPointsUneJournee.get(i);
pointsUneJournee.add(egalite);
i++;
}
// Plus grand nombre de fois premier
- List<PointsSaison> classementFoisPremier = PointsSaison.find.where().eq("saison", saison).findList();
+ List<PointsSaison> classementFoisPremier = PointsSaison.find.where().eq("saison", saison).orderBy().desc("nbFoisPremier").findList();
i=1;
Integer maxFoisPremier = classementFoisPremier.get(0).getNbFoisPremier();
List<PointsSaison> nbFoisPremier = new ArrayList<PointsSaison>();
nbFoisPremier.add(classementFoisPremier.get(0));
while (classementFoisPremier.size()!=i && classementFoisPremier.get(i).getNbFoisPremier()==maxFoisPremier) {
PointsSaison egalite = classementFoisPremier.get(i);
nbFoisPremier.add(egalite);
i++;
}
return ok(statistiques.render(user, journeesPassees, journee, points, meilleurPronostiqueurs, mauvaisPronostiqueurs, pointsCorrectsJournee,
scoreCorrectsTotal, scoresCorrectsUneJournee, pointsUneJournee, nbFoisPremier));
}
}
| true | true | public static Result getStat(String id) {
Long idLong;
Date maintenant = new Date();
Sys_parameter system = Sys_parameter.find.byId((long) 1);
Saison saison = system.getSaisonEnCours();
Journee premiereJournee = saison.getPremiereJournee();
Journee derniereJournee= saison.getDerniereJournee();
List<Journee> journeesPassees = Journee.find.where().le("id", derniereJournee.getId()).ge("id", premiereJournee.getId()).lt("dateJournee", maintenant).orderBy().desc("dateJournee").findList();
if (id.equalsIgnoreCase("0")) {
idLong = journeesPassees.get(0).id;
} else {
idLong = Long.parseLong(id);
}
Utilisateur user = Utilisateur.findByPseudo(request().username());
Journee journee = Journee.find.byId(idLong);
Integer points = PointsSaison.find.where().eq("saison", saison).eq("user", user).findList().get(0).pointsTotalSaison;
// Meilleur pronostiqueur de la journée
List<PointsJournee> classementPronostiqueurJournee = PointsJournee.find.where().eq("journee", journee).orderBy().desc("points").findList();
Integer i=1;
Integer scorePremier = classementPronostiqueurJournee.get(0).getPoints();
List<PointsJournee> meilleurPronostiqueurs = new ArrayList<PointsJournee>();
meilleurPronostiqueurs.add(classementPronostiqueurJournee.get(0));
while (classementPronostiqueurJournee.size()!=i && classementPronostiqueurJournee.get(i).getPoints()==scorePremier) {
PointsJournee egalite = classementPronostiqueurJournee.get(i);
meilleurPronostiqueurs.add(egalite);
i++;
}
// Plus mauvais de la journée
List<PointsJournee> classementPronostiqueurAscJournee = PointsJournee.find.where().eq("journee", journee).orderBy().asc("points").findList();
i=1;
Integer scoreDernier = classementPronostiqueurAscJournee.get(0).getPoints();
List<PointsJournee> mauvaisPronostiqueurs = new ArrayList<PointsJournee>();
mauvaisPronostiqueurs.add(classementPronostiqueurAscJournee.get(0));
while (classementPronostiqueurAscJournee.size()!=i && classementPronostiqueurAscJournee.get(i).getPoints()==scoreDernier) {
PointsJournee egalite = classementPronostiqueurAscJournee.get(i);
mauvaisPronostiqueurs.add(egalite);
i++;
}
// Scores corrects journée
List<PointsJournee> classementPointsCorrectsJournee = PointsJournee.find.where().eq("journee", journee).orderBy().desc("scoresCorrects").findList();
i=1;
Integer scoreCorrectsJournee = classementPointsCorrectsJournee.get(0).getScoresCorrects();
List<PointsJournee> pointsCorrectsJournee = new ArrayList<PointsJournee>();
pointsCorrectsJournee.add(classementPointsCorrectsJournee.get(0));
while (classementPointsCorrectsJournee.size()!=i && classementPointsCorrectsJournee.get(i).getScoresCorrects()==scoreCorrectsJournee) {
PointsJournee egalite = classementPointsCorrectsJournee.get(i);
pointsCorrectsJournee.add(egalite);
i++;
}
// Plus grand nombre de scores corrects au total
List<PointsSaison> classementScoresCorrectsTotal = PointsSaison.find.where().eq("saison", saison).orderBy().desc("totalScoresCorrects").findList();
i=1;
Integer maxScoreCorrects = classementScoresCorrectsTotal.get(0).getTotalScoresCorrects();
List<PointsSaison> scoreCorrectsTotal = new ArrayList<PointsSaison>();
scoreCorrectsTotal.add(classementScoresCorrectsTotal.get(0));
while (classementScoresCorrectsTotal.size()!=i && classementScoresCorrectsTotal.get(i).getTotalScoresCorrects()==maxScoreCorrects) {
PointsSaison egalite = classementScoresCorrectsTotal.get(i);
scoreCorrectsTotal.add(egalite);
i++;
}
// Plus grand nombre de scores corrects en une journée
List<PointsJournee> classementScoreCorrectsUneJournee = PointsJournee.find.where().ge("journee",saison.getPremiereJournee()).
le("journee", saison.getDerniereJournee()).orderBy().desc("scoresCorrects").findList();
i=1;
Integer maxScoreCorrectsUneJournee = classementScoreCorrectsUneJournee.get(0).getScoresCorrects();
List<PointsJournee> scoresCorrectsUneJournee = new ArrayList<PointsJournee>();
scoresCorrectsUneJournee.add(classementScoreCorrectsUneJournee.get(0));
while (classementScoreCorrectsUneJournee.size()!=i && classementScoreCorrectsUneJournee.get(i).getScoresCorrects()==maxScoreCorrectsUneJournee) {
PointsJournee egalite = classementScoreCorrectsUneJournee.get(i);
scoresCorrectsUneJournee.add(egalite);
i++;
}
// Meilleur score en une journée
List<PointsJournee> classementPointsUneJournee = PointsJournee.find.where().ge("journee",saison.getPremiereJournee()).
le("journee", saison.getDerniereJournee()).orderBy().desc("points").findList();
i=1;
Integer maxPointsUneJournee = classementPointsUneJournee.get(0).getPoints();
List<PointsJournee> pointsUneJournee = new ArrayList<PointsJournee>();
pointsUneJournee.add(classementPointsUneJournee.get(0));
while (classementPointsUneJournee.size()!=i && classementPointsUneJournee.get(i).getPoints()==maxPointsUneJournee) {
PointsJournee egalite = classementPointsUneJournee.get(i);
pointsUneJournee.add(egalite);
i++;
}
// Plus grand nombre de fois premier
List<PointsSaison> classementFoisPremier = PointsSaison.find.where().eq("saison", saison).findList();
i=1;
Integer maxFoisPremier = classementFoisPremier.get(0).getNbFoisPremier();
List<PointsSaison> nbFoisPremier = new ArrayList<PointsSaison>();
nbFoisPremier.add(classementFoisPremier.get(0));
while (classementFoisPremier.size()!=i && classementFoisPremier.get(i).getNbFoisPremier()==maxFoisPremier) {
PointsSaison egalite = classementFoisPremier.get(i);
nbFoisPremier.add(egalite);
i++;
}
return ok(statistiques.render(user, journeesPassees, journee, points, meilleurPronostiqueurs, mauvaisPronostiqueurs, pointsCorrectsJournee,
scoreCorrectsTotal, scoresCorrectsUneJournee, pointsUneJournee, nbFoisPremier));
}
| public static Result getStat(String id) {
Long idLong;
Date maintenant = new Date();
Sys_parameter system = Sys_parameter.find.byId((long) 1);
Saison saison = system.getSaisonEnCours();
Journee premiereJournee = saison.getPremiereJournee();
Journee derniereJournee= saison.getDerniereJournee();
List<Journee> journeesPassees = Journee.find.where().le("id", derniereJournee.getId()).ge("id", premiereJournee.getId()).lt("dateJournee", maintenant).orderBy().desc("dateJournee").findList();
if (id.equalsIgnoreCase("0")) {
idLong = journeesPassees.get(0).id;
} else {
idLong = Long.parseLong(id);
}
Utilisateur user = Utilisateur.findByPseudo(request().username());
Journee journee = Journee.find.byId(idLong);
Integer points = PointsSaison.find.where().eq("saison", saison).eq("user", user).findList().get(0).pointsTotalSaison;
// Meilleur pronostiqueur de la journée
List<PointsJournee> classementPronostiqueurJournee = PointsJournee.find.where().eq("journee", journee).orderBy().desc("points").findList();
Integer i=1;
Integer scorePremier = classementPronostiqueurJournee.get(0).getPoints();
List<PointsJournee> meilleurPronostiqueurs = new ArrayList<PointsJournee>();
meilleurPronostiqueurs.add(classementPronostiqueurJournee.get(0));
while (classementPronostiqueurJournee.size()!=i && classementPronostiqueurJournee.get(i).getPoints()==scorePremier) {
PointsJournee egalite = classementPronostiqueurJournee.get(i);
meilleurPronostiqueurs.add(egalite);
i++;
}
// Plus mauvais de la journée
List<PointsJournee> classementPronostiqueurAscJournee = PointsJournee.find.where().eq("journee", journee).orderBy().asc("points").findList();
i=1;
Integer scoreDernier = classementPronostiqueurAscJournee.get(0).getPoints();
List<PointsJournee> mauvaisPronostiqueurs = new ArrayList<PointsJournee>();
mauvaisPronostiqueurs.add(classementPronostiqueurAscJournee.get(0));
while (classementPronostiqueurAscJournee.size()!=i && classementPronostiqueurAscJournee.get(i).getPoints()==scoreDernier) {
PointsJournee egalite = classementPronostiqueurAscJournee.get(i);
mauvaisPronostiqueurs.add(egalite);
i++;
}
// Scores corrects journée
List<PointsJournee> classementPointsCorrectsJournee = PointsJournee.find.where().eq("journee", journee).orderBy().desc("scoresCorrects").findList();
i=1;
Integer scoreCorrectsJournee = classementPointsCorrectsJournee.get(0).getScoresCorrects();
List<PointsJournee> pointsCorrectsJournee = new ArrayList<PointsJournee>();
pointsCorrectsJournee.add(classementPointsCorrectsJournee.get(0));
while (classementPointsCorrectsJournee.size()!=i && classementPointsCorrectsJournee.get(i).getScoresCorrects()==scoreCorrectsJournee) {
PointsJournee egalite = classementPointsCorrectsJournee.get(i);
pointsCorrectsJournee.add(egalite);
i++;
}
// Plus grand nombre de scores corrects au total
List<PointsSaison> classementScoresCorrectsTotal = PointsSaison.find.where().eq("saison", saison).orderBy().desc("totalScoresCorrects").findList();
i=1;
Integer maxScoreCorrects = classementScoresCorrectsTotal.get(0).getTotalScoresCorrects();
List<PointsSaison> scoreCorrectsTotal = new ArrayList<PointsSaison>();
scoreCorrectsTotal.add(classementScoresCorrectsTotal.get(0));
while (classementScoresCorrectsTotal.size()!=i && classementScoresCorrectsTotal.get(i).getTotalScoresCorrects()==maxScoreCorrects) {
PointsSaison egalite = classementScoresCorrectsTotal.get(i);
scoreCorrectsTotal.add(egalite);
i++;
}
// Plus grand nombre de scores corrects en une journée
List<PointsJournee> classementScoreCorrectsUneJournee = PointsJournee.find.where().ge("journee",saison.getPremiereJournee()).
le("journee", saison.getDerniereJournee()).orderBy().desc("scoresCorrects").findList();
i=1;
Integer maxScoreCorrectsUneJournee = classementScoreCorrectsUneJournee.get(0).getScoresCorrects();
List<PointsJournee> scoresCorrectsUneJournee = new ArrayList<PointsJournee>();
scoresCorrectsUneJournee.add(classementScoreCorrectsUneJournee.get(0));
while (classementScoreCorrectsUneJournee.size()!=i && classementScoreCorrectsUneJournee.get(i).getScoresCorrects()==maxScoreCorrectsUneJournee) {
PointsJournee egalite = classementScoreCorrectsUneJournee.get(i);
scoresCorrectsUneJournee.add(egalite);
i++;
}
// Meilleur score en une journée
List<PointsJournee> classementPointsUneJournee = PointsJournee.find.where().ge("journee",saison.getPremiereJournee()).
le("journee", saison.getDerniereJournee()).orderBy().desc("points").findList();
i=1;
Integer maxPointsUneJournee = classementPointsUneJournee.get(0).getPoints();
List<PointsJournee> pointsUneJournee = new ArrayList<PointsJournee>();
pointsUneJournee.add(classementPointsUneJournee.get(0));
while (classementPointsUneJournee.size()!=i && classementPointsUneJournee.get(i).getPoints()==maxPointsUneJournee) {
PointsJournee egalite = classementPointsUneJournee.get(i);
pointsUneJournee.add(egalite);
i++;
}
// Plus grand nombre de fois premier
List<PointsSaison> classementFoisPremier = PointsSaison.find.where().eq("saison", saison).orderBy().desc("nbFoisPremier").findList();
i=1;
Integer maxFoisPremier = classementFoisPremier.get(0).getNbFoisPremier();
List<PointsSaison> nbFoisPremier = new ArrayList<PointsSaison>();
nbFoisPremier.add(classementFoisPremier.get(0));
while (classementFoisPremier.size()!=i && classementFoisPremier.get(i).getNbFoisPremier()==maxFoisPremier) {
PointsSaison egalite = classementFoisPremier.get(i);
nbFoisPremier.add(egalite);
i++;
}
return ok(statistiques.render(user, journeesPassees, journee, points, meilleurPronostiqueurs, mauvaisPronostiqueurs, pointsCorrectsJournee,
scoreCorrectsTotal, scoresCorrectsUneJournee, pointsUneJournee, nbFoisPremier));
}
|
diff --git a/src/share/impl/contentstore/classes/com/sun/jumpimpl/module/contentstore/FileStoreImpl.java b/src/share/impl/contentstore/classes/com/sun/jumpimpl/module/contentstore/FileStoreImpl.java
index f90567a..7c3503f 100644
--- a/src/share/impl/contentstore/classes/com/sun/jumpimpl/module/contentstore/FileStoreImpl.java
+++ b/src/share/impl/contentstore/classes/com/sun/jumpimpl/module/contentstore/FileStoreImpl.java
@@ -1,326 +1,326 @@
/*
* %W% %E%
*
* Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program 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 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 version 2 for more details (a copy is
* included at /legal/license.txt).
*
* 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 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.jumpimpl.module.contentstore;
import java.io.File;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import com.sun.jump.module.contentstore.*;
public class FileStoreImpl extends JUMPStore {
//HashMap jumpNodeLists = new HashMap(); // uri, JUMPNode.List
boolean verbose = false;
public void load(Map map) {
Object basedir;
if ((basedir = System.getProperty("contentstore.root")) != null) {
setStoreRoot((String)basedir);
} else if (map != null && (basedir = map.get("contentstore.root")) != null) {
setStoreRoot((String)basedir);
} else {
setStoreRoot(".");
}
}
public void unload() {
}
public void createDataNode(String uri, JUMPData jumpData) throws IOException {
File file = uriToDataFile(uri);
File parentFile = file.getParentFile();
writeToFile(file, jumpData);
}
public void createNode(String uri) throws IOException {
File file = uriToListFile(uri);
file.mkdirs();
if (!file.exists())
throw new IOException("Could not create: " + file);
}
public JUMPNode getNode(String uri) throws IOException {
// getNode(String) needs to return what the createDataNode() above store
// if the uri parameter represents a data node.
//System.out.println("getNode uri:" + uri);
if (!isDataUri(uri)) {
// This URI represents non-leaf node.
// No caching for now - might want to optimize in the future.
//JUMPNode node = (JUMPNode) jumpNodeLists.get(uri);
//if (node == null) {
// synchronized(jumpNodeLists) {
// node = new JUMPNodeListImpl("list", uri);
// jumpNodeLists.put(uri, node);
// }
//}
return new JUMPNodeListImpl("list", uri);
} else {
try {
File file = uriToDataFile(uri);
String name = getDataNodeName(uri);
if (!file.isHidden()) { // Don't make a node for hidden system files
JUMPData dataObject = readFromFile(file, name);
- JUMPNode node = new JUMPNodeDataImpl(uri, name, dataObject);
+ JUMPNode node = new JUMPNodeDataImpl(name, uri, dataObject);
return node;
}
} catch (IOException e) {
if (verbose)
System.err.println(e); // need to do something about exceptions
}
}
return null;
}
protected void updateDataNode (String uri, JUMPData data)
throws IOException {
createDataNode(uri, data);
}
public void deleteNode(String uri) {
File file = uriToListFile(uri);
deleteFile(file, true);
}
// deletes everything under this file
private boolean deleteFile(File file, boolean success) {
if (file.isDirectory()) {
File[] list = file.listFiles();
for (int i = 0; i < list.length; i++) {
deleteFile(list[i], success);
}
}
success = file.delete() & success;
return success;
}
String root; // The real path to the store root.
protected void setStoreRoot(String root) {
File file = new File(root);
if (file.exists()) {
this.root = file.getAbsolutePath();
return;
}
// What to do about error checking?
throw new RuntimeException("Cannot set persistent store, "+
"repositoryDir="+root+" does not exist");
}
protected File uriToDataFile(String uri) {
String absolutePath = convertToAbsolutePath(uri, true);
return new File(absolutePath + File.separatorChar + getDataNodeName(uri));
}
protected File uriToListFile(String uri) {
String absolutePath = convertToAbsolutePath(uri, false);
return new File(absolutePath);
}
private String getDataNodeName(String uri) {
return uri.substring(uri.lastIndexOf(File.separatorChar) + 1);
}
private void writeToFile(File file, JUMPData data) throws IOException {
int dataFormat = data.getFormat();
Object rawDataValue = data.getValue();
// Special processing for the java.util.Properties format
if (file.getPath().endsWith(".properties")) {
Properties prop = (Properties) rawDataValue;
prop.store(new FileOutputStream(file),
"Generated by " + this.getClass().getName());
} else {
// All other cases, simply write out the format, then serialized data.
ObjectOutputStream oout = new ObjectOutputStream(new FileOutputStream(file));
oout.writeInt(dataFormat);
oout.writeObject(rawDataValue);
oout.close();
}
}
private JUMPData readFromFile(File file, String fileName) throws IOException {
int format;
Object value;
// Special processing for the java.util.Properties format
if (fileName.endsWith(".properties")) {
format = JUMPData.FORMAT_SERIALIZABLE;
Properties prop = new Properties();
prop.load(new FileInputStream(file));
value = prop;
} else {
// All other cases, simply read in the format, then deserialized data.
try {
ObjectInputStream oin = new ObjectInputStream(new FileInputStream(file));
format = oin.readInt();
value = oin.readObject();
} catch (java.io.StreamCorruptedException e) {
// this means we ran into a file format that's not JUMPNode.Data.
throw new IOException("Failed to create JUMPNode.Data from " + file.getName());
} catch (ClassNotFoundException e) { // can't happen!
e.printStackTrace();
return null;
}
}
return new JUMPData(value, format);
}
/*
* URI string need to start with ".". Any other restrictions?
* If isDataUri boolean param is true, then the uri represents a leaf node
* and the absolute uri returns the value with the last item trimmed down
* ex. convertToAbsolutePath("./apps/App1", false) and
* convertToAbsolutePath("./apps/App1/title", true) will both yield
* "<root dir>/apps/App1" as a return value.
**/
private String convertToAbsolutePath(String uri, boolean isData) {
if (!uri.startsWith("."))
throw new IllegalArgumentException("Malformed uri, " + uri);
String pathUri;
if (isData) {
pathUri = root.concat(uri.substring(1, uri.lastIndexOf(File.separatorChar)));
} else {
pathUri = root.concat(uri.substring(1));
}
return pathUri;
}
private boolean isDataUri(String uri) {
if (!uri.startsWith("."))
return false;
String absolutePath = convertToAbsolutePath(uri, false);
File file = new File(absolutePath);
if (file.exists() && file.isDirectory())
return false;
// need a check on data file exists here.
return true;
}
class JUMPNodeDataImpl implements JUMPNode.Data {
JUMPData data;
String name;
String uri;
JUMPNodeDataImpl(String name, String uri, JUMPData data) {
this.name = name;
this.uri = uri;
this.data = data;
}
public boolean containsData() { return true; }
public String getName() { return name; }
public String getURI() { return uri; }
public JUMPData getData() { return data; }
public String toString() {
return "JUMPNode.Data (" + name + "," + uri + "," + data + ")";
}
public boolean equals(Object obj) {
if (!(obj instanceof JUMPNode.Data)) return false;
JUMPNode.Data other = (JUMPNode.Data) obj;
return (name.equals(other.getName())
&& uri.equals(other.getURI())
&& data.equals(other.getData()));
}
}
class JUMPNodeListImpl implements JUMPNode.List {
String name;
String uri;
ArrayList children;
JUMPNodeListImpl(String name, String uri) {
this.name = name;
this.uri = uri;
}
public boolean containsData() { return false; }
public String getName() { return name; }
public String getURI() { return uri; }
public Iterator getChildren() {
//if (children == null) { // should we cache? What if dir content changes?
children = new ArrayList();
File file = uriToListFile(uri);
String[] names = file.list();
for (int i = 0; names != null && i < names.length; i++) {
try {
JUMPNode node = getNode(uri + File.separatorChar + names[i]);
if (node != null)
children.add(node);
} catch (IOException e) {}
}
//}
return children.iterator();
}
public String toString() {
return "JUMPNode.List (" + name + "," + uri + ")";
}
public boolean equals(Object obj) {
if (!(obj instanceof JUMPNode.List)) return false;
JUMPNode.List other = (JUMPNode.List) obj;
return (name.equals(other.getName()) && uri.equals(other.getURI()));
}
}
}
| true | true | public JUMPNode getNode(String uri) throws IOException {
// getNode(String) needs to return what the createDataNode() above store
// if the uri parameter represents a data node.
//System.out.println("getNode uri:" + uri);
if (!isDataUri(uri)) {
// This URI represents non-leaf node.
// No caching for now - might want to optimize in the future.
//JUMPNode node = (JUMPNode) jumpNodeLists.get(uri);
//if (node == null) {
// synchronized(jumpNodeLists) {
// node = new JUMPNodeListImpl("list", uri);
// jumpNodeLists.put(uri, node);
// }
//}
return new JUMPNodeListImpl("list", uri);
} else {
try {
File file = uriToDataFile(uri);
String name = getDataNodeName(uri);
if (!file.isHidden()) { // Don't make a node for hidden system files
JUMPData dataObject = readFromFile(file, name);
JUMPNode node = new JUMPNodeDataImpl(uri, name, dataObject);
return node;
}
} catch (IOException e) {
if (verbose)
System.err.println(e); // need to do something about exceptions
}
}
return null;
}
| public JUMPNode getNode(String uri) throws IOException {
// getNode(String) needs to return what the createDataNode() above store
// if the uri parameter represents a data node.
//System.out.println("getNode uri:" + uri);
if (!isDataUri(uri)) {
// This URI represents non-leaf node.
// No caching for now - might want to optimize in the future.
//JUMPNode node = (JUMPNode) jumpNodeLists.get(uri);
//if (node == null) {
// synchronized(jumpNodeLists) {
// node = new JUMPNodeListImpl("list", uri);
// jumpNodeLists.put(uri, node);
// }
//}
return new JUMPNodeListImpl("list", uri);
} else {
try {
File file = uriToDataFile(uri);
String name = getDataNodeName(uri);
if (!file.isHidden()) { // Don't make a node for hidden system files
JUMPData dataObject = readFromFile(file, name);
JUMPNode node = new JUMPNodeDataImpl(name, uri, dataObject);
return node;
}
} catch (IOException e) {
if (verbose)
System.err.println(e); // need to do something about exceptions
}
}
return null;
}
|
diff --git a/agent/src/main/java/org/whitesource/teamcity/agent/WhitesourceLifeCycleListener.java b/agent/src/main/java/org/whitesource/teamcity/agent/WhitesourceLifeCycleListener.java
index 0a23dc0..2b1a16e 100644
--- a/agent/src/main/java/org/whitesource/teamcity/agent/WhitesourceLifeCycleListener.java
+++ b/agent/src/main/java/org/whitesource/teamcity/agent/WhitesourceLifeCycleListener.java
@@ -1,260 +1,260 @@
/**
* Copyright (C) 2012 White 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 org.whitesource.teamcity.agent;
import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.ExtensionHolder;
import jetbrains.buildServer.agent.*;
import jetbrains.buildServer.log.Loggers;
import jetbrains.buildServer.util.EventDispatcher;
import jetbrains.buildServer.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.CollectionUtils;
import org.whitesource.agent.api.dispatch.CheckPoliciesResult;
import org.whitesource.agent.api.dispatch.UpdateInventoryResult;
import org.whitesource.agent.api.model.AgentProjectInfo;
import org.whitesource.agent.api.model.DependencyInfo;
import org.whitesource.agent.client.WhitesourceService;
import org.whitesource.agent.client.WssServiceException;
import org.whitesource.agent.report.PolicyCheckReport;
import org.whitesource.teamcity.common.Constants;
import org.whitesource.teamcity.common.WssUtils;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* @author Edo.Shor
*/
public class WhitesourceLifeCycleListener extends AgentLifeCycleAdapter {
/* --- Static members --- */
private static final String LOG_COMPONENT = "LifeCycleListener";
private ExtensionHolder extensionHolder;
/* --- Constructors --- */
/**
* Constructor
*/
public WhitesourceLifeCycleListener(@NotNull final EventDispatcher<AgentLifeCycleListener> eventDispatcher,
@NotNull final ExtensionHolder extensionHolder) {
this.extensionHolder = extensionHolder;
eventDispatcher.addListener(this);
}
@Override
public void agentInitialized(@NotNull BuildAgent agent) {
super.agentInitialized(agent);
Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT, "initialized"));
}
/* --- Interface implementation methods --- */
@Override
public void beforeRunnerStart(@NotNull BuildRunnerContext runner) {
super.beforeRunnerStart(runner);
if (shouldUpdate(runner)) {
Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT, "before runner start "
+ runner.getBuild().getProjectName() + " type " + runner.getName()));
}
}
@Override
public void runnerFinished(@NotNull BuildRunnerContext runner, @NotNull BuildFinishedStatus status) {
super.runnerFinished(runner, status);
AgentRunningBuild build = runner.getBuild();
Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT, "runner finished " + build.getProjectName() + " type " + runner.getName()));
if (!shouldUpdate(runner)) { return; } // no need to update white source...
final BuildProgressLogger buildLogger = build.getBuildLogger();
buildLogger.message("Updating White Source");
// make sure we have an organization token
Map<String, String> runnerParameters = runner.getRunnerParameters();
String orgToken = runnerParameters.get(Constants.RUNNER_OVERRIDE_ORGANIZATION_TOKEN);
if (StringUtil.isEmptyOrSpaces(orgToken)) {
orgToken = runnerParameters.get(Constants.RUNNER_ORGANIZATION_TOKEN);
}
if (StringUtil.isEmptyOrSpaces(orgToken)) {
stopBuildOnError((AgentRunningBuildEx) build,
new IllegalStateException("Empty organization token. Please make sure an organization token is defined for this runner"));
return;
}
// should we check policies first ?
boolean shouldCheckPolicies;
String overrideCheckPolicies = runnerParameters.get(Constants.RUNNER_OVERRIDE_CHECK_POLICIES);
if (StringUtils.isBlank(overrideCheckPolicies) ||
"global".equals(overrideCheckPolicies)) {
shouldCheckPolicies = Boolean.parseBoolean(runnerParameters.get(Constants.RUNNER_CHECK_POLICIES));
} else {
- shouldCheckPolicies = "enabled".equals(overrideCheckPolicies);
+ shouldCheckPolicies = "enable".equals(overrideCheckPolicies);
}
String product = runnerParameters.get(Constants.RUNNER_PRODUCT);
String productVersion = runnerParameters.get(Constants.RUNNER_PRODUCT_VERSION);
// collect OSS usage information
buildLogger.message("Collecting OSS usage information");
Collection<AgentProjectInfo> projectInfos;
if (WssUtils.isMavenRunType(runner.getRunType())) {
MavenOssInfoExtractor extractor = new MavenOssInfoExtractor(runner);
projectInfos = extractor.extract();
if (StringUtil.isEmptyOrSpaces(product)) {
product = extractor.getTopMostProjectName();
}
} else {
GenericOssInfoExtractor extractor = new GenericOssInfoExtractor(runner);
projectInfos = extractor.extract();
}
debugAgentProjectInfos(projectInfos);
// send to white source
if (CollectionUtils.isEmpty(projectInfos)) {
buildLogger.message("No open source information found.");
} else {
WhitesourceService service = createServiceClient(runner);
try{
if (shouldCheckPolicies) {
buildLogger.message("Checking policies");
CheckPoliciesResult result = service.checkPolicies(orgToken, product, productVersion, projectInfos);
policyCheckReport(runner, result);
if (result.hasRejections()) {
stopBuild((AgentRunningBuildEx) build, "Open source rejected by organization policies.");
} else {
buildLogger.message("All dependencies conform with open source policies.");
sendUpdate(orgToken, product, productVersion, projectInfos, service, buildLogger);
}
} else {
sendUpdate(orgToken, product, productVersion, projectInfos, service, buildLogger);
}
} catch (WssServiceException e) {
stopBuildOnError((AgentRunningBuildEx) build, e);
} catch (IOException e) {
stopBuildOnError((AgentRunningBuildEx) build, e);
} catch (RuntimeException e) {
Loggers.AGENT.error(WssUtils.logMsg(LOG_COMPONENT, "Runtime Error"), e);
stopBuildOnError((AgentRunningBuildEx) build, e);
} finally {
service.shutdown();
}
}
}
private void policyCheckReport(BuildRunnerContext runner, CheckPoliciesResult result) throws IOException {
AgentRunningBuild build = runner.getBuild();
PolicyCheckReport report = new PolicyCheckReport(result, build.getProjectName(), build.getBuildNumber());
File reportArchive = report.generate(build.getBuildTempDirectory(), true);
ArtifactsPublisher publisher = extensionHolder.getExtensions(ArtifactsPublisher.class).iterator().next();
Map<File, String> artifactsToPublish = new HashMap<File, String>();
artifactsToPublish.put(reportArchive, "");
publisher.publishFiles(artifactsToPublish);
}
/* --- Private methods --- */
private boolean shouldUpdate(BuildRunnerContext runner) {
String shouldUpdate = runner.getRunnerParameters().get(Constants.RUNNER_DO_UPDATE);
return !StringUtil.isEmptyOrSpaces(shouldUpdate) && Boolean.parseBoolean(shouldUpdate);
}
private WhitesourceService createServiceClient(BuildRunnerContext runner) {
Map<String, String> runnerParameters = runner.getRunnerParameters();
String serviceUrl = runnerParameters.get(Constants.RUNNER_SERVICE_URL);
WhitesourceService service = new WhitesourceService(Constants.AGENT_TYPE, Constants.AGENT_VERSION, serviceUrl);
String proxyHost = runnerParameters.get(Constants.RUNNER_PROXY_HOST);
if (!StringUtil.isEmptyOrSpaces(proxyHost)) {
int port = Integer.parseInt(runnerParameters.get(Constants.RUNNER_PROXY_PORT));
String username = runnerParameters.get(Constants.RUNNER_PROXY_USERNAME);
String password = runnerParameters.get(Constants.RUNNER_PROXY_PASSWORD);
service.getClient().setProxy(proxyHost, port, username, password);
}
return service;
}
private void sendUpdate(String orgToken, String product, String productVersion, Collection<AgentProjectInfo> projectInfos,
WhitesourceService service, BuildProgressLogger buildLogger)
throws WssServiceException {
buildLogger.message("Sending to White Source");
UpdateInventoryResult updateResult = service.update(orgToken, product, productVersion, projectInfos);
logUpdateResult(updateResult, buildLogger);
}
private void logUpdateResult(UpdateInventoryResult result, BuildProgressLogger logger) {
Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT, "update success"));
logger.message("White Source update results: ");
logger.message("White Source organization: " + result.getOrganization());
logger.message(result.getCreatedProjects().size() + " Newly created projects:");
logger.message(StringUtil.join(result.getCreatedProjects(), ","));
logger.message(result.getUpdatedProjects().size() + " existing projects were updated:");
logger.message(StringUtil.join(result.getUpdatedProjects(), ","));
}
private void stopBuildOnError(AgentRunningBuildEx build, Exception e) {
Loggers.AGENT.warn(WssUtils.logMsg(LOG_COMPONENT, "Stopping build"), e);
BuildProgressLogger logger = build.getBuildLogger();
String errorMessage = e.getLocalizedMessage();
logger.buildFailureDescription(errorMessage);
logger.exception(e);
logger.flush();
build.stopBuild(errorMessage);
}
private void stopBuild(AgentRunningBuildEx build, String message) {
Loggers.AGENT.warn(WssUtils.logMsg(LOG_COMPONENT, "Stopping build: + message"));
BuildProgressLogger logger = build.getBuildLogger();
logger.buildFailureDescription(message);
logger.flush();
build.stopBuild(message);
}
private void debugAgentProjectInfos(Collection<AgentProjectInfo> projectInfos) {
final Logger log = Loggers.AGENT;
log.info("----------------- dumping projectInfos -----------------");
log.info("Total number of projects : " + projectInfos.size());
for (AgentProjectInfo projectInfo : projectInfos) {
log.info("Project coordiantes: " + projectInfo.getCoordinates());
log.info("Project parent coordiantes: " + projectInfo.getParentCoordinates());
Collection<DependencyInfo> dependencies = projectInfo.getDependencies();
log.info("total # of dependencies: " + dependencies.size());
for (DependencyInfo info : dependencies) {
log.info(info + " SHA-1: " + info.getSha1());
}
}
log.info("----------------- dump finished -----------------");
}
}
| true | true | public void runnerFinished(@NotNull BuildRunnerContext runner, @NotNull BuildFinishedStatus status) {
super.runnerFinished(runner, status);
AgentRunningBuild build = runner.getBuild();
Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT, "runner finished " + build.getProjectName() + " type " + runner.getName()));
if (!shouldUpdate(runner)) { return; } // no need to update white source...
final BuildProgressLogger buildLogger = build.getBuildLogger();
buildLogger.message("Updating White Source");
// make sure we have an organization token
Map<String, String> runnerParameters = runner.getRunnerParameters();
String orgToken = runnerParameters.get(Constants.RUNNER_OVERRIDE_ORGANIZATION_TOKEN);
if (StringUtil.isEmptyOrSpaces(orgToken)) {
orgToken = runnerParameters.get(Constants.RUNNER_ORGANIZATION_TOKEN);
}
if (StringUtil.isEmptyOrSpaces(orgToken)) {
stopBuildOnError((AgentRunningBuildEx) build,
new IllegalStateException("Empty organization token. Please make sure an organization token is defined for this runner"));
return;
}
// should we check policies first ?
boolean shouldCheckPolicies;
String overrideCheckPolicies = runnerParameters.get(Constants.RUNNER_OVERRIDE_CHECK_POLICIES);
if (StringUtils.isBlank(overrideCheckPolicies) ||
"global".equals(overrideCheckPolicies)) {
shouldCheckPolicies = Boolean.parseBoolean(runnerParameters.get(Constants.RUNNER_CHECK_POLICIES));
} else {
shouldCheckPolicies = "enabled".equals(overrideCheckPolicies);
}
String product = runnerParameters.get(Constants.RUNNER_PRODUCT);
String productVersion = runnerParameters.get(Constants.RUNNER_PRODUCT_VERSION);
// collect OSS usage information
buildLogger.message("Collecting OSS usage information");
Collection<AgentProjectInfo> projectInfos;
if (WssUtils.isMavenRunType(runner.getRunType())) {
MavenOssInfoExtractor extractor = new MavenOssInfoExtractor(runner);
projectInfos = extractor.extract();
if (StringUtil.isEmptyOrSpaces(product)) {
product = extractor.getTopMostProjectName();
}
} else {
GenericOssInfoExtractor extractor = new GenericOssInfoExtractor(runner);
projectInfos = extractor.extract();
}
debugAgentProjectInfos(projectInfos);
// send to white source
if (CollectionUtils.isEmpty(projectInfos)) {
buildLogger.message("No open source information found.");
} else {
WhitesourceService service = createServiceClient(runner);
try{
if (shouldCheckPolicies) {
buildLogger.message("Checking policies");
CheckPoliciesResult result = service.checkPolicies(orgToken, product, productVersion, projectInfos);
policyCheckReport(runner, result);
if (result.hasRejections()) {
stopBuild((AgentRunningBuildEx) build, "Open source rejected by organization policies.");
} else {
buildLogger.message("All dependencies conform with open source policies.");
sendUpdate(orgToken, product, productVersion, projectInfos, service, buildLogger);
}
} else {
sendUpdate(orgToken, product, productVersion, projectInfos, service, buildLogger);
}
} catch (WssServiceException e) {
stopBuildOnError((AgentRunningBuildEx) build, e);
} catch (IOException e) {
stopBuildOnError((AgentRunningBuildEx) build, e);
} catch (RuntimeException e) {
Loggers.AGENT.error(WssUtils.logMsg(LOG_COMPONENT, "Runtime Error"), e);
stopBuildOnError((AgentRunningBuildEx) build, e);
} finally {
service.shutdown();
}
}
}
| public void runnerFinished(@NotNull BuildRunnerContext runner, @NotNull BuildFinishedStatus status) {
super.runnerFinished(runner, status);
AgentRunningBuild build = runner.getBuild();
Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT, "runner finished " + build.getProjectName() + " type " + runner.getName()));
if (!shouldUpdate(runner)) { return; } // no need to update white source...
final BuildProgressLogger buildLogger = build.getBuildLogger();
buildLogger.message("Updating White Source");
// make sure we have an organization token
Map<String, String> runnerParameters = runner.getRunnerParameters();
String orgToken = runnerParameters.get(Constants.RUNNER_OVERRIDE_ORGANIZATION_TOKEN);
if (StringUtil.isEmptyOrSpaces(orgToken)) {
orgToken = runnerParameters.get(Constants.RUNNER_ORGANIZATION_TOKEN);
}
if (StringUtil.isEmptyOrSpaces(orgToken)) {
stopBuildOnError((AgentRunningBuildEx) build,
new IllegalStateException("Empty organization token. Please make sure an organization token is defined for this runner"));
return;
}
// should we check policies first ?
boolean shouldCheckPolicies;
String overrideCheckPolicies = runnerParameters.get(Constants.RUNNER_OVERRIDE_CHECK_POLICIES);
if (StringUtils.isBlank(overrideCheckPolicies) ||
"global".equals(overrideCheckPolicies)) {
shouldCheckPolicies = Boolean.parseBoolean(runnerParameters.get(Constants.RUNNER_CHECK_POLICIES));
} else {
shouldCheckPolicies = "enable".equals(overrideCheckPolicies);
}
String product = runnerParameters.get(Constants.RUNNER_PRODUCT);
String productVersion = runnerParameters.get(Constants.RUNNER_PRODUCT_VERSION);
// collect OSS usage information
buildLogger.message("Collecting OSS usage information");
Collection<AgentProjectInfo> projectInfos;
if (WssUtils.isMavenRunType(runner.getRunType())) {
MavenOssInfoExtractor extractor = new MavenOssInfoExtractor(runner);
projectInfos = extractor.extract();
if (StringUtil.isEmptyOrSpaces(product)) {
product = extractor.getTopMostProjectName();
}
} else {
GenericOssInfoExtractor extractor = new GenericOssInfoExtractor(runner);
projectInfos = extractor.extract();
}
debugAgentProjectInfos(projectInfos);
// send to white source
if (CollectionUtils.isEmpty(projectInfos)) {
buildLogger.message("No open source information found.");
} else {
WhitesourceService service = createServiceClient(runner);
try{
if (shouldCheckPolicies) {
buildLogger.message("Checking policies");
CheckPoliciesResult result = service.checkPolicies(orgToken, product, productVersion, projectInfos);
policyCheckReport(runner, result);
if (result.hasRejections()) {
stopBuild((AgentRunningBuildEx) build, "Open source rejected by organization policies.");
} else {
buildLogger.message("All dependencies conform with open source policies.");
sendUpdate(orgToken, product, productVersion, projectInfos, service, buildLogger);
}
} else {
sendUpdate(orgToken, product, productVersion, projectInfos, service, buildLogger);
}
} catch (WssServiceException e) {
stopBuildOnError((AgentRunningBuildEx) build, e);
} catch (IOException e) {
stopBuildOnError((AgentRunningBuildEx) build, e);
} catch (RuntimeException e) {
Loggers.AGENT.error(WssUtils.logMsg(LOG_COMPONENT, "Runtime Error"), e);
stopBuildOnError((AgentRunningBuildEx) build, e);
} finally {
service.shutdown();
}
}
}
|
diff --git a/src/frankversnel/processing/component/ComponentNotFoundException.java b/src/frankversnel/processing/component/ComponentNotFoundException.java
index 589e41b..300288a 100644
--- a/src/frankversnel/processing/component/ComponentNotFoundException.java
+++ b/src/frankversnel/processing/component/ComponentNotFoundException.java
@@ -1,17 +1,17 @@
package frankversnel.processing.component;
import frankversnel.processing.GameObject;
public class ComponentNotFoundException extends Exception {
/**
*
*/
private static final long serialVersionUID = -8863053240768908484L;
public <T extends Component> ComponentNotFoundException(Class<T> componentType,
GameObject gameObject) {
- super("Component of type " + componentType.getClass() +
- " could not be fournd for " + gameObject);
+ super("Component of type " + componentType +
+ " could not be found for " + gameObject);
}
}
| true | true | public <T extends Component> ComponentNotFoundException(Class<T> componentType,
GameObject gameObject) {
super("Component of type " + componentType.getClass() +
" could not be fournd for " + gameObject);
}
| public <T extends Component> ComponentNotFoundException(Class<T> componentType,
GameObject gameObject) {
super("Component of type " + componentType +
" could not be found for " + gameObject);
}
|
diff --git a/gameoflife-core/src/main/java/com/wakaleo/gameoflife/domain/GridWriter.java b/gameoflife-core/src/main/java/com/wakaleo/gameoflife/domain/GridWriter.java
index 834b4af..c78f444 100644
--- a/gameoflife-core/src/main/java/com/wakaleo/gameoflife/domain/GridWriter.java
+++ b/gameoflife-core/src/main/java/com/wakaleo/gameoflife/domain/GridWriter.java
@@ -1,15 +1,18 @@
package com.wakaleo.gameoflife.domain;
public class GridWriter {
public String convertToString(Cell[][] gridContents) {
StringBuffer printedGrid = new StringBuffer();
for(Cell[] row : gridContents) {
for( Cell cell : row) {
printedGrid.append(cell.toString());
}
- printedGrid.append("\n");
+ // TODO: This simply masks the problem: why empty rows being passed?
+ if(row.length > 0) {
+ printedGrid.append("\n");
+ }
}
return printedGrid.toString();
}
}
| true | true | public String convertToString(Cell[][] gridContents) {
StringBuffer printedGrid = new StringBuffer();
for(Cell[] row : gridContents) {
for( Cell cell : row) {
printedGrid.append(cell.toString());
}
printedGrid.append("\n");
}
return printedGrid.toString();
}
| public String convertToString(Cell[][] gridContents) {
StringBuffer printedGrid = new StringBuffer();
for(Cell[] row : gridContents) {
for( Cell cell : row) {
printedGrid.append(cell.toString());
}
// TODO: This simply masks the problem: why empty rows being passed?
if(row.length > 0) {
printedGrid.append("\n");
}
}
return printedGrid.toString();
}
|
diff --git a/src/main/java/fi/csc/microarray/analyser/ws/impl/EnfinWsUtils.java b/src/main/java/fi/csc/microarray/analyser/ws/impl/EnfinWsUtils.java
index ac19f00f5..35074b61b 100644
--- a/src/main/java/fi/csc/microarray/analyser/ws/impl/EnfinWsUtils.java
+++ b/src/main/java/fi/csc/microarray/analyser/ws/impl/EnfinWsUtils.java
@@ -1,299 +1,299 @@
package fi.csc.microarray.analyser.ws.impl;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.TransformerException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import fi.csc.microarray.analyser.ws.HtmlUtil;
import fi.csc.microarray.analyser.ws.ResultTableCollector;
import fi.csc.microarray.analyser.ws.HtmlUtil.ValueHtmlFormatter;
import fi.csc.microarray.util.XmlUtil;
public class EnfinWsUtils {
static interface AnnotationIdentifier {
boolean isAnnotation(Element setElement);
}
static interface AnnotationNameFinder {
String findAnnotationName(Element setElement);
}
public static void main(String[] args) throws SAXException, ParserConfigurationException, TransformerException, SOAPException, IOException {
String[] probes = new String[] {
"204704_s_at",
"221589_s_at",
"206065_s_at",
"209459_s_at",
"209460_at",
"206024_at",
"205719_s_at",
"205892_s_at",
"202036_s_at",
"206054_at",
"209443_at"
};
//String[] probes = JavaJobUtils.getProbes(new File("/home/akallio/two-sample.tsv"));
ResultTableCollector intactAnnotations = queryIntact(probes);
writeIntactHtml(intactAnnotations, new File("intact.html"));
ResultTableCollector reactomeAnnotations = queryReactome(probes);
writeReactomeHtml(reactomeAnnotations, new File("reactome.html"));
}
- private static void writeIntactHtml(ResultTableCollector intactAnnotations, File file) throws FileNotFoundException {
+ public static void writeIntactHtml(ResultTableCollector intactAnnotations, File file) throws FileNotFoundException {
ValueHtmlFormatter interactionIdFormatter = new ValueHtmlFormatter() {
public String format(String string, String[] currentRow) {
return "<a href=\"http://www.ebi.ac.uk/intact/pages/interactions/interactions.xhtml?conversationContext=1&queryTxt=" + string.replace(' ', '+') + "\">" + string + "</a>";
}
};
ValueHtmlFormatter uniprotFormatter = new ValueHtmlFormatter() {
public String format(String string, String[] currentRow) {
String formatted = "";
for (String protein : string.split(" ")) {
formatted += "<a href=\"http://www.uniprot.org/uniprot/" + protein.replace(' ', '+') + "\">" + protein + "</a> ";
}
return formatted;
}
};
HtmlUtil.writeHtmlTable(intactAnnotations, new String[] {"Name", "Probe IDs", "Participants"}, new String[] {"Interaction", "Probe ID", "Interacting proteins"}, new HtmlUtil.ValueHtmlFormatter[] {interactionIdFormatter, HtmlUtil.NO_FORMATTING_FORMATTER, uniprotFormatter}, "IntAct protein interactions", new FileOutputStream(file));
}
public static void writeReactomeHtml(ResultTableCollector reactomeAnnotations, File htmlOutput) throws FileNotFoundException {
ValueHtmlFormatter pathwayNameFormatter = new ValueHtmlFormatter() {
public String format(String string, String[] currentRow) {
return "<a href=\"http://www.reactome.org/cgi-bin/search2?DB=gk_current&OPERATOR=ALL&QUERY=" + string.replace(' ', '+') + "&SPECIES=&SUBMIT=Go!\">" + string + "</a>";
}
};
HtmlUtil.writeHtmlTable(reactomeAnnotations, new String[] { "Name", "Probe IDs" }, new String[] {"Pathway", "Probe ID's for participating proteins"}, new HtmlUtil.ValueHtmlFormatter[] {pathwayNameFormatter, HtmlUtil.NO_FORMATTING_FORMATTER}, "Reactome pathway associations", new FileOutputStream(htmlOutput));
}
public static ResultTableCollector queryIntact(String[] probes) throws SOAPException, MalformedURLException, SAXException, IOException, ParserConfigurationException, TransformerException {
Document uniprotResponse = queryUniprotIds(probes);
// query IntAct with UniProt identifiers
SOAPMessage intactSoapMessage = initialiseSoapMessage();
SOAPBody intactSoapBody = initialiseSoapBody(intactSoapMessage);
attachEnfinXml(intactSoapBody, fetchEnfinXml(uniprotResponse), "findPartners", "http://ebi.ac.uk/enfin/core/web/services/intact");
Document intactResponse = sendSoapMessage(intactSoapMessage, new URL("http://www.ebi.ac.uk/enfin-srv/encore/intact/service"));
return collectAnnotations(intactResponse, new AnnotationIdentifier() {
public boolean isAnnotation(Element setElement) {
List<Element> names = XmlUtil.getChildElements(setElement, "names");
return !names.isEmpty() && "IntAct interaction".equals(XmlUtil.getChildElement(names.get(0), "fullName").getTextContent());
}
}, new AnnotationNameFinder() {
public String findAnnotationName(Element setElement) {
Element primaryRef = (Element)XmlUtil.getChildElement(setElement, "xrefs").getChildNodes().item(0);
return primaryRef.getAttribute("id");
}
});
}
public static ResultTableCollector queryReactome(String[] probes) throws SOAPException, MalformedURLException, SAXException, IOException, ParserConfigurationException, TransformerException {
Document uniprotResponse = queryUniprotIds(probes);
// query Reactome with UniProt identifiers
SOAPMessage intactSoapMessage = initialiseSoapMessage();
SOAPBody intactSoapBody = initialiseSoapBody(intactSoapMessage);
attachEnfinXml(intactSoapBody, fetchEnfinXml(uniprotResponse), "findPath", "http://ebi.ac.uk/enfin/core/web/services/reactome");
Document reactomeResponse = sendSoapMessage(intactSoapMessage, new URL("http://www.ebi.ac.uk/enfin-srv/encore/reactome/service"));
return collectAnnotations(reactomeResponse, new AnnotationIdentifier() {
public boolean isAnnotation(Element setElement) {
List<Element> setTypes = XmlUtil.getChildElements(setElement, "setType");
return !setTypes.isEmpty() && "Reactome".equals(setTypes.get(0).getAttribute("db"));
}
}, new AnnotationNameFinder() {
public String findAnnotationName(Element setElement) {
Element fullName = (Element)XmlUtil.getChildElement(setElement, "names").getChildNodes().item(0);
return fullName.getTextContent();
}
});
}
private static Document queryUniprotIds(String[] probes) throws SOAPException, SAXException, IOException, ParserConfigurationException, MalformedURLException {
// Step 1. Create ENFIN XML out of Affy probe list
SOAPMessage probeSoapMessage = initialiseSoapMessage();
SOAPBody probeSoapBody = initialiseSoapBody(probeSoapMessage);
SOAPElement probeEntries = createOperation(probeSoapBody, "docFromAffyList", "http://ebi.ac.uk/enfin/core/web/services/utility");
for (String probe : probes) {
SOAPElement arg = probeEntries.addChildElement("parameter");
arg.setTextContent(probe);
}
Document probeResponse = sendSoapMessage(probeSoapMessage, new URL("http://www.ebi.ac.uk/enfin-srv/encore/utility/service"));
// Step 2. Convert Affy probes to UniProt identifiers
SOAPMessage uniprotSoapMessage = initialiseSoapMessage();
SOAPBody uniprotSoapBody = initialiseSoapBody(uniprotSoapMessage);
attachEnfinXml(uniprotSoapBody, fetchEnfinXml(probeResponse), "mapAffy2UniProt", "http://ebi.ac.uk/enfin/core/web/services/affy2uniprot");
Document uniprotResponse = sendSoapMessage(uniprotSoapMessage, new URL("http://www.ebi.ac.uk/enfin-srv/encore/affy2uniprot/service"));
return uniprotResponse;
}
private static Document fetchEnfinXml(Document response) throws ParserConfigurationException {
Document document = XmlUtil.newDocument();
document.appendChild(document.importNode(response.getDocumentElement().getElementsByTagNameNS("http://ebi.ac.uk/enfin/core/model", "entries").item(0), true));
return document;
}
private static ResultTableCollector collectAnnotations(Document response, AnnotationIdentifier annotationIdentifier, AnnotationNameFinder annotationNameFinder) {
ResultTableCollector annotationCollector = new ResultTableCollector();
NodeList childNodes = response.getDocumentElement().getChildNodes().item(0).getChildNodes().item(0).getChildNodes().item(0).getChildNodes().item(0).getChildNodes();
// iterate over molecules
HashMap<String, String> moleculeMap = new HashMap<String, String>();
for (int i = 0; i < childNodes.getLength(); i++) {
if ("molecule".equals(childNodes.item(i).getLocalName())) {
Element molecule = (Element)childNodes.item(i);
String moleculeId = molecule.getAttribute("id");
Element primaryRef = (Element)XmlUtil.getChildElement(molecule, "xrefs").getChildNodes().item(0);
String moleculeName = primaryRef.getAttribute("id");
moleculeMap.put(moleculeId, moleculeName);
}
}
// iterate over mappings (Affy->UniProt)
HashMap<String, String> proteinToAffyMap = new HashMap<String, String>();
for (int i = 0; i < childNodes.getLength(); i++) {
if ("set".equals(childNodes.item(i).getLocalName())) {
Element set = (Element) childNodes.item(i);
Element setType = XmlUtil.getChildElement(set, "setType");
if (setType != null && "Affymetrix ID mapped to UniProt accession(s)".equals(setType.getAttribute("term"))) {
List<Element> participants = XmlUtil.getChildElements(set, "participant");
String affyRef = moleculeMap.get(participants.get(0).getAttribute("moleculeRef"));
// iterate over rest
for (int j = 1; j < participants.size(); j++) {
String proteinId = participants.get(j).getAttribute("moleculeRef");
proteinToAffyMap.put(proteinId, affyRef);
}
}
}
}
// iterate over interactions
int index = 0;
for (int i = 0; i < childNodes.getLength(); i++) {
if ("set".equals(((Element)childNodes.item(i)).getLocalName())) {
Element set = (Element)childNodes.item(i);
if (annotationIdentifier.isAnnotation(set)) {
String annotationName = annotationNameFinder.findAnnotationName(set);
annotationCollector.addAnnotation(index, "Name", annotationName);
String probeids = "";
String moleculeNames = "";
List<Element> participants = XmlUtil.getChildElements(set, "participant");
for (Element participant : participants) {
String participantValue = participant.getAttribute("moleculeRef");
String moleculeName = moleculeMap.get(participantValue);
moleculeNames += (" " + moleculeName);
String probeName = proteinToAffyMap.get(participantValue);
if (probeName != null) {
probeids += (" " + probeName);
}
}
annotationCollector.addAnnotation(index, "Probe IDs", probeids);
annotationCollector.addAnnotation(index, "Participants", moleculeNames);
index++;
}
}
}
return annotationCollector;
}
private static Document sendSoapMessage(SOAPMessage soapMessage, URL endpoint) throws SAXException, IOException, ParserConfigurationException, SOAPException {
soapMessage.saveChanges();
SOAPConnectionFactory connectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = connectionFactory.createConnection();
SOAPMessage resp = soapConnection.call(soapMessage, endpoint);
ByteArrayOutputStream out = new ByteArrayOutputStream();
resp.writeTo(out);
soapConnection.close();
return XmlUtil.parseReader(new InputStreamReader(new ByteArrayInputStream(out.toByteArray())));
}
private static SOAPBody initialiseSoapBody(SOAPMessage message) throws SOAPException {
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
return soapEnvelope.getBody();
}
private static SOAPMessage initialiseSoapMessage() throws SOAPException {
MessageFactory mf = MessageFactory.newInstance();
return mf.createMessage();
}
private static void attachEnfinXml(SOAPBody soapBody, Document enfinXml, String operation, String operationNamespace) throws SOAPException, ParserConfigurationException {
Document document = XmlUtil.newDocument();
document.appendChild(document.createElementNS(operationNamespace, operation));
document.getDocumentElement().appendChild(document.importNode(enfinXml.getDocumentElement(), true));
soapBody.addDocument(document);
}
private static SOAPElement createOperation(SOAPBody soapBody, String operation, String operationNamespace) throws SOAPException {
soapBody.addNamespaceDeclaration("oper", operationNamespace);
SOAPElement elementFindPartners = soapBody.addChildElement(operation, "oper");
elementFindPartners.addNamespaceDeclaration("model", "http://ebi.ac.uk/enfin/core/model");
return elementFindPartners;
}
}
| true | true | private static void writeIntactHtml(ResultTableCollector intactAnnotations, File file) throws FileNotFoundException {
ValueHtmlFormatter interactionIdFormatter = new ValueHtmlFormatter() {
public String format(String string, String[] currentRow) {
return "<a href=\"http://www.ebi.ac.uk/intact/pages/interactions/interactions.xhtml?conversationContext=1&queryTxt=" + string.replace(' ', '+') + "\">" + string + "</a>";
}
};
ValueHtmlFormatter uniprotFormatter = new ValueHtmlFormatter() {
public String format(String string, String[] currentRow) {
String formatted = "";
for (String protein : string.split(" ")) {
formatted += "<a href=\"http://www.uniprot.org/uniprot/" + protein.replace(' ', '+') + "\">" + protein + "</a> ";
}
return formatted;
}
};
HtmlUtil.writeHtmlTable(intactAnnotations, new String[] {"Name", "Probe IDs", "Participants"}, new String[] {"Interaction", "Probe ID", "Interacting proteins"}, new HtmlUtil.ValueHtmlFormatter[] {interactionIdFormatter, HtmlUtil.NO_FORMATTING_FORMATTER, uniprotFormatter}, "IntAct protein interactions", new FileOutputStream(file));
}
public static void writeReactomeHtml(ResultTableCollector reactomeAnnotations, File htmlOutput) throws FileNotFoundException {
ValueHtmlFormatter pathwayNameFormatter = new ValueHtmlFormatter() {
public String format(String string, String[] currentRow) {
return "<a href=\"http://www.reactome.org/cgi-bin/search2?DB=gk_current&OPERATOR=ALL&QUERY=" + string.replace(' ', '+') + "&SPECIES=&SUBMIT=Go!\">" + string + "</a>";
}
};
HtmlUtil.writeHtmlTable(reactomeAnnotations, new String[] { "Name", "Probe IDs" }, new String[] {"Pathway", "Probe ID's for participating proteins"}, new HtmlUtil.ValueHtmlFormatter[] {pathwayNameFormatter, HtmlUtil.NO_FORMATTING_FORMATTER}, "Reactome pathway associations", new FileOutputStream(htmlOutput));
}
public static ResultTableCollector queryIntact(String[] probes) throws SOAPException, MalformedURLException, SAXException, IOException, ParserConfigurationException, TransformerException {
Document uniprotResponse = queryUniprotIds(probes);
// query IntAct with UniProt identifiers
SOAPMessage intactSoapMessage = initialiseSoapMessage();
SOAPBody intactSoapBody = initialiseSoapBody(intactSoapMessage);
attachEnfinXml(intactSoapBody, fetchEnfinXml(uniprotResponse), "findPartners", "http://ebi.ac.uk/enfin/core/web/services/intact");
Document intactResponse = sendSoapMessage(intactSoapMessage, new URL("http://www.ebi.ac.uk/enfin-srv/encore/intact/service"));
return collectAnnotations(intactResponse, new AnnotationIdentifier() {
public boolean isAnnotation(Element setElement) {
List<Element> names = XmlUtil.getChildElements(setElement, "names");
return !names.isEmpty() && "IntAct interaction".equals(XmlUtil.getChildElement(names.get(0), "fullName").getTextContent());
}
}, new AnnotationNameFinder() {
public String findAnnotationName(Element setElement) {
Element primaryRef = (Element)XmlUtil.getChildElement(setElement, "xrefs").getChildNodes().item(0);
return primaryRef.getAttribute("id");
}
});
}
public static ResultTableCollector queryReactome(String[] probes) throws SOAPException, MalformedURLException, SAXException, IOException, ParserConfigurationException, TransformerException {
Document uniprotResponse = queryUniprotIds(probes);
// query Reactome with UniProt identifiers
SOAPMessage intactSoapMessage = initialiseSoapMessage();
SOAPBody intactSoapBody = initialiseSoapBody(intactSoapMessage);
attachEnfinXml(intactSoapBody, fetchEnfinXml(uniprotResponse), "findPath", "http://ebi.ac.uk/enfin/core/web/services/reactome");
Document reactomeResponse = sendSoapMessage(intactSoapMessage, new URL("http://www.ebi.ac.uk/enfin-srv/encore/reactome/service"));
return collectAnnotations(reactomeResponse, new AnnotationIdentifier() {
public boolean isAnnotation(Element setElement) {
List<Element> setTypes = XmlUtil.getChildElements(setElement, "setType");
return !setTypes.isEmpty() && "Reactome".equals(setTypes.get(0).getAttribute("db"));
}
}, new AnnotationNameFinder() {
public String findAnnotationName(Element setElement) {
Element fullName = (Element)XmlUtil.getChildElement(setElement, "names").getChildNodes().item(0);
return fullName.getTextContent();
}
});
}
private static Document queryUniprotIds(String[] probes) throws SOAPException, SAXException, IOException, ParserConfigurationException, MalformedURLException {
// Step 1. Create ENFIN XML out of Affy probe list
SOAPMessage probeSoapMessage = initialiseSoapMessage();
SOAPBody probeSoapBody = initialiseSoapBody(probeSoapMessage);
SOAPElement probeEntries = createOperation(probeSoapBody, "docFromAffyList", "http://ebi.ac.uk/enfin/core/web/services/utility");
for (String probe : probes) {
SOAPElement arg = probeEntries.addChildElement("parameter");
arg.setTextContent(probe);
}
Document probeResponse = sendSoapMessage(probeSoapMessage, new URL("http://www.ebi.ac.uk/enfin-srv/encore/utility/service"));
// Step 2. Convert Affy probes to UniProt identifiers
SOAPMessage uniprotSoapMessage = initialiseSoapMessage();
SOAPBody uniprotSoapBody = initialiseSoapBody(uniprotSoapMessage);
attachEnfinXml(uniprotSoapBody, fetchEnfinXml(probeResponse), "mapAffy2UniProt", "http://ebi.ac.uk/enfin/core/web/services/affy2uniprot");
Document uniprotResponse = sendSoapMessage(uniprotSoapMessage, new URL("http://www.ebi.ac.uk/enfin-srv/encore/affy2uniprot/service"));
return uniprotResponse;
}
private static Document fetchEnfinXml(Document response) throws ParserConfigurationException {
Document document = XmlUtil.newDocument();
document.appendChild(document.importNode(response.getDocumentElement().getElementsByTagNameNS("http://ebi.ac.uk/enfin/core/model", "entries").item(0), true));
return document;
}
private static ResultTableCollector collectAnnotations(Document response, AnnotationIdentifier annotationIdentifier, AnnotationNameFinder annotationNameFinder) {
ResultTableCollector annotationCollector = new ResultTableCollector();
NodeList childNodes = response.getDocumentElement().getChildNodes().item(0).getChildNodes().item(0).getChildNodes().item(0).getChildNodes().item(0).getChildNodes();
// iterate over molecules
HashMap<String, String> moleculeMap = new HashMap<String, String>();
for (int i = 0; i < childNodes.getLength(); i++) {
if ("molecule".equals(childNodes.item(i).getLocalName())) {
Element molecule = (Element)childNodes.item(i);
String moleculeId = molecule.getAttribute("id");
Element primaryRef = (Element)XmlUtil.getChildElement(molecule, "xrefs").getChildNodes().item(0);
String moleculeName = primaryRef.getAttribute("id");
moleculeMap.put(moleculeId, moleculeName);
}
}
// iterate over mappings (Affy->UniProt)
HashMap<String, String> proteinToAffyMap = new HashMap<String, String>();
for (int i = 0; i < childNodes.getLength(); i++) {
if ("set".equals(childNodes.item(i).getLocalName())) {
Element set = (Element) childNodes.item(i);
Element setType = XmlUtil.getChildElement(set, "setType");
if (setType != null && "Affymetrix ID mapped to UniProt accession(s)".equals(setType.getAttribute("term"))) {
List<Element> participants = XmlUtil.getChildElements(set, "participant");
String affyRef = moleculeMap.get(participants.get(0).getAttribute("moleculeRef"));
// iterate over rest
for (int j = 1; j < participants.size(); j++) {
String proteinId = participants.get(j).getAttribute("moleculeRef");
proteinToAffyMap.put(proteinId, affyRef);
}
}
}
}
// iterate over interactions
int index = 0;
for (int i = 0; i < childNodes.getLength(); i++) {
if ("set".equals(((Element)childNodes.item(i)).getLocalName())) {
Element set = (Element)childNodes.item(i);
if (annotationIdentifier.isAnnotation(set)) {
String annotationName = annotationNameFinder.findAnnotationName(set);
annotationCollector.addAnnotation(index, "Name", annotationName);
String probeids = "";
String moleculeNames = "";
List<Element> participants = XmlUtil.getChildElements(set, "participant");
for (Element participant : participants) {
String participantValue = participant.getAttribute("moleculeRef");
String moleculeName = moleculeMap.get(participantValue);
moleculeNames += (" " + moleculeName);
String probeName = proteinToAffyMap.get(participantValue);
if (probeName != null) {
probeids += (" " + probeName);
}
}
annotationCollector.addAnnotation(index, "Probe IDs", probeids);
annotationCollector.addAnnotation(index, "Participants", moleculeNames);
index++;
}
}
}
return annotationCollector;
}
private static Document sendSoapMessage(SOAPMessage soapMessage, URL endpoint) throws SAXException, IOException, ParserConfigurationException, SOAPException {
soapMessage.saveChanges();
SOAPConnectionFactory connectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = connectionFactory.createConnection();
SOAPMessage resp = soapConnection.call(soapMessage, endpoint);
ByteArrayOutputStream out = new ByteArrayOutputStream();
resp.writeTo(out);
soapConnection.close();
return XmlUtil.parseReader(new InputStreamReader(new ByteArrayInputStream(out.toByteArray())));
}
private static SOAPBody initialiseSoapBody(SOAPMessage message) throws SOAPException {
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
return soapEnvelope.getBody();
}
private static SOAPMessage initialiseSoapMessage() throws SOAPException {
MessageFactory mf = MessageFactory.newInstance();
return mf.createMessage();
}
private static void attachEnfinXml(SOAPBody soapBody, Document enfinXml, String operation, String operationNamespace) throws SOAPException, ParserConfigurationException {
Document document = XmlUtil.newDocument();
document.appendChild(document.createElementNS(operationNamespace, operation));
document.getDocumentElement().appendChild(document.importNode(enfinXml.getDocumentElement(), true));
soapBody.addDocument(document);
}
private static SOAPElement createOperation(SOAPBody soapBody, String operation, String operationNamespace) throws SOAPException {
soapBody.addNamespaceDeclaration("oper", operationNamespace);
SOAPElement elementFindPartners = soapBody.addChildElement(operation, "oper");
elementFindPartners.addNamespaceDeclaration("model", "http://ebi.ac.uk/enfin/core/model");
return elementFindPartners;
}
}
| public static void writeIntactHtml(ResultTableCollector intactAnnotations, File file) throws FileNotFoundException {
ValueHtmlFormatter interactionIdFormatter = new ValueHtmlFormatter() {
public String format(String string, String[] currentRow) {
return "<a href=\"http://www.ebi.ac.uk/intact/pages/interactions/interactions.xhtml?conversationContext=1&queryTxt=" + string.replace(' ', '+') + "\">" + string + "</a>";
}
};
ValueHtmlFormatter uniprotFormatter = new ValueHtmlFormatter() {
public String format(String string, String[] currentRow) {
String formatted = "";
for (String protein : string.split(" ")) {
formatted += "<a href=\"http://www.uniprot.org/uniprot/" + protein.replace(' ', '+') + "\">" + protein + "</a> ";
}
return formatted;
}
};
HtmlUtil.writeHtmlTable(intactAnnotations, new String[] {"Name", "Probe IDs", "Participants"}, new String[] {"Interaction", "Probe ID", "Interacting proteins"}, new HtmlUtil.ValueHtmlFormatter[] {interactionIdFormatter, HtmlUtil.NO_FORMATTING_FORMATTER, uniprotFormatter}, "IntAct protein interactions", new FileOutputStream(file));
}
public static void writeReactomeHtml(ResultTableCollector reactomeAnnotations, File htmlOutput) throws FileNotFoundException {
ValueHtmlFormatter pathwayNameFormatter = new ValueHtmlFormatter() {
public String format(String string, String[] currentRow) {
return "<a href=\"http://www.reactome.org/cgi-bin/search2?DB=gk_current&OPERATOR=ALL&QUERY=" + string.replace(' ', '+') + "&SPECIES=&SUBMIT=Go!\">" + string + "</a>";
}
};
HtmlUtil.writeHtmlTable(reactomeAnnotations, new String[] { "Name", "Probe IDs" }, new String[] {"Pathway", "Probe ID's for participating proteins"}, new HtmlUtil.ValueHtmlFormatter[] {pathwayNameFormatter, HtmlUtil.NO_FORMATTING_FORMATTER}, "Reactome pathway associations", new FileOutputStream(htmlOutput));
}
public static ResultTableCollector queryIntact(String[] probes) throws SOAPException, MalformedURLException, SAXException, IOException, ParserConfigurationException, TransformerException {
Document uniprotResponse = queryUniprotIds(probes);
// query IntAct with UniProt identifiers
SOAPMessage intactSoapMessage = initialiseSoapMessage();
SOAPBody intactSoapBody = initialiseSoapBody(intactSoapMessage);
attachEnfinXml(intactSoapBody, fetchEnfinXml(uniprotResponse), "findPartners", "http://ebi.ac.uk/enfin/core/web/services/intact");
Document intactResponse = sendSoapMessage(intactSoapMessage, new URL("http://www.ebi.ac.uk/enfin-srv/encore/intact/service"));
return collectAnnotations(intactResponse, new AnnotationIdentifier() {
public boolean isAnnotation(Element setElement) {
List<Element> names = XmlUtil.getChildElements(setElement, "names");
return !names.isEmpty() && "IntAct interaction".equals(XmlUtil.getChildElement(names.get(0), "fullName").getTextContent());
}
}, new AnnotationNameFinder() {
public String findAnnotationName(Element setElement) {
Element primaryRef = (Element)XmlUtil.getChildElement(setElement, "xrefs").getChildNodes().item(0);
return primaryRef.getAttribute("id");
}
});
}
public static ResultTableCollector queryReactome(String[] probes) throws SOAPException, MalformedURLException, SAXException, IOException, ParserConfigurationException, TransformerException {
Document uniprotResponse = queryUniprotIds(probes);
// query Reactome with UniProt identifiers
SOAPMessage intactSoapMessage = initialiseSoapMessage();
SOAPBody intactSoapBody = initialiseSoapBody(intactSoapMessage);
attachEnfinXml(intactSoapBody, fetchEnfinXml(uniprotResponse), "findPath", "http://ebi.ac.uk/enfin/core/web/services/reactome");
Document reactomeResponse = sendSoapMessage(intactSoapMessage, new URL("http://www.ebi.ac.uk/enfin-srv/encore/reactome/service"));
return collectAnnotations(reactomeResponse, new AnnotationIdentifier() {
public boolean isAnnotation(Element setElement) {
List<Element> setTypes = XmlUtil.getChildElements(setElement, "setType");
return !setTypes.isEmpty() && "Reactome".equals(setTypes.get(0).getAttribute("db"));
}
}, new AnnotationNameFinder() {
public String findAnnotationName(Element setElement) {
Element fullName = (Element)XmlUtil.getChildElement(setElement, "names").getChildNodes().item(0);
return fullName.getTextContent();
}
});
}
private static Document queryUniprotIds(String[] probes) throws SOAPException, SAXException, IOException, ParserConfigurationException, MalformedURLException {
// Step 1. Create ENFIN XML out of Affy probe list
SOAPMessage probeSoapMessage = initialiseSoapMessage();
SOAPBody probeSoapBody = initialiseSoapBody(probeSoapMessage);
SOAPElement probeEntries = createOperation(probeSoapBody, "docFromAffyList", "http://ebi.ac.uk/enfin/core/web/services/utility");
for (String probe : probes) {
SOAPElement arg = probeEntries.addChildElement("parameter");
arg.setTextContent(probe);
}
Document probeResponse = sendSoapMessage(probeSoapMessage, new URL("http://www.ebi.ac.uk/enfin-srv/encore/utility/service"));
// Step 2. Convert Affy probes to UniProt identifiers
SOAPMessage uniprotSoapMessage = initialiseSoapMessage();
SOAPBody uniprotSoapBody = initialiseSoapBody(uniprotSoapMessage);
attachEnfinXml(uniprotSoapBody, fetchEnfinXml(probeResponse), "mapAffy2UniProt", "http://ebi.ac.uk/enfin/core/web/services/affy2uniprot");
Document uniprotResponse = sendSoapMessage(uniprotSoapMessage, new URL("http://www.ebi.ac.uk/enfin-srv/encore/affy2uniprot/service"));
return uniprotResponse;
}
private static Document fetchEnfinXml(Document response) throws ParserConfigurationException {
Document document = XmlUtil.newDocument();
document.appendChild(document.importNode(response.getDocumentElement().getElementsByTagNameNS("http://ebi.ac.uk/enfin/core/model", "entries").item(0), true));
return document;
}
private static ResultTableCollector collectAnnotations(Document response, AnnotationIdentifier annotationIdentifier, AnnotationNameFinder annotationNameFinder) {
ResultTableCollector annotationCollector = new ResultTableCollector();
NodeList childNodes = response.getDocumentElement().getChildNodes().item(0).getChildNodes().item(0).getChildNodes().item(0).getChildNodes().item(0).getChildNodes();
// iterate over molecules
HashMap<String, String> moleculeMap = new HashMap<String, String>();
for (int i = 0; i < childNodes.getLength(); i++) {
if ("molecule".equals(childNodes.item(i).getLocalName())) {
Element molecule = (Element)childNodes.item(i);
String moleculeId = molecule.getAttribute("id");
Element primaryRef = (Element)XmlUtil.getChildElement(molecule, "xrefs").getChildNodes().item(0);
String moleculeName = primaryRef.getAttribute("id");
moleculeMap.put(moleculeId, moleculeName);
}
}
// iterate over mappings (Affy->UniProt)
HashMap<String, String> proteinToAffyMap = new HashMap<String, String>();
for (int i = 0; i < childNodes.getLength(); i++) {
if ("set".equals(childNodes.item(i).getLocalName())) {
Element set = (Element) childNodes.item(i);
Element setType = XmlUtil.getChildElement(set, "setType");
if (setType != null && "Affymetrix ID mapped to UniProt accession(s)".equals(setType.getAttribute("term"))) {
List<Element> participants = XmlUtil.getChildElements(set, "participant");
String affyRef = moleculeMap.get(participants.get(0).getAttribute("moleculeRef"));
// iterate over rest
for (int j = 1; j < participants.size(); j++) {
String proteinId = participants.get(j).getAttribute("moleculeRef");
proteinToAffyMap.put(proteinId, affyRef);
}
}
}
}
// iterate over interactions
int index = 0;
for (int i = 0; i < childNodes.getLength(); i++) {
if ("set".equals(((Element)childNodes.item(i)).getLocalName())) {
Element set = (Element)childNodes.item(i);
if (annotationIdentifier.isAnnotation(set)) {
String annotationName = annotationNameFinder.findAnnotationName(set);
annotationCollector.addAnnotation(index, "Name", annotationName);
String probeids = "";
String moleculeNames = "";
List<Element> participants = XmlUtil.getChildElements(set, "participant");
for (Element participant : participants) {
String participantValue = participant.getAttribute("moleculeRef");
String moleculeName = moleculeMap.get(participantValue);
moleculeNames += (" " + moleculeName);
String probeName = proteinToAffyMap.get(participantValue);
if (probeName != null) {
probeids += (" " + probeName);
}
}
annotationCollector.addAnnotation(index, "Probe IDs", probeids);
annotationCollector.addAnnotation(index, "Participants", moleculeNames);
index++;
}
}
}
return annotationCollector;
}
private static Document sendSoapMessage(SOAPMessage soapMessage, URL endpoint) throws SAXException, IOException, ParserConfigurationException, SOAPException {
soapMessage.saveChanges();
SOAPConnectionFactory connectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = connectionFactory.createConnection();
SOAPMessage resp = soapConnection.call(soapMessage, endpoint);
ByteArrayOutputStream out = new ByteArrayOutputStream();
resp.writeTo(out);
soapConnection.close();
return XmlUtil.parseReader(new InputStreamReader(new ByteArrayInputStream(out.toByteArray())));
}
private static SOAPBody initialiseSoapBody(SOAPMessage message) throws SOAPException {
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
return soapEnvelope.getBody();
}
private static SOAPMessage initialiseSoapMessage() throws SOAPException {
MessageFactory mf = MessageFactory.newInstance();
return mf.createMessage();
}
private static void attachEnfinXml(SOAPBody soapBody, Document enfinXml, String operation, String operationNamespace) throws SOAPException, ParserConfigurationException {
Document document = XmlUtil.newDocument();
document.appendChild(document.createElementNS(operationNamespace, operation));
document.getDocumentElement().appendChild(document.importNode(enfinXml.getDocumentElement(), true));
soapBody.addDocument(document);
}
private static SOAPElement createOperation(SOAPBody soapBody, String operation, String operationNamespace) throws SOAPException {
soapBody.addNamespaceDeclaration("oper", operationNamespace);
SOAPElement elementFindPartners = soapBody.addChildElement(operation, "oper");
elementFindPartners.addNamespaceDeclaration("model", "http://ebi.ac.uk/enfin/core/model");
return elementFindPartners;
}
}
|
diff --git a/driver-one/src/main/java/com/telefonica/claudia/smi/provisioning/ONEProvisioningDriver.java b/driver-one/src/main/java/com/telefonica/claudia/smi/provisioning/ONEProvisioningDriver.java
index aadc669..a864a41 100644
--- a/driver-one/src/main/java/com/telefonica/claudia/smi/provisioning/ONEProvisioningDriver.java
+++ b/driver-one/src/main/java/com/telefonica/claudia/smi/provisioning/ONEProvisioningDriver.java
@@ -1,1716 +1,1718 @@
/*
* Claudia Project
* http://claudia.morfeo-project.org
*
* (C) Copyright 2010 Telefonica Investigacion y Desarrollo
* S.A.Unipersonal (Telefonica I+D)
*
* See CREDITS file for info about members and contributors.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License (AGPL) 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 Affero 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.
*
* If you want to use this software an plan to distribute a
* proprietary application in any way, and you are not licensing and
* distributing your source code under AGPL, you probably need to
* purchase a commercial license of the product. Please contact
* [email protected] for more information.
*/
package com.telefonica.claudia.smi.provisioning;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.dmtf.schemas.ovf.envelope._1.ContentType;
import org.dmtf.schemas.ovf.envelope._1.DiskSectionType;
import org.dmtf.schemas.ovf.envelope._1.EnvelopeType;
import org.dmtf.schemas.ovf.envelope._1.FileType;
import org.dmtf.schemas.ovf.envelope._1.ProductSectionType;
import org.dmtf.schemas.ovf.envelope._1.RASDType;
import org.dmtf.schemas.ovf.envelope._1.ReferencesType;
import org.dmtf.schemas.ovf.envelope._1.VirtualDiskDescType;
import org.dmtf.schemas.ovf.envelope._1.VirtualHardwareSectionType;
import org.dmtf.schemas.ovf.envelope._1.VirtualSystemCollectionType;
import org.dmtf.schemas.ovf.envelope._1.VirtualSystemType;
import org.dmtf.schemas.ovf.envelope._1.ProductSectionType.Property;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.abiquo.ovf.OVFEnvelopeUtils;
import com.abiquo.ovf.exceptions.EmptyEnvelopeException;
import com.abiquo.ovf.section.OVFProductUtils;
import com.abiquo.ovf.xml.OVFSerializer;
import com.telefonica.claudia.smi.DataTypesUtils;
import com.telefonica.claudia.smi.Main;
import com.telefonica.claudia.smi.TCloudConstants;
import com.telefonica.claudia.smi.URICreation;
import com.telefonica.claudia.smi.task.Task;
import com.telefonica.claudia.smi.task.TaskManager;
public class ONEProvisioningDriver implements ProvisioningDriver {
public static enum ControlActionType {shutdown, hold, release, stop, suspend, resume, finalize};
//public static enum VmStateType {INIT, PENDING, HOLD, ACTIVE, STOPPED, SUSPENDED, DONE, FAILED};
private final static int INIT_STATE = 0;
private final static int PENDING_STATE = 1;
private final static int HOLD_STATE = 2;
private final static int ACTIVE_STATE = 3;
private final static int STOPPED_STATE = 4;
private final static int SUSPENDED_STATE = 5;
private final static int DONE_STATE = 6;
private final static int FAILED_STATE = 7;
// LCM_INIT, PROLOG, BOOT, RUNNING, MIGRATE, SAVE_STOP, SAVE_SUSPEND, SAVE_MIGRATE, PROLOG_MIGRATE, EPILOG_STOP, EPILOG, SHUTDOWN, CANCEL
private final static int INIT_SUBSTATE = 0;
private final static int PROLOG_SUBSTATE = 1;
private final static int BOOT_SUBSTATE = 2;
private final static int RUNNING_SUBSTATE = 3;
private final static int MIGRATE_SUBSTATE = 4;
private final static int SAVE_STOP_SUBSTATE = 5;
private final static int SAVE_SUSPEND_SUBSTATE = 6;
private final static int SAVE_MIGRATE_SUBSTATE = 7;
private final static int PROLOG_MIGRATE_SUBSTATE = 8;
private final static int PROLOG_RESUME_SUBSTATE = 9;
private final static int EPILOG_STOP_SUBSTATE = 10;
private final static int EPILOG_SUBSTATE = 11;
private final static int SHUDTOWN_SUBSTATE = 12;
private final static int CANCEL_SUBSTATE = 13;
private HashMap<String, String> text_migrability = new HashMap();
private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger("com.telefonica.claudia.smi.provisioning.ONEProvisioningDriver");
// Tag names of the returning info doc for Virtual machines
public static final String VM_STATE = "STATE";
public static final String VM_SUBSTATE = "LCM_STATE";
// XMLRPC commands to access OpenNebula features
private final static String VM_ALLOCATION_COMMAND = "one.vm.allocate";
private final static String VM_UPDATE_COMMAND = "one.vm.action";
private final static String VM_GETINFO_COMMAND = "one.vm.info";
private final static String VM_GETALL_COMMAND = "one.vmpool.info";
private final static String VM_DELETE_COMMAND = "one.vm.delete";
private final static String NET_ALLOCATION_COMMAND = "one.vn.allocate";
private final static String NET_GETINFO_COMMAND = "one.vn.info";
private final static String NET_GETALL_COMMAND = "one.vnpool.info";
private final static String NET_DELETE_COMMAND = "one.vn.delete";
//private final static String DEBUGGING_CONSOLE = "RAW = [ type =\"kvm\", data =\"<devices><serial type='pty'><source path='/dev/pts/5'/><target port='0'/></serial><console type='pty' tty='/dev/pts/5'><source path='/dev/pts/5'/><target port='0'/></console></devices>\" ]";
/**
* Connection URL for OpenNebula. It defaults to localhost, but can be
* overriden with the property oneURL of the server configuration file.
*/
private String oneURL = "http://localhost:2633/RPC2";
/**
* Server configuration file URL property identifier.
*/
private final static String URL_PROPERTY = "oneUrl";
private final static String USER_PROPERTY = "oneUser";
private final static String PASSWORD_PROPERTY = "onePassword";
private static final String KERNEL_PROPERTY = "oneKernel";
private static final String INITRD_PROPERTY = "oneInitrd";
private static final String ARCH_PROPERTY = "arch";
private static final String ENVIRONMENT_PROPERTY = "oneEnvironmentPath";
private final static String SSHKEY_PROPERTY = "oneSshKey";
private final static String SCRIPTPATH_PROPERTY = "oneScriptPath";
private final static String ETH0_GATEWAY_PROPERTY = "eth0Gateway";
private final static String ETH0_DNS_PROPERTY = "eth0Dns";
private final static String ETH1_GATEWAY_PROPERTY = "eth1Gateway";
private final static String ETH1_DNS_PROPERTY = "eth1Dns";
private final static String NET_INIT_SCRIPT0 = "netInitScript0";
private final static String NET_INIT_SCRIPT1 = "netInitScript1";
private String oneSession = "oneadmin:5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8";
private XmlRpcClient xmlRpcClient = null;
private static final String NETWORK_BRIDGE = "oneNetworkBridge";
private static final String XEN_DISK = "xendisk";
/**
* Collection containing the mapping from fqns to ids. This mapped is used as a cache
* of the getVmId method (vm ids never change once assigned).
*/
private Map<String, Integer> idVmMap = new HashMap<String, Integer>();
/**
* Collection containing the mapping from fqns to ids. This mapped is used as a cache
* of the getVmId method (vm ids never change once assigned).
*/
private Map<String, Integer> idNetMap = new HashMap<String, Integer>();
private String hypervisorInitrd="";
private String arch="";
private String hypervisorKernel="";
private String customizationPort;
private String environmentRepositoryPath;
private static String networkBridge="";
private static String xendisk="";
private static String oneSshKey="";
private static String oneScriptPath="";
private static String eth0Gateway="";
private static String eth1Gateway="";
private static String eth0Dns="";
private static String eth1Dns="";
private static String netInitScript0="";
private static String netInitScript1="";
public static final String ASSIGNATION_SYMBOL = "=";
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
public static final String ONE_VM_ID = "NAME";
public static final String ONE_VM_TYPE = "TYPE";
public static final String ONE_VM_STATE = "STATE";
public static final String ONE_VM_MEMORY = "MEMORY";
public static final String ONE_VM_NAME = "NAME";
public static final String ONE_VM_UUID = "UUID";
public static final String ONE_VM_CPU = "CPU";
public static final String ONE_VM_VCPU = "VCPU";
public static final String ONE_VM_RAW_VMI = "RAW_VMI";
public static final String ONE_VM_OS = "OS";
public static final String ONE_VM_OS_PARAM_KERNEL = "kernel";
public static final String ONE_VM_OS_PARAM_INITRD = "initrd";
public static final String ONE_VM_OS_PARAM_ROOT = "root";
public static final String ONE_VM_OS_PARAM_BOOT = "boot";
public static final String ONE_VM_GRAPHICS = "GRAPHICS";
public static final String ONE_VM_GRAPHICS_TYPE = "type";
public static final String ONE_VM_GRAPHICS_LISTEN = "listen";
public static final String ONE_VM_GRAPHICS_PORT = "port";
public static final String ONE_VM_DISK_COLLECTION = "DISKS";
public static final String ONE_VM_DISK = "DISK";
public static final String ONE_VM_DISK_PARAM_IMAGE = "source";
public static final String ONE_VM_DISK_PARAM_FORMAT = "format";
public static final String ONE_VM_DISK_PARAM_SIZE = "size";
public static final String ONE_VM_DISK_PARAM_TARGET = "target";
public static final String ONE_VM_DISK_PARAM_DIGEST = "digest";
public static final String ONE_VM_DISK_PARAM_TYPE = "type";
public static final String ONE_VM_DISK_PARAM_DRIVER = "driver";
public static final String ONE_VM_NIC_COLLECTION = "NICS";
public static final String ONE_VM_NIC = "NIC";
public static final String ONE_VM_NIC_PARAM_IP = "ip";
public static final String ONE_VM_NIC_PARAM_NETWORK = "NETWORK";
public static final String ONE_NET_ID = "ID";
public static final String ONE_NET_NAME = "NAME";
public static final String ONE_NET_BRIDGE = "BRIDGE";
public static final String ONE_NET_TYPE = "TYPE";
public static final String ONE_NET_ADDRESS = "NETWORK_ADDRESS";
public static final String ONE_NET_SIZE = "NETWORK_SIZE";
public static final String ONE_NET_LEASES = "LEASES";
public static final String ONE_NET_IP = "IP";
public static final String ONE_NET_MAC = "MAC";
public static final String ONE_DISK_ID = "ID";
public static final String ONE_DISK_NAME = "NAME";
public static final String ONE_DISK_URL = "URL";
public static final String ONE_DISK_SIZE = "SIZE";
public static final String ONE_OVF_URL = "OVF";
public static final String ONE_CONTEXT = "CONTEXT";
public static final String RESULT_NET_ID = "ID";
public static final String RESULT_NET_NAME = "NAME";
public static final String RESULT_NET_ADDRESS = "NETWORK_ADDRESS";
public static final String RESULT_NET_BRIDGE = "BRIDGE";
public static final String RESULT_NET_TYPE = "TYPE";
public static final String MULT_CONF_LEFT_DELIMITER = "[";
public static final String MULT_CONF_RIGHT_DELIMITER = "]";
public static final String MULT_CONF_SEPARATOR = ",";
public static final String QUOTE = "\"";
private static final int ResourceTypeCPU = 3;
private static final int ResourceTypeMEMORY = 4;
private static final int ResourceTypeNIC = 10;
private static final int ResourceTypeDISK = 17;
public class DeployVMTask extends Task {
public static final long POLLING_INTERVAL= 10000;
private static final int MAX_CONNECTION_ATEMPTS = 5;
String fqnVm;
String ovf;
public DeployVMTask(String fqn, String ovf) {
super();
this.fqnVm = fqn;
this.ovf = ovf;
}
@Override
public void execute() {
this.status = TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
try {
// Create the Virtual Machine
String result = createVirtualMachine();
if (result==null) {
this.status= TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
}
// Wait until the state is RUNNING
this.status = TaskStatus.WAITING;
int connectionAttempts=0;
while (true) {
try {
Document vmInfo = getVirtualMachineState(result);
Integer state = Integer.parseInt(vmInfo.getElementsByTagName(VM_STATE).item(0).getTextContent());
Integer subState = Integer.parseInt(vmInfo.getElementsByTagName(VM_SUBSTATE).item(0).getTextContent());
if (state == ACTIVE_STATE && subState == RUNNING_SUBSTATE ) {
this.status= TaskStatus.SUCCESS;
this.endTime = System.currentTimeMillis();
break;
} else if (state ==FAILED_STATE) {
this.status= TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
break;
}
connectionAttempts=0;
} catch (IOException ioe) {
if (connectionAttempts> MAX_CONNECTION_ATEMPTS) {
this.status= TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
break;
} else
connectionAttempts++;
log.warn("Connection exception accessing ONE. Trying again. Error: " + ioe.getMessage());
}
Thread.sleep(POLLING_INTERVAL);
}
} catch (IOException e) {
log.error("Error connecting to ONE: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
} catch (Exception e) {
log.error("Unexpected error creating VM: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
e.printStackTrace();
return;
}
}
public String createVirtualMachine() throws Exception {
List<String> rpcParams = new ArrayList<String>();
rpcParams.add(oneSession);
rpcParams.add(TCloud2ONEVM(ovf, fqnVm));
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(VM_ALLOCATION_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
throw new IOException ("Error on allocation of VEE replica , XMLRPC call failed: " + ex.getMessage(), ex);
}
boolean success = (Boolean)result[0];
if(success) {
log.debug("Request succeded. Returining: \n\n" + ((Integer)result[1]).toString() + "\n\n");
this.returnMsg = "Virtual machine internal id: " + ((Integer)result[1]).toString();
return ((Integer)result[1]).toString();
} else {
log.error("Error recieved from ONE: " + (String)result[1]);
this.error = new TaskError();
this.error.message = (String)result[1];
return null;
}
}
}
public class DeployNetworkTask extends Task {
String fqnNet;
String ovf;
public DeployNetworkTask(String netFqn, String ovf) {
this.fqnNet = netFqn;
this.ovf = ovf;
}
@Override
public void execute() {
this.status = TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
try {
if (!createNetwork()) {
this.status= TaskStatus.ERROR;
return;
}
this.status= TaskStatus.SUCCESS;
} catch (IOException e) {
log.error("Error connecting to ONE: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.endTime = System.currentTimeMillis();
this.status = TaskStatus.ERROR;
return;
} catch (Exception e) {
log.error("Unknown error creating network: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.endTime = System.currentTimeMillis();
this.status = TaskStatus.ERROR;
}
}
public boolean createNetwork() throws Exception {
List<String> rpcParams = new ArrayList<String>();
rpcParams.add(oneSession);
rpcParams.add(TCloud2ONENet(ovf));
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(NET_ALLOCATION_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
log.error("Connection error. Could not reach ONE host: " + ex.getMessage());
throw new IOException ("Error on allocation of the new network , XMLRPC call failed", ex);
}
boolean success = (Boolean)result[0];
if(success) {
log.debug("Network creation request succeded: " + result[1]);
this.returnMsg = ((Integer)result[1]).toString();
return true;
} else {
log.error("Error recieved from ONE: " + (String)result[1]);
this.error = new TaskError();
this.error.message = (String)result[1];
return false;
}
}
}
public class UndeployVMTask extends Task {
String fqnVm;
public UndeployVMTask(String vmFqn) {
this.fqnVm = vmFqn;
}
@Override
public void execute() {
this.status= TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
// Undeploy the VM
try {
String id = getVmId(fqnVm).toString();
deleteVirtualMachine(id);
this.status= TaskStatus.SUCCESS;
this.endTime = System.currentTimeMillis();
} catch (IOException e) {
log.error("Error connecting to ONE: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
} catch (Exception e) {
log.error("Unknown error undeploying VM: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
}
}
@SuppressWarnings("unchecked")
public boolean deleteVirtualMachine(String id) throws IOException {
List rpcParams = new ArrayList ();
ControlActionType controlAction = ControlActionType.finalize;
log.info("PONG deleteVirtualMachine id: "+ id);
rpcParams.add(oneSession);
rpcParams.add(controlAction.toString());
rpcParams.add(Integer.parseInt(id));
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(VM_UPDATE_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
log.error("Connection error trying to update VM: " + ex.getMessage());
throw new IOException ("Error updating VEE replica , XMLRPC call failed", ex);
}
if (result==null) {
throw new IOException("No result returned from XMLRPC call");
} else {
return (Boolean)result[0];
}
}
}
public class UndeployNetworkTask extends Task {
String fqnNet;
public UndeployNetworkTask(String netFqn) {
this.fqnNet = netFqn;
}
@Override
public void execute() {
this.status= TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
// Undeploy the VM
try {
deleteNetwork(getNetId(fqnNet).toString());
this.status= TaskStatus.SUCCESS;
this.endTime = System.currentTimeMillis();
} catch (IOException e) {
log.error("Error connecting to ONE: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
} catch (Exception e) {
log.error("Unknown error undeploying Network: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
}
}
@SuppressWarnings("unchecked")
public void deleteNetwork(String id) throws IOException {
List rpcParams = new ArrayList<String>();
rpcParams.add(oneSession);
rpcParams.add(new Integer(id) );
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(NET_DELETE_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
throw new IOException ("Error deleting the network , XMLRPC call failed", ex);
}
boolean success = (Boolean)result[0];
if(success) {
} else {
throw new IOException("Unknown error trying to delete network: " + (String)result[1]);
}
}
}
public class ActionVMTask extends Task {
String fqnVM;
String action;
String errorMessage="";
public ActionVMTask(String fqnVM, String action) {
this.fqnVM = fqnVM;
this.action = action;
}
@Override
public void execute() {
this.status= TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
// Undeploy the VM
try {
boolean result = doAction();
if (result)
this.status= TaskStatus.SUCCESS;
else {
this.status = TaskStatus.ERROR;
this.error = new TaskError();
this.error.message = errorMessage;
}
this.endTime = System.currentTimeMillis();
} catch (IOException e) {
log.error("Error connecting to VMWare: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
} catch (Exception e) {
log.error("Unknown error executing action" + action + ": " + e.getMessage() + " -> " + e.getClass().getCanonicalName());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
}
}
public boolean doAction() throws Exception {
System.out.println("Executing action: " + action);
return true;
}
}
protected String TCloud2ONEVM(String xml, String veeFqn) throws Exception {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
if (!doc.getFirstChild().getNodeName().equals(TCloudConstants.TAG_INSTANTIATE_OVF)) {
log.error("Element <"+TCloudConstants.TAG_INSTANTIATE_OVF+"> not found.");
throw new Exception("Element <"+TCloudConstants.TAG_INSTANTIATE_OVF+"> not found.");
}
Element root = (Element) doc.getFirstChild();
String replicaName = root.getAttribute("name");
NodeList envelopeItems = doc.getElementsByTagNameNS("*", "Envelope");
if (envelopeItems.getLength() != 1) {
log.error("Envelope items not found.");
throw new Exception("Envelope items not found.");
}
// Extract the IP from the aspects section
Map<String, String> ipOnNetworkMap = new HashMap<String, String>();
NodeList aspects = doc.getElementsByTagNameNS("*", "Aspect");
for (int i=0; i < aspects.getLength(); i++) {
Element aspect = (Element) aspects.item(i);
if (aspect.getAttribute("name").equals("IP Config")) {
NodeList properties = aspect.getElementsByTagNameNS("*", "Property");
for (int j=0; j < properties.getLength(); j++) {
Element property = (Element) properties.item(j);
NodeList keys = property.getElementsByTagNameNS("*", "Key");
NodeList values = property.getElementsByTagNameNS("*", "Value");
if (keys.getLength() >0 && values.getLength()>0) {
ipOnNetworkMap.put(keys.item(0).getTextContent(), values.item(0).getTextContent());
}
}
}
}
// Extract the ovf sections and pass them to the OVF manager to be processed.
Document ovfDoc = builder.newDocument();
ovfDoc.appendChild(ovfDoc.importNode(envelopeItems.item(0), true));
OVFSerializer ovfSerializer = OVFSerializer.getInstance();
ovfSerializer.setValidateXML(false);
EnvelopeType envelope = ovfSerializer.readXMLEnvelope(new ByteArrayInputStream(DataTypesUtils.serializeXML(ovfDoc).getBytes()));
ContentType entityInstance = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);
if (entityInstance instanceof VirtualSystemType) {
VirtualSystemType vs = (VirtualSystemType) entityInstance;
VirtualHardwareSectionType vh = OVFEnvelopeUtils.getSection(vs, VirtualHardwareSectionType.class);
String virtualizationType = vh.getSystem().getVirtualSystemType().getValue();
String scriptListProp = null;
String scriptListTemplate = "";
String hostname=null;
ProductSectionType productSection;
productSection = OVFEnvelopeUtils.getSection(vs, ProductSectionType.class);
try
{
Property prop = OVFProductUtils.getProperty(productSection, "SCRIPT_LIST");
scriptListProp = prop.getValue().toString();
String[] scriptList = scriptListProp.split("/");
scriptListTemplate = "";
for (String scrt: scriptList){
scriptListTemplate = scriptListTemplate + " "+oneScriptPath+"/"+scrt;
}
}
catch (Exception e)
{
//TODO throw PropertyNotFoundException
//logger.error(e);
scriptListProp="";
scriptListTemplate = "";
}
String netcontext=getNetContext(vh, veeFqn,xml, scriptListProp);
try
{
Property prop = OVFProductUtils.getProperty(productSection, "HOSTNAME");
hostname = prop.getValue().toString();
}
catch (Exception e)
{
//TODO throw PropertyNotFoundException
//logger.error(e);
hostname="";
}
StringBuffer allParametersString = new StringBuffer();
// Migrability ....
allParametersString.append(ONE_VM_NAME).append(ASSIGNATION_SYMBOL).append(replicaName).append(LINE_SEPARATOR);
if (virtualizationType.toLowerCase().equals("kvm")) {
allParametersString.append("REQUIREMENTS").append(ASSIGNATION_SYMBOL).append("\"HYPERVISOR=\\\"kvm\\\"\"").append(LINE_SEPARATOR);
} else if (virtualizationType.toLowerCase().equals("xen")) {
allParametersString.append("REQUIREMENTS").append(ASSIGNATION_SYMBOL).append("\"HYPERVISOR=\\\"xen\\\"\"").append(LINE_SEPARATOR);
}
allParametersString.append(ONE_VM_OS).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
String diskRoot;
if (virtualizationType.toLowerCase().equals("kvm")) {
diskRoot = "h";
allParametersString.append(ONE_VM_OS_PARAM_BOOT).append(ASSIGNATION_SYMBOL).append("hd").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
} else {
diskRoot = xendisk;
allParametersString.append(ONE_VM_OS_PARAM_INITRD).append(ASSIGNATION_SYMBOL).append(hypervisorInitrd).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_OS_PARAM_KERNEL).append(ASSIGNATION_SYMBOL).append(hypervisorKernel).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
if(arch.length()>0)
allParametersString.append("ARCH").append(ASSIGNATION_SYMBOL).append("\"").append(arch).append("\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_OS_PARAM_ROOT).append(ASSIGNATION_SYMBOL).append(diskRoot + "da1").append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
allParametersString.append(ONE_CONTEXT).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
if(hostname.length()>0) {
allParametersString.append("hostname = \""+hostname+"\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
+ if(netcontext.length()>0) {
allParametersString.append(netcontext);
+ }
allParametersString.append("public_key").append(ASSIGNATION_SYMBOL).append(oneSshKey).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("CustomizationUrl").append(ASSIGNATION_SYMBOL).append("\"" + Main.PROTOCOL + Main.serverHost + ":" + customizationPort + "/"+ replicaName+ "\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("files").append(ASSIGNATION_SYMBOL).append("\"" + environmentRepositoryPath + "/"+ replicaName + "/ovf-env.xml" +scriptListTemplate+ "\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("target").append(ASSIGNATION_SYMBOL).append("\"" + diskRoot + "dd"+ "\"").append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
if (vh.getSystem() != null && vh.getSystem().getVirtualSystemType()!= null &&
vh.getSystem().getVirtualSystemType().getValue() != null &&
vh.getSystem().getVirtualSystemType().getValue().equals("vjsc"))
{
allParametersString.append("HYPERVISOR").append(ASSIGNATION_SYMBOL).append("VJSC").append(LINE_SEPARATOR);
}
char sdaId = 'a';
List<RASDType> items = vh.getItem();
for (Iterator<RASDType> iteratorRASD = items.iterator(); iteratorRASD.hasNext();) {
RASDType item = (RASDType) iteratorRASD.next();
/* Get the resource type and process it accordingly */
int rsType = new Integer(item.getResourceType().getValue());
int quantity = 1;
if (item.getVirtualQuantity() != null) {
quantity = item.getVirtualQuantity().getValue().intValue();
}
switch (rsType) {
case ResourceTypeCPU:
// for (int k = 0; k < quantity; k++) {
allParametersString.append(ONE_VM_CPU).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_VCPU).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
// }
break;
case ResourceTypeDISK:
/*
* The rasd:HostResource will follow the pattern
* 'ovf://disk/<id>' where id is the ovf:diskId of some
* <Disk>
*/
String hostRes = item.getHostResource().get(0).getValue();
StringTokenizer st = new StringTokenizer(hostRes, "/");
/*
* Only ovf:/<file|disk>/<n> format is valid, accodring
* OVF spec
*/
if (st.countTokens() != 3) {
throw new IllegalArgumentException("malformed HostResource value (" + hostRes + ")");
}
if (!(st.nextToken().equals("ovf:"))) {
throw new IllegalArgumentException("HostResource must start with ovf: (" + hostRes + ")");
}
String hostResType = st.nextToken();
if (!(hostResType.equals("disk") || hostResType.equals("file"))) {
throw new IllegalArgumentException("HostResource type must be either disk or file: (" + hostRes + ")");
}
String hostResId = st.nextToken();
String fileRef = null;
String capacity = null;
String format = null;
if (hostResType.equals("disk")) {
/* This type involves an indirection level */
DiskSectionType ds = null;
ds = OVFEnvelopeUtils.getSection(envelope, DiskSectionType.class);
List<VirtualDiskDescType> disks = ds.getDisk();
for (Iterator<VirtualDiskDescType> iteratorDk = disks.iterator(); iteratorDk.hasNext();) {
VirtualDiskDescType disk = iteratorDk.next();
String diskId = disk.getDiskId();
if (diskId.equals(hostResId)) {
fileRef = disk.getFileRef();
capacity = disk.getCapacity();
format = disk.getFormat();
break;
}
}
} else {
throw new IllegalArgumentException("File type not supported in Disk sections.");
}
/* Throw exceptions in the case of missing information */
if (fileRef == null) {
log.warn("file reference can not be found for disk: " + hostRes);
}
URL url = null;
String digest = null;
String driver = null;
ReferencesType ref = envelope.getReferences();
List<FileType> files = ref.getFile();
for (Iterator<FileType> iteratorFl = files.iterator(); iteratorFl.hasNext();) {
FileType fl = iteratorFl.next();
if (fileRef!=null)
{
if (fl.getId().equals(fileRef)) {
try {
url = new URL(fl.getHref());
} catch (MalformedURLException e) {
throw new IllegalArgumentException("problems parsing disk href: " + e.getMessage());
}
}
/*
* If capacity was not set using ovf:capacity in
* <Disk>, try to get it know frm <File>
* ovf:size
*/
if (capacity == null && fl.getSize() != null) {
capacity = fl.getSize().toString();
}
/* Try to get the digest */
Map<QName, String> attributesFile = fl.getOtherAttributes();
QName digestAtt = new QName("http://schemas.telefonica.com/claudia/ovf","digest");
digest = attributesFile.get(digestAtt);
Map<QName, String> attributesFile2 = fl.getOtherAttributes();
QName driverAtt = new QName("http://schemas.telefonica.com/claudia/ovf","driver");
driver = attributesFile.get(driverAtt);
break;
}
}
/* Throw exceptions in the case of missing information */
if (capacity == null) {
throw new IllegalArgumentException("capacity can not be set for disk " + hostRes);
}
if (url == null && fileRef!=null) {
throw new IllegalArgumentException("url can not be set for disk " + hostRes);
}
if (digest == null) {
log.debug("md5sum digest was not found for disk " + hostRes);
}
String urlDisk = null;
if (url != null)
{
urlDisk = url.toString();
if (urlDisk.contains("file:/"))
urlDisk = urlDisk.replace("file:/", "file:///");
}
File filesystem = new File("/dev/" + diskRoot + "d" + sdaId);
allParametersString.append(ONE_VM_DISK).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
if (urlDisk!= null)
allParametersString.append(ONE_VM_DISK_PARAM_IMAGE).append(ASSIGNATION_SYMBOL).append(urlDisk).append(MULT_CONF_SEPARATOR);
if (virtualizationType.toLowerCase().equals("kvm")) {
allParametersString.append(ONE_VM_DISK_PARAM_TARGET).append(ASSIGNATION_SYMBOL).append(diskRoot + "d" + sdaId).append(MULT_CONF_SEPARATOR);
} else
allParametersString.append(ONE_VM_DISK_PARAM_TARGET).append(ASSIGNATION_SYMBOL).append(filesystem.getAbsolutePath()).append(MULT_CONF_SEPARATOR);
if (format!=null)
{
if (format.equals("ext3"))
{
allParametersString.append(ONE_VM_DISK_PARAM_TYPE).append(ASSIGNATION_SYMBOL).append("fs").append(MULT_CONF_SEPARATOR);
}
allParametersString.append(ONE_VM_DISK_PARAM_FORMAT).append(ASSIGNATION_SYMBOL).append(format).append(MULT_CONF_SEPARATOR);
}
if (driver!=null)
allParametersString.append(ONE_VM_DISK_PARAM_DRIVER).append(ASSIGNATION_SYMBOL).append(driver).append(MULT_CONF_SEPARATOR);
if (digest!=null)
allParametersString.append(ONE_VM_DISK_PARAM_DIGEST).append(ASSIGNATION_SYMBOL).append(digest).append(MULT_CONF_SEPARATOR);
allParametersString.append(ONE_VM_DISK_PARAM_SIZE).append(ASSIGNATION_SYMBOL).append(capacity);
allParametersString.append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
sdaId++;
break;
case ResourceTypeMEMORY:
allParametersString.append(ONE_VM_MEMORY).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
break;
case ResourceTypeNIC:
String fqnNet = URICreation.getService(veeFqn) + ".networks." + item.getConnection().get(0).getValue();
allParametersString.append(ONE_VM_NIC).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER).append(LINE_SEPARATOR);
allParametersString.append(ONE_NET_BRIDGE).append(ASSIGNATION_SYMBOL).append(networkBridge).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR).
append(ONE_VM_NIC_PARAM_NETWORK).append(ASSIGNATION_SYMBOL).append(fqnNet).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR).
append(ONE_VM_NIC_PARAM_IP).append(ASSIGNATION_SYMBOL).append(ipOnNetworkMap.get(fqnNet)).append(LINE_SEPARATOR).
append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
break;
default:
throw new IllegalArgumentException("unknown hw type: " + rsType);
}
}
//allParametersString.append(LINE_SEPARATOR).append(DEBUGGING_CONSOLE).append(LINE_SEPARATOR);
log.debug("VM data sent:\n\n" + allParametersString.toString() + "\n\n");
System.out.println("VM data sent:\n\n" + allParametersString.toString() + "\n\n");
return allParametersString.toString();
} else {
throw new IllegalArgumentException("OVF malformed. No VirtualSystemType found.");
}
} catch (IOException e1) {
log.error("OVF of the virtual machine was not well formed or it contained some errors.");
throw new Exception("OVF of the virtual machine was not well formed or it contained some errors: " + e1.getMessage());
} catch (ParserConfigurationException e) {
log.error("Error configuring parser: " + e.getMessage());
throw new Exception("Error configuring parser: " + e.getMessage());
} catch (FactoryConfigurationError e) {
log.error("Error retrieving parser: " + e.getMessage());
throw new Exception("Error retrieving parser: " + e.getMessage());
} catch (Exception e) {
log.error("Error configuring a XML Builder.");
throw new Exception("Error configuring a XML Builder: " + e.getMessage());
}
}
protected static String ONEVM2TCloud(String ONETemplate) {
// TODO: ONE Template to TCloud translation
return "";
}
protected static String getNetContext(VirtualHardwareSectionType vh, String veeFqn,String xml, String scriptListProp) throws Exception {
// log.debug("PONG2 xml" +xml+ "\n");
StringBuffer allParametersString = new StringBuffer();
List<RASDType> items = vh.getItem();
int i=0;
for (Iterator<RASDType> iteratorRASD = items.iterator(); iteratorRASD.hasNext();) {
RASDType item = (RASDType) iteratorRASD.next();
/* Get the resource type and process it accordingly */
int rsType = new Integer(item.getResourceType().getValue());
int quantity = 1;
if (item.getVirtualQuantity() != null) {
quantity = item.getVirtualQuantity().getValue().intValue();
}
switch (rsType) {
case ResourceTypeNIC:
try {
// log.debug("PONG eth0Dns" + eth0Dns + "\n");
// log.debug("PONG eth0Gateway" + eth0Gateway + "\n");
// log.debug("PONG eth1Dns" + eth1Dns + "\n");
// log.debug("PONG eth1Gateway" + eth1Gateway + "\n");
String fqnNet = URICreation.getService(veeFqn) + ".networks." + item.getConnection().get(0).getValue();
allParametersString.append("ip_eth"+i).append(ASSIGNATION_SYMBOL).append("\"$NIC[IP, NETWORK=\\\""+fqnNet+"\\\"]\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
String dns="";
String gateway="";
if(i==0){
dns=eth0Dns;
gateway=eth0Gateway;
}
if(i==1){
dns=eth1Dns;
gateway=eth1Gateway;
}
if(dns.length()>0)
{
allParametersString.append("dns_eth"+i).append(ASSIGNATION_SYMBOL).append(dns).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
if(gateway.length()>0)
{
allParametersString.append("gateway_eth"+i).append(ASSIGNATION_SYMBOL).append(gateway).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
i++;
} catch (FactoryConfigurationError e) {
log.error("Error retrieving parser: " + e.getMessage());
throw new Exception("Error retrieving parser: " + e.getMessage());
} catch (Exception e) {
log.error("Error configuring a XML Builder.");
throw new Exception("Error configuring a XML Builder: " + e.getMessage());
}
break;
default:
//throw new IllegalArgumentException("unknown hw type: " + rsType);
}
}
if (i==1){
if(netInitScript0.length()>0) {
allParametersString.append("SCRIPT_EXEC=\""+netInitScript0);
}
}
if (i==2){
if(netInitScript1.length()>0) {
allParametersString.append("SCRIPT_EXEC=\""+netInitScript1);
}
}
if (scriptListProp != null & scriptListProp.length()!=0)
{
String[] scriptList = scriptListProp.split("/");
String scriptListTemplate = "";
for (String scrt: scriptList){
if (scrt.indexOf(".py")!=-1)
{
if (scrt.equals("OVFParser.py")) {
System.out.println ("python /mnt/stratuslab/"+scrt);
allParametersString.append("; python /mnt/stratuslab/"+scrt+"");
}
if (scrt.equals("restful-server.py")) {
System.out.println ("/etc/init.d/lb_server start");
allParametersString.append("; /etc/init.d/lb_server start");
}
if (scrt.equals("torqueProbe.py")) {
System.out.println ("/etc/init.d/probe start");
allParametersString.append("; /etc/init.d/probe start");
}
}
}
}
allParametersString.append("\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
return allParametersString.toString();
}
protected static String TCloud2ONENet(String xml) throws Exception {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
// log.debug("PONG3 doc" +doc.getTextContent()+ "\n");
Element root = (Element) doc.getFirstChild();
String fqn = root.getAttribute(TCloudConstants.ATTR_NETWORK_NAME);
// log.debug("PONG3 fqn" + fqn + "\n");
NodeList macEnabled = doc.getElementsByTagName(TCloudConstants.TAG_NETWORK_MAC_ENABLED);
Element firstmacenElement = (Element)macEnabled.item(0);
NodeList textMacenList = firstmacenElement.getChildNodes();
String macenabled= ((Node)textMacenList.item(0)).getNodeValue().trim();
NodeList netmaskList = doc.getElementsByTagName(TCloudConstants.TAG_NETWORK_NETMASK);
NodeList baseAddressList = doc.getElementsByTagName(TCloudConstants.TAG_NETWORK_BASE_ADDRESS);
StringBuffer allParametersString = new StringBuffer();
String privateNet = null;
if (root.getAttribute(TCloudConstants.ATTR_NETWORK_TYPE).equals("true"))
privateNet = "private";
else
privateNet ="public";
// If there is a netmask, calculate the size of the net counting it's bits.
if (netmaskList.getLength() >0) {
Element netmask = (Element) netmaskList.item(0);
if (!netmask.getTextContent().matches("\\d+\\.\\d+\\.\\d+\\.\\d+"))
throw new IllegalArgumentException("Wrong IPv4 format. Expected example: 192.168.0.0 Got: " + netmask.getTextContent());
String[] ipBytes = netmask.getTextContent().split("\\.");
short[] result = new short[4];
for (int i=0; i < 4; i++) {
try {
result[i] = Short.parseShort(ipBytes[i]);
if (result[i]>255) throw new NumberFormatException("Should be in the range [0-255].");
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Number out of bounds. Bytes should be on the range 0-255.");
}
}
// The network can host 2^n where n is the number of bits in the network address,
// substracting the broadcast and the network value (all 1s and all 0s).
int size = (int) Math.pow(2, 32.0-getBitNumber(result));
if (size < 8)
size = 8;
else
size -= 2;
if (macenabled.equals("false"))
allParametersString.append(ONE_NET_SIZE).append(ASSIGNATION_SYMBOL).append(size).append(LINE_SEPARATOR);
}
if (baseAddressList.getLength()>0) {
if (macenabled.equals("false"))
allParametersString.append(ONE_NET_ADDRESS).append(ASSIGNATION_SYMBOL).append(baseAddressList.item(0).getTextContent()).append(LINE_SEPARATOR);
}
// Translate the simple data to RPC format
allParametersString.append(ONE_NET_NAME).append(ASSIGNATION_SYMBOL).append(fqn).append(LINE_SEPARATOR);
// Add the net Type
if (macenabled.equals("false")) {
allParametersString.append(ONE_NET_TYPE).append(ASSIGNATION_SYMBOL).append("RANGED").append(LINE_SEPARATOR);
}
else {
allParametersString.append(ONE_NET_TYPE).append(ASSIGNATION_SYMBOL).append("FIXED").append(LINE_SEPARATOR);
}
allParametersString.append(ONE_NET_BRIDGE).append(ASSIGNATION_SYMBOL).append(networkBridge).append(LINE_SEPARATOR);
NodeList ipLeaseList = doc.getElementsByTagName(TCloudConstants.TAG_NETWORK_IPLEASES);
for (int i=0; i<ipLeaseList .getLength(); i++){
Node firstIpLeaseNode = ipLeaseList.item(i);
if (firstIpLeaseNode.getNodeType() == Node.ELEMENT_NODE){
Element firstIpLeaseElement = (Element)firstIpLeaseNode;
NodeList ipList =firstIpLeaseElement.getElementsByTagName(TCloudConstants.TAG_NETWORK_IP);
Element firstIpElement = (Element)ipList.item(0);
NodeList textIpList = firstIpElement.getChildNodes();
String ipString = ("IP="+((Node)textIpList.item(0)).getNodeValue().trim());
NodeList macList =firstIpLeaseElement.getElementsByTagName(TCloudConstants.TAG_NETWORK_MAC);
Element firstMacElement = (Element)macList.item(0);
NodeList textMacList = firstMacElement.getChildNodes();
String macString = ("MAC="+((Node)textMacList.item(0)).getNodeValue().trim());
allParametersString.append(ONE_NET_LEASES).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
allParametersString.append(ipString).append(MULT_CONF_SEPARATOR).append(macString).append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
}
}
log.debug("Network data sent:\n\n" + allParametersString.toString() + "\n\n");
return allParametersString.toString();
} catch (IOException e1) {
log.error("OVF of the virtual machine was not well formed or it contained some errors.");
throw new Exception("OVF of the virtual machine was not well formed or it contained some errors: " + e1.getMessage());
} catch (ParserConfigurationException e) {
log.error("Error configuring parser: " + e.getMessage());
throw new Exception("Error configuring parser: " + e.getMessage());
} catch (FactoryConfigurationError e) {
log.error("Error retrieving parser: " + e.getMessage());
throw new Exception("Error retrieving parser: " + e.getMessage());
} catch (Exception e) {
log.error("Error configuring a XML Builder.");
throw new Exception("Error configuring a XML Builder: " + e.getMessage());
}
}
protected static String ONENet2TCloud(String ONETemplate) {
return "";
}
/**
* Get the number of bits with value 1 in the given IP.
*
* @return
*/
public static int getBitNumber (short[] ip) {
if (ip == null || ip.length != 4)
return 0;
int bits=0;
for (int i=0; i < 4; i++)
for (int j=0; j< 15; j++)
bits += ( ((short)Math.pow(2, j))& ip[i]) / Math.pow(2, j);
return bits;
}
/**
* Retrieve the virtual network id given its fqn.
*
* @param fqn
* FQN of the Virtual Network (mapped to its name property in ONE).
*
* @return
* The internal id of the Virtual Network if it exists or -1 otherwise.
*
* @throws Exception
*
*/
protected Integer getNetId(String fqn) throws Exception {
if (!idNetMap.containsKey(fqn))
idNetMap = getNetworkIds();
if (idNetMap.containsKey(fqn))
return idNetMap.get(fqn);
else
return -1;
}
/**
* Retrieve the vm's id given its fqn.
*
* @param fqn
* FQN of the Virtual Machine (mapped to its name property in ONE).
*
* @return
* The internal id of the Virtual Machine if it exists or -1 otherwise.
*
* @throws Exception
*
*/
protected Integer getVmId(String fqn) throws Exception {
if (!idVmMap.containsKey(fqn))
idVmMap = getVmIds();
if (idVmMap.containsKey(fqn))
return idVmMap.get(fqn);
else
return -1;
}
/**
* Retrieve a map of the currently deployed VMs, and its ids.
*
* @return
* A map where the key is the VM's FQN and the value the VM's id.
* @throws Exception
*/
@SuppressWarnings("unchecked")
protected Map<String, Integer> getVmIds() throws Exception {
List rpcParams = new ArrayList<String>();
rpcParams.add(oneSession);
rpcParams.add(-2);
HashMap<String, Integer> mapResult = new HashMap<String, Integer>();
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(VM_GETALL_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
throw new IOException ("Error obtaining the VM list: " + ex.getMessage(), ex);
}
boolean success = (Boolean)result[0];
if(success) {
String resultList = (String) result[1];
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(resultList.getBytes()));
NodeList vmList = doc.getElementsByTagName("VM");
for (int i=0; i < vmList.getLength(); i++) {
Element vm = (Element) vmList.item(i);
String fqn = ((Element)vm.getElementsByTagName("NAME").item(0)).getTextContent();
try {
Integer value = Integer.parseInt(((Element)vm.getElementsByTagName("ID").item(0)).getTextContent());
mapResult.put(fqn, value);
} catch(NumberFormatException nfe) {
log.warn("Numerical id expected, got [" + ((Element)vm.getElementsByTagName("ID").item(0)).getTextContent() + "]");
continue;
}
}
return mapResult;
} catch (ParserConfigurationException e) {
log.error("Parser Configuration Error: " + e.getMessage());
throw new IOException ("Parser Configuration Error", e);
} catch (SAXException e) {
log.error("Parse error reading the answer: " + e.getMessage());
throw new IOException ("XML Parse error", e);
}
} else {
log.error("Error recieved from ONE: " + result[1]);
throw new Exception("Error recieved from ONE: " + result[1]);
}
}
@SuppressWarnings("unchecked")
protected HashMap<String, Integer> getNetworkIds() throws IOException {
List rpcParams = new ArrayList();
rpcParams.add(oneSession);
rpcParams.add(-2);
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(NET_GETALL_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
throw new IOException ("Error obtaining the network list", ex);
}
boolean success = (Boolean)result[0];
if(success) {
HashMap<String, Integer> mapResult = new HashMap<String, Integer>();
String resultList = (String) result[1];
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(resultList.getBytes()));
NodeList vmList = doc.getElementsByTagName("VNET");
for (int i=0; i < vmList.getLength(); i++) {
Element vm = (Element) vmList.item(i);
String fqn = ((Element)vm.getElementsByTagName("NAME").item(0)).getTextContent();
try {
Integer value = Integer.parseInt(((Element)vm.getElementsByTagName("ID").item(0)).getTextContent());
mapResult.put(fqn, value);
} catch(NumberFormatException nfe) {
log.warn("Numerical id expected, got [" + ((Element)vm.getElementsByTagName("ID").item(0)).getTextContent() + "]");
continue;
}
}
return mapResult;
} catch (ParserConfigurationException e) {
throw new IOException ("Parser Configuration Error", e);
} catch (SAXException e) {
throw new IOException ("XML Parse error", e);
}
} else {
throw new IOException("Error recieved from ONE: " +(String)result[1]);
}
}
public ONEProvisioningDriver(Properties prop) {
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
log.info("Creating OpenNebula conector");
if (prop.containsKey(URL_PROPERTY)) {
oneURL = (String) prop.get(URL_PROPERTY);
log.info("URL created: " + oneURL);
}
if (prop.containsKey(USER_PROPERTY)&&prop.containsKey(PASSWORD_PROPERTY)) {
oneSession = ((String) prop.get(USER_PROPERTY)) + ":" + ((String) prop.get(PASSWORD_PROPERTY));
log.info("Session created: " + oneSession);
}
if (prop.containsKey(KERNEL_PROPERTY)) {
hypervisorKernel = ((String) prop.get(KERNEL_PROPERTY));
}
if (prop.containsKey(INITRD_PROPERTY)) {
hypervisorInitrd = ((String) prop.get(INITRD_PROPERTY));
}
if (prop.containsKey(ARCH_PROPERTY)) {
arch = ((String) prop.get(ARCH_PROPERTY));
}
if (prop.containsKey(Main.CUSTOMIZATION_PORT_PROPERTY)) {
customizationPort = ((String) prop.get(Main.CUSTOMIZATION_PORT_PROPERTY));
}
if (prop.containsKey(ENVIRONMENT_PROPERTY)) {
environmentRepositoryPath = (String) prop.get(ENVIRONMENT_PROPERTY);
}
if (prop.containsKey(NETWORK_BRIDGE)) {
networkBridge = ((String) prop.get(NETWORK_BRIDGE));
}
if (prop.containsKey(XEN_DISK)) {
xendisk = ((String) prop.get(XEN_DISK));
}
if (prop.containsKey(SSHKEY_PROPERTY)) {
oneSshKey = ((String) prop.get(SSHKEY_PROPERTY));
}
if (prop.containsKey(SCRIPTPATH_PROPERTY)) {
oneScriptPath = ((String) prop.get(SCRIPTPATH_PROPERTY));
}
if (prop.containsKey(ETH0_GATEWAY_PROPERTY)) {
eth0Gateway= ((String) prop.get(ETH0_GATEWAY_PROPERTY));
}
if (prop.containsKey(ETH0_DNS_PROPERTY)) {
eth0Dns = ((String) prop.get(ETH0_DNS_PROPERTY));
}
if (prop.containsKey(ETH1_GATEWAY_PROPERTY)) {
eth1Gateway = ((String) prop.get(ETH1_GATEWAY_PROPERTY));
}
if (prop.containsKey(ETH1_DNS_PROPERTY)) {
eth1Dns = ((String) prop.get(ETH1_DNS_PROPERTY));
}
if (prop.containsKey(NET_INIT_SCRIPT0)) {
netInitScript0 = ((String) prop.get(NET_INIT_SCRIPT0));
}
if (prop.containsKey(NET_INIT_SCRIPT1)) {
netInitScript1 = ((String) prop.get(NET_INIT_SCRIPT1));
}
try {
config.setServerURL(new URL(oneURL));
} catch (MalformedURLException e) {
log.error("Malformed URL: " + oneURL);
throw new RuntimeException(e);
}
xmlRpcClient = new XmlRpcClient();
log.info("XMLRPC client created");
xmlRpcClient.setConfig(config);
log.info("XMLRPC client configured");
/* MIGRABILITY TAG */
text_migrability.put("cross-host", "HOST");
text_migrability.put("cross-sitehost", "SITE");
text_migrability.put("none", "NONE");
// FULL??
}
@SuppressWarnings("unchecked")
public Document getVirtualMachineState(String id) throws IOException {
List rpcParams = new ArrayList ();
rpcParams.add(oneSession);
rpcParams.add(new Integer(id));
log.debug("Virtual machine info requested for id: " + id);
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(VM_GETINFO_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
log.error("Connection error trying to get VM information: " + ex.getMessage());
throw new IOException ("Error on reading VM state , XMLRPC call failed", ex);
}
boolean completed = (Boolean) result[0];
if (completed) {
String resultList = (String) result[1];
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// RESERVOIR ONLY: the info cames with a XML inside the element RAW_VMI, WITH HEADERS
if (resultList.contains("<RAW_VMI>")) {
resultList = resultList.replace(resultList.substring(resultList.indexOf("<RAW_VMI>"), resultList.indexOf("</RAW_VMI>") + 10), "");
}
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(resultList.getBytes()));
log.debug("VM Info request succeded");
return doc;
} catch (ParserConfigurationException e) {
log.error("Error configuring parser: " + e.getMessage());
throw new IOException ("Parser Configuration Error", e);
} catch (SAXException e) {
log.error("Parse error obtaining info: " + e.getMessage());
throw new IOException ("XML Parse error", e);
}
} else {
log.error("VM Info request failed: " + result[1]);
return null;
}
}
public String getAtributeVirtualSystem(VirtualSystemType vs, String attribute) throws NumberFormatException {
Iterator itr = vs.getOtherAttributes().entrySet().iterator();
while (itr.hasNext()) {
Map.Entry e = (Map.Entry)itr.next();
if ((e.getKey()).equals(new QName ("http://schemas.telefonica.com/claudia/ovf", attribute)))
return (String)e.getValue();
}
return "";
}
public ArrayList<VirtualSystemType> getVirtualSystem (EnvelopeType envelope) throws Exception {
ContentType entityInstance = null;
ArrayList<VirtualSystemType> virtualSystems = new ArrayList ();
try {
entityInstance = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);
} catch (EmptyEnvelopeException e) {
log.error(e);
}
HashMap<String,VirtualSystemType> virtualsystems = new HashMap();
if (entityInstance instanceof VirtualSystemType) {
virtualSystems.add((VirtualSystemType)entityInstance);
} else if (entityInstance instanceof VirtualSystemCollectionType) {
VirtualSystemCollectionType virtualSystemCollectionType = (VirtualSystemCollectionType) entityInstance;
for (VirtualSystemType vs : OVFEnvelopeUtils.getVirtualSystems(virtualSystemCollectionType))
{
virtualSystems.add(vs);
}
}//End for
return virtualSystems;
}
@Override
public long deleteNetwork(String netFqn) throws IOException {
return TaskManager.getInstance().addTask(new UndeployNetworkTask(netFqn), URICreation.getVDC(netFqn)).getTaskId();
}
@Override
public long deleteVirtualMachine(String vmFqn) throws IOException {
return TaskManager.getInstance().addTask(new UndeployVMTask(vmFqn), URICreation.getVDC(vmFqn)).getTaskId();
}
@Override
public long deployNetwork(String netFqn, String ovf) throws IOException {
return TaskManager.getInstance().addTask(new DeployNetworkTask(netFqn, ovf), URICreation.getVDC(netFqn)).getTaskId();
}
@Override
public long deployVirtualMachine(String fqn, String ovf) throws IOException {
return TaskManager.getInstance().addTask(new DeployVMTask(fqn, ovf), URICreation.getVDC(fqn)).getTaskId();
}
public long powerActionVirtualMachine(String fqn, String action) throws IOException {
return TaskManager.getInstance().addTask(new ActionVMTask(fqn, action), URICreation.getVDC(fqn)).getTaskId();
}
public String getNetwork(String fqn) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getNetworkList() throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getVirtualMachine(String fqn) throws IOException {
// TODO Auto-generated method stub
return null;
}
}
| false | true | protected String TCloud2ONEVM(String xml, String veeFqn) throws Exception {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
if (!doc.getFirstChild().getNodeName().equals(TCloudConstants.TAG_INSTANTIATE_OVF)) {
log.error("Element <"+TCloudConstants.TAG_INSTANTIATE_OVF+"> not found.");
throw new Exception("Element <"+TCloudConstants.TAG_INSTANTIATE_OVF+"> not found.");
}
Element root = (Element) doc.getFirstChild();
String replicaName = root.getAttribute("name");
NodeList envelopeItems = doc.getElementsByTagNameNS("*", "Envelope");
if (envelopeItems.getLength() != 1) {
log.error("Envelope items not found.");
throw new Exception("Envelope items not found.");
}
// Extract the IP from the aspects section
Map<String, String> ipOnNetworkMap = new HashMap<String, String>();
NodeList aspects = doc.getElementsByTagNameNS("*", "Aspect");
for (int i=0; i < aspects.getLength(); i++) {
Element aspect = (Element) aspects.item(i);
if (aspect.getAttribute("name").equals("IP Config")) {
NodeList properties = aspect.getElementsByTagNameNS("*", "Property");
for (int j=0; j < properties.getLength(); j++) {
Element property = (Element) properties.item(j);
NodeList keys = property.getElementsByTagNameNS("*", "Key");
NodeList values = property.getElementsByTagNameNS("*", "Value");
if (keys.getLength() >0 && values.getLength()>0) {
ipOnNetworkMap.put(keys.item(0).getTextContent(), values.item(0).getTextContent());
}
}
}
}
// Extract the ovf sections and pass them to the OVF manager to be processed.
Document ovfDoc = builder.newDocument();
ovfDoc.appendChild(ovfDoc.importNode(envelopeItems.item(0), true));
OVFSerializer ovfSerializer = OVFSerializer.getInstance();
ovfSerializer.setValidateXML(false);
EnvelopeType envelope = ovfSerializer.readXMLEnvelope(new ByteArrayInputStream(DataTypesUtils.serializeXML(ovfDoc).getBytes()));
ContentType entityInstance = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);
if (entityInstance instanceof VirtualSystemType) {
VirtualSystemType vs = (VirtualSystemType) entityInstance;
VirtualHardwareSectionType vh = OVFEnvelopeUtils.getSection(vs, VirtualHardwareSectionType.class);
String virtualizationType = vh.getSystem().getVirtualSystemType().getValue();
String scriptListProp = null;
String scriptListTemplate = "";
String hostname=null;
ProductSectionType productSection;
productSection = OVFEnvelopeUtils.getSection(vs, ProductSectionType.class);
try
{
Property prop = OVFProductUtils.getProperty(productSection, "SCRIPT_LIST");
scriptListProp = prop.getValue().toString();
String[] scriptList = scriptListProp.split("/");
scriptListTemplate = "";
for (String scrt: scriptList){
scriptListTemplate = scriptListTemplate + " "+oneScriptPath+"/"+scrt;
}
}
catch (Exception e)
{
//TODO throw PropertyNotFoundException
//logger.error(e);
scriptListProp="";
scriptListTemplate = "";
}
String netcontext=getNetContext(vh, veeFqn,xml, scriptListProp);
try
{
Property prop = OVFProductUtils.getProperty(productSection, "HOSTNAME");
hostname = prop.getValue().toString();
}
catch (Exception e)
{
//TODO throw PropertyNotFoundException
//logger.error(e);
hostname="";
}
StringBuffer allParametersString = new StringBuffer();
// Migrability ....
allParametersString.append(ONE_VM_NAME).append(ASSIGNATION_SYMBOL).append(replicaName).append(LINE_SEPARATOR);
if (virtualizationType.toLowerCase().equals("kvm")) {
allParametersString.append("REQUIREMENTS").append(ASSIGNATION_SYMBOL).append("\"HYPERVISOR=\\\"kvm\\\"\"").append(LINE_SEPARATOR);
} else if (virtualizationType.toLowerCase().equals("xen")) {
allParametersString.append("REQUIREMENTS").append(ASSIGNATION_SYMBOL).append("\"HYPERVISOR=\\\"xen\\\"\"").append(LINE_SEPARATOR);
}
allParametersString.append(ONE_VM_OS).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
String diskRoot;
if (virtualizationType.toLowerCase().equals("kvm")) {
diskRoot = "h";
allParametersString.append(ONE_VM_OS_PARAM_BOOT).append(ASSIGNATION_SYMBOL).append("hd").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
} else {
diskRoot = xendisk;
allParametersString.append(ONE_VM_OS_PARAM_INITRD).append(ASSIGNATION_SYMBOL).append(hypervisorInitrd).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_OS_PARAM_KERNEL).append(ASSIGNATION_SYMBOL).append(hypervisorKernel).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
if(arch.length()>0)
allParametersString.append("ARCH").append(ASSIGNATION_SYMBOL).append("\"").append(arch).append("\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_OS_PARAM_ROOT).append(ASSIGNATION_SYMBOL).append(diskRoot + "da1").append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
allParametersString.append(ONE_CONTEXT).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
if(hostname.length()>0) {
allParametersString.append("hostname = \""+hostname+"\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
allParametersString.append(netcontext);
allParametersString.append("public_key").append(ASSIGNATION_SYMBOL).append(oneSshKey).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("CustomizationUrl").append(ASSIGNATION_SYMBOL).append("\"" + Main.PROTOCOL + Main.serverHost + ":" + customizationPort + "/"+ replicaName+ "\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("files").append(ASSIGNATION_SYMBOL).append("\"" + environmentRepositoryPath + "/"+ replicaName + "/ovf-env.xml" +scriptListTemplate+ "\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("target").append(ASSIGNATION_SYMBOL).append("\"" + diskRoot + "dd"+ "\"").append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
if (vh.getSystem() != null && vh.getSystem().getVirtualSystemType()!= null &&
vh.getSystem().getVirtualSystemType().getValue() != null &&
vh.getSystem().getVirtualSystemType().getValue().equals("vjsc"))
{
allParametersString.append("HYPERVISOR").append(ASSIGNATION_SYMBOL).append("VJSC").append(LINE_SEPARATOR);
}
char sdaId = 'a';
List<RASDType> items = vh.getItem();
for (Iterator<RASDType> iteratorRASD = items.iterator(); iteratorRASD.hasNext();) {
RASDType item = (RASDType) iteratorRASD.next();
/* Get the resource type and process it accordingly */
int rsType = new Integer(item.getResourceType().getValue());
int quantity = 1;
if (item.getVirtualQuantity() != null) {
quantity = item.getVirtualQuantity().getValue().intValue();
}
switch (rsType) {
case ResourceTypeCPU:
// for (int k = 0; k < quantity; k++) {
allParametersString.append(ONE_VM_CPU).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_VCPU).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
// }
break;
case ResourceTypeDISK:
/*
* The rasd:HostResource will follow the pattern
* 'ovf://disk/<id>' where id is the ovf:diskId of some
* <Disk>
*/
String hostRes = item.getHostResource().get(0).getValue();
StringTokenizer st = new StringTokenizer(hostRes, "/");
/*
* Only ovf:/<file|disk>/<n> format is valid, accodring
* OVF spec
*/
if (st.countTokens() != 3) {
throw new IllegalArgumentException("malformed HostResource value (" + hostRes + ")");
}
if (!(st.nextToken().equals("ovf:"))) {
throw new IllegalArgumentException("HostResource must start with ovf: (" + hostRes + ")");
}
String hostResType = st.nextToken();
if (!(hostResType.equals("disk") || hostResType.equals("file"))) {
throw new IllegalArgumentException("HostResource type must be either disk or file: (" + hostRes + ")");
}
String hostResId = st.nextToken();
String fileRef = null;
String capacity = null;
String format = null;
if (hostResType.equals("disk")) {
/* This type involves an indirection level */
DiskSectionType ds = null;
ds = OVFEnvelopeUtils.getSection(envelope, DiskSectionType.class);
List<VirtualDiskDescType> disks = ds.getDisk();
for (Iterator<VirtualDiskDescType> iteratorDk = disks.iterator(); iteratorDk.hasNext();) {
VirtualDiskDescType disk = iteratorDk.next();
String diskId = disk.getDiskId();
if (diskId.equals(hostResId)) {
fileRef = disk.getFileRef();
capacity = disk.getCapacity();
format = disk.getFormat();
break;
}
}
} else {
throw new IllegalArgumentException("File type not supported in Disk sections.");
}
/* Throw exceptions in the case of missing information */
if (fileRef == null) {
log.warn("file reference can not be found for disk: " + hostRes);
}
URL url = null;
String digest = null;
String driver = null;
ReferencesType ref = envelope.getReferences();
List<FileType> files = ref.getFile();
for (Iterator<FileType> iteratorFl = files.iterator(); iteratorFl.hasNext();) {
FileType fl = iteratorFl.next();
if (fileRef!=null)
{
if (fl.getId().equals(fileRef)) {
try {
url = new URL(fl.getHref());
} catch (MalformedURLException e) {
throw new IllegalArgumentException("problems parsing disk href: " + e.getMessage());
}
}
/*
* If capacity was not set using ovf:capacity in
* <Disk>, try to get it know frm <File>
* ovf:size
*/
if (capacity == null && fl.getSize() != null) {
capacity = fl.getSize().toString();
}
/* Try to get the digest */
Map<QName, String> attributesFile = fl.getOtherAttributes();
QName digestAtt = new QName("http://schemas.telefonica.com/claudia/ovf","digest");
digest = attributesFile.get(digestAtt);
Map<QName, String> attributesFile2 = fl.getOtherAttributes();
QName driverAtt = new QName("http://schemas.telefonica.com/claudia/ovf","driver");
driver = attributesFile.get(driverAtt);
break;
}
}
/* Throw exceptions in the case of missing information */
if (capacity == null) {
throw new IllegalArgumentException("capacity can not be set for disk " + hostRes);
}
if (url == null && fileRef!=null) {
throw new IllegalArgumentException("url can not be set for disk " + hostRes);
}
if (digest == null) {
log.debug("md5sum digest was not found for disk " + hostRes);
}
String urlDisk = null;
if (url != null)
{
urlDisk = url.toString();
if (urlDisk.contains("file:/"))
urlDisk = urlDisk.replace("file:/", "file:///");
}
File filesystem = new File("/dev/" + diskRoot + "d" + sdaId);
allParametersString.append(ONE_VM_DISK).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
if (urlDisk!= null)
allParametersString.append(ONE_VM_DISK_PARAM_IMAGE).append(ASSIGNATION_SYMBOL).append(urlDisk).append(MULT_CONF_SEPARATOR);
if (virtualizationType.toLowerCase().equals("kvm")) {
allParametersString.append(ONE_VM_DISK_PARAM_TARGET).append(ASSIGNATION_SYMBOL).append(diskRoot + "d" + sdaId).append(MULT_CONF_SEPARATOR);
} else
allParametersString.append(ONE_VM_DISK_PARAM_TARGET).append(ASSIGNATION_SYMBOL).append(filesystem.getAbsolutePath()).append(MULT_CONF_SEPARATOR);
if (format!=null)
{
if (format.equals("ext3"))
{
allParametersString.append(ONE_VM_DISK_PARAM_TYPE).append(ASSIGNATION_SYMBOL).append("fs").append(MULT_CONF_SEPARATOR);
}
allParametersString.append(ONE_VM_DISK_PARAM_FORMAT).append(ASSIGNATION_SYMBOL).append(format).append(MULT_CONF_SEPARATOR);
}
if (driver!=null)
allParametersString.append(ONE_VM_DISK_PARAM_DRIVER).append(ASSIGNATION_SYMBOL).append(driver).append(MULT_CONF_SEPARATOR);
if (digest!=null)
allParametersString.append(ONE_VM_DISK_PARAM_DIGEST).append(ASSIGNATION_SYMBOL).append(digest).append(MULT_CONF_SEPARATOR);
allParametersString.append(ONE_VM_DISK_PARAM_SIZE).append(ASSIGNATION_SYMBOL).append(capacity);
allParametersString.append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
sdaId++;
break;
case ResourceTypeMEMORY:
allParametersString.append(ONE_VM_MEMORY).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
break;
case ResourceTypeNIC:
String fqnNet = URICreation.getService(veeFqn) + ".networks." + item.getConnection().get(0).getValue();
allParametersString.append(ONE_VM_NIC).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER).append(LINE_SEPARATOR);
allParametersString.append(ONE_NET_BRIDGE).append(ASSIGNATION_SYMBOL).append(networkBridge).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR).
append(ONE_VM_NIC_PARAM_NETWORK).append(ASSIGNATION_SYMBOL).append(fqnNet).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR).
append(ONE_VM_NIC_PARAM_IP).append(ASSIGNATION_SYMBOL).append(ipOnNetworkMap.get(fqnNet)).append(LINE_SEPARATOR).
append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
break;
default:
throw new IllegalArgumentException("unknown hw type: " + rsType);
}
}
//allParametersString.append(LINE_SEPARATOR).append(DEBUGGING_CONSOLE).append(LINE_SEPARATOR);
log.debug("VM data sent:\n\n" + allParametersString.toString() + "\n\n");
System.out.println("VM data sent:\n\n" + allParametersString.toString() + "\n\n");
return allParametersString.toString();
} else {
throw new IllegalArgumentException("OVF malformed. No VirtualSystemType found.");
}
} catch (IOException e1) {
log.error("OVF of the virtual machine was not well formed or it contained some errors.");
throw new Exception("OVF of the virtual machine was not well formed or it contained some errors: " + e1.getMessage());
} catch (ParserConfigurationException e) {
log.error("Error configuring parser: " + e.getMessage());
throw new Exception("Error configuring parser: " + e.getMessage());
} catch (FactoryConfigurationError e) {
log.error("Error retrieving parser: " + e.getMessage());
throw new Exception("Error retrieving parser: " + e.getMessage());
} catch (Exception e) {
log.error("Error configuring a XML Builder.");
throw new Exception("Error configuring a XML Builder: " + e.getMessage());
}
}
| protected String TCloud2ONEVM(String xml, String veeFqn) throws Exception {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
if (!doc.getFirstChild().getNodeName().equals(TCloudConstants.TAG_INSTANTIATE_OVF)) {
log.error("Element <"+TCloudConstants.TAG_INSTANTIATE_OVF+"> not found.");
throw new Exception("Element <"+TCloudConstants.TAG_INSTANTIATE_OVF+"> not found.");
}
Element root = (Element) doc.getFirstChild();
String replicaName = root.getAttribute("name");
NodeList envelopeItems = doc.getElementsByTagNameNS("*", "Envelope");
if (envelopeItems.getLength() != 1) {
log.error("Envelope items not found.");
throw new Exception("Envelope items not found.");
}
// Extract the IP from the aspects section
Map<String, String> ipOnNetworkMap = new HashMap<String, String>();
NodeList aspects = doc.getElementsByTagNameNS("*", "Aspect");
for (int i=0; i < aspects.getLength(); i++) {
Element aspect = (Element) aspects.item(i);
if (aspect.getAttribute("name").equals("IP Config")) {
NodeList properties = aspect.getElementsByTagNameNS("*", "Property");
for (int j=0; j < properties.getLength(); j++) {
Element property = (Element) properties.item(j);
NodeList keys = property.getElementsByTagNameNS("*", "Key");
NodeList values = property.getElementsByTagNameNS("*", "Value");
if (keys.getLength() >0 && values.getLength()>0) {
ipOnNetworkMap.put(keys.item(0).getTextContent(), values.item(0).getTextContent());
}
}
}
}
// Extract the ovf sections and pass them to the OVF manager to be processed.
Document ovfDoc = builder.newDocument();
ovfDoc.appendChild(ovfDoc.importNode(envelopeItems.item(0), true));
OVFSerializer ovfSerializer = OVFSerializer.getInstance();
ovfSerializer.setValidateXML(false);
EnvelopeType envelope = ovfSerializer.readXMLEnvelope(new ByteArrayInputStream(DataTypesUtils.serializeXML(ovfDoc).getBytes()));
ContentType entityInstance = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);
if (entityInstance instanceof VirtualSystemType) {
VirtualSystemType vs = (VirtualSystemType) entityInstance;
VirtualHardwareSectionType vh = OVFEnvelopeUtils.getSection(vs, VirtualHardwareSectionType.class);
String virtualizationType = vh.getSystem().getVirtualSystemType().getValue();
String scriptListProp = null;
String scriptListTemplate = "";
String hostname=null;
ProductSectionType productSection;
productSection = OVFEnvelopeUtils.getSection(vs, ProductSectionType.class);
try
{
Property prop = OVFProductUtils.getProperty(productSection, "SCRIPT_LIST");
scriptListProp = prop.getValue().toString();
String[] scriptList = scriptListProp.split("/");
scriptListTemplate = "";
for (String scrt: scriptList){
scriptListTemplate = scriptListTemplate + " "+oneScriptPath+"/"+scrt;
}
}
catch (Exception e)
{
//TODO throw PropertyNotFoundException
//logger.error(e);
scriptListProp="";
scriptListTemplate = "";
}
String netcontext=getNetContext(vh, veeFqn,xml, scriptListProp);
try
{
Property prop = OVFProductUtils.getProperty(productSection, "HOSTNAME");
hostname = prop.getValue().toString();
}
catch (Exception e)
{
//TODO throw PropertyNotFoundException
//logger.error(e);
hostname="";
}
StringBuffer allParametersString = new StringBuffer();
// Migrability ....
allParametersString.append(ONE_VM_NAME).append(ASSIGNATION_SYMBOL).append(replicaName).append(LINE_SEPARATOR);
if (virtualizationType.toLowerCase().equals("kvm")) {
allParametersString.append("REQUIREMENTS").append(ASSIGNATION_SYMBOL).append("\"HYPERVISOR=\\\"kvm\\\"\"").append(LINE_SEPARATOR);
} else if (virtualizationType.toLowerCase().equals("xen")) {
allParametersString.append("REQUIREMENTS").append(ASSIGNATION_SYMBOL).append("\"HYPERVISOR=\\\"xen\\\"\"").append(LINE_SEPARATOR);
}
allParametersString.append(ONE_VM_OS).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
String diskRoot;
if (virtualizationType.toLowerCase().equals("kvm")) {
diskRoot = "h";
allParametersString.append(ONE_VM_OS_PARAM_BOOT).append(ASSIGNATION_SYMBOL).append("hd").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
} else {
diskRoot = xendisk;
allParametersString.append(ONE_VM_OS_PARAM_INITRD).append(ASSIGNATION_SYMBOL).append(hypervisorInitrd).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_OS_PARAM_KERNEL).append(ASSIGNATION_SYMBOL).append(hypervisorKernel).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
if(arch.length()>0)
allParametersString.append("ARCH").append(ASSIGNATION_SYMBOL).append("\"").append(arch).append("\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_OS_PARAM_ROOT).append(ASSIGNATION_SYMBOL).append(diskRoot + "da1").append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
allParametersString.append(ONE_CONTEXT).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
if(hostname.length()>0) {
allParametersString.append("hostname = \""+hostname+"\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
if(netcontext.length()>0) {
allParametersString.append(netcontext);
}
allParametersString.append("public_key").append(ASSIGNATION_SYMBOL).append(oneSshKey).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("CustomizationUrl").append(ASSIGNATION_SYMBOL).append("\"" + Main.PROTOCOL + Main.serverHost + ":" + customizationPort + "/"+ replicaName+ "\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("files").append(ASSIGNATION_SYMBOL).append("\"" + environmentRepositoryPath + "/"+ replicaName + "/ovf-env.xml" +scriptListTemplate+ "\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("target").append(ASSIGNATION_SYMBOL).append("\"" + diskRoot + "dd"+ "\"").append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
if (vh.getSystem() != null && vh.getSystem().getVirtualSystemType()!= null &&
vh.getSystem().getVirtualSystemType().getValue() != null &&
vh.getSystem().getVirtualSystemType().getValue().equals("vjsc"))
{
allParametersString.append("HYPERVISOR").append(ASSIGNATION_SYMBOL).append("VJSC").append(LINE_SEPARATOR);
}
char sdaId = 'a';
List<RASDType> items = vh.getItem();
for (Iterator<RASDType> iteratorRASD = items.iterator(); iteratorRASD.hasNext();) {
RASDType item = (RASDType) iteratorRASD.next();
/* Get the resource type and process it accordingly */
int rsType = new Integer(item.getResourceType().getValue());
int quantity = 1;
if (item.getVirtualQuantity() != null) {
quantity = item.getVirtualQuantity().getValue().intValue();
}
switch (rsType) {
case ResourceTypeCPU:
// for (int k = 0; k < quantity; k++) {
allParametersString.append(ONE_VM_CPU).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_VCPU).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
// }
break;
case ResourceTypeDISK:
/*
* The rasd:HostResource will follow the pattern
* 'ovf://disk/<id>' where id is the ovf:diskId of some
* <Disk>
*/
String hostRes = item.getHostResource().get(0).getValue();
StringTokenizer st = new StringTokenizer(hostRes, "/");
/*
* Only ovf:/<file|disk>/<n> format is valid, accodring
* OVF spec
*/
if (st.countTokens() != 3) {
throw new IllegalArgumentException("malformed HostResource value (" + hostRes + ")");
}
if (!(st.nextToken().equals("ovf:"))) {
throw new IllegalArgumentException("HostResource must start with ovf: (" + hostRes + ")");
}
String hostResType = st.nextToken();
if (!(hostResType.equals("disk") || hostResType.equals("file"))) {
throw new IllegalArgumentException("HostResource type must be either disk or file: (" + hostRes + ")");
}
String hostResId = st.nextToken();
String fileRef = null;
String capacity = null;
String format = null;
if (hostResType.equals("disk")) {
/* This type involves an indirection level */
DiskSectionType ds = null;
ds = OVFEnvelopeUtils.getSection(envelope, DiskSectionType.class);
List<VirtualDiskDescType> disks = ds.getDisk();
for (Iterator<VirtualDiskDescType> iteratorDk = disks.iterator(); iteratorDk.hasNext();) {
VirtualDiskDescType disk = iteratorDk.next();
String diskId = disk.getDiskId();
if (diskId.equals(hostResId)) {
fileRef = disk.getFileRef();
capacity = disk.getCapacity();
format = disk.getFormat();
break;
}
}
} else {
throw new IllegalArgumentException("File type not supported in Disk sections.");
}
/* Throw exceptions in the case of missing information */
if (fileRef == null) {
log.warn("file reference can not be found for disk: " + hostRes);
}
URL url = null;
String digest = null;
String driver = null;
ReferencesType ref = envelope.getReferences();
List<FileType> files = ref.getFile();
for (Iterator<FileType> iteratorFl = files.iterator(); iteratorFl.hasNext();) {
FileType fl = iteratorFl.next();
if (fileRef!=null)
{
if (fl.getId().equals(fileRef)) {
try {
url = new URL(fl.getHref());
} catch (MalformedURLException e) {
throw new IllegalArgumentException("problems parsing disk href: " + e.getMessage());
}
}
/*
* If capacity was not set using ovf:capacity in
* <Disk>, try to get it know frm <File>
* ovf:size
*/
if (capacity == null && fl.getSize() != null) {
capacity = fl.getSize().toString();
}
/* Try to get the digest */
Map<QName, String> attributesFile = fl.getOtherAttributes();
QName digestAtt = new QName("http://schemas.telefonica.com/claudia/ovf","digest");
digest = attributesFile.get(digestAtt);
Map<QName, String> attributesFile2 = fl.getOtherAttributes();
QName driverAtt = new QName("http://schemas.telefonica.com/claudia/ovf","driver");
driver = attributesFile.get(driverAtt);
break;
}
}
/* Throw exceptions in the case of missing information */
if (capacity == null) {
throw new IllegalArgumentException("capacity can not be set for disk " + hostRes);
}
if (url == null && fileRef!=null) {
throw new IllegalArgumentException("url can not be set for disk " + hostRes);
}
if (digest == null) {
log.debug("md5sum digest was not found for disk " + hostRes);
}
String urlDisk = null;
if (url != null)
{
urlDisk = url.toString();
if (urlDisk.contains("file:/"))
urlDisk = urlDisk.replace("file:/", "file:///");
}
File filesystem = new File("/dev/" + diskRoot + "d" + sdaId);
allParametersString.append(ONE_VM_DISK).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
if (urlDisk!= null)
allParametersString.append(ONE_VM_DISK_PARAM_IMAGE).append(ASSIGNATION_SYMBOL).append(urlDisk).append(MULT_CONF_SEPARATOR);
if (virtualizationType.toLowerCase().equals("kvm")) {
allParametersString.append(ONE_VM_DISK_PARAM_TARGET).append(ASSIGNATION_SYMBOL).append(diskRoot + "d" + sdaId).append(MULT_CONF_SEPARATOR);
} else
allParametersString.append(ONE_VM_DISK_PARAM_TARGET).append(ASSIGNATION_SYMBOL).append(filesystem.getAbsolutePath()).append(MULT_CONF_SEPARATOR);
if (format!=null)
{
if (format.equals("ext3"))
{
allParametersString.append(ONE_VM_DISK_PARAM_TYPE).append(ASSIGNATION_SYMBOL).append("fs").append(MULT_CONF_SEPARATOR);
}
allParametersString.append(ONE_VM_DISK_PARAM_FORMAT).append(ASSIGNATION_SYMBOL).append(format).append(MULT_CONF_SEPARATOR);
}
if (driver!=null)
allParametersString.append(ONE_VM_DISK_PARAM_DRIVER).append(ASSIGNATION_SYMBOL).append(driver).append(MULT_CONF_SEPARATOR);
if (digest!=null)
allParametersString.append(ONE_VM_DISK_PARAM_DIGEST).append(ASSIGNATION_SYMBOL).append(digest).append(MULT_CONF_SEPARATOR);
allParametersString.append(ONE_VM_DISK_PARAM_SIZE).append(ASSIGNATION_SYMBOL).append(capacity);
allParametersString.append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
sdaId++;
break;
case ResourceTypeMEMORY:
allParametersString.append(ONE_VM_MEMORY).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
break;
case ResourceTypeNIC:
String fqnNet = URICreation.getService(veeFqn) + ".networks." + item.getConnection().get(0).getValue();
allParametersString.append(ONE_VM_NIC).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER).append(LINE_SEPARATOR);
allParametersString.append(ONE_NET_BRIDGE).append(ASSIGNATION_SYMBOL).append(networkBridge).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR).
append(ONE_VM_NIC_PARAM_NETWORK).append(ASSIGNATION_SYMBOL).append(fqnNet).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR).
append(ONE_VM_NIC_PARAM_IP).append(ASSIGNATION_SYMBOL).append(ipOnNetworkMap.get(fqnNet)).append(LINE_SEPARATOR).
append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
break;
default:
throw new IllegalArgumentException("unknown hw type: " + rsType);
}
}
//allParametersString.append(LINE_SEPARATOR).append(DEBUGGING_CONSOLE).append(LINE_SEPARATOR);
log.debug("VM data sent:\n\n" + allParametersString.toString() + "\n\n");
System.out.println("VM data sent:\n\n" + allParametersString.toString() + "\n\n");
return allParametersString.toString();
} else {
throw new IllegalArgumentException("OVF malformed. No VirtualSystemType found.");
}
} catch (IOException e1) {
log.error("OVF of the virtual machine was not well formed or it contained some errors.");
throw new Exception("OVF of the virtual machine was not well formed or it contained some errors: " + e1.getMessage());
} catch (ParserConfigurationException e) {
log.error("Error configuring parser: " + e.getMessage());
throw new Exception("Error configuring parser: " + e.getMessage());
} catch (FactoryConfigurationError e) {
log.error("Error retrieving parser: " + e.getMessage());
throw new Exception("Error retrieving parser: " + e.getMessage());
} catch (Exception e) {
log.error("Error configuring a XML Builder.");
throw new Exception("Error configuring a XML Builder: " + e.getMessage());
}
}
|
diff --git a/Source/App/src/dimappers/android/pub/DataRequestGetPhotos.java b/Source/App/src/dimappers/android/pub/DataRequestGetPhotos.java
index 082d388..a2118d4 100644
--- a/Source/App/src/dimappers/android/pub/DataRequestGetPhotos.java
+++ b/Source/App/src/dimappers/android/pub/DataRequestGetPhotos.java
@@ -1,47 +1,47 @@
package dimappers.android.pub;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
public class DataRequestGetPhotos implements IDataRequest<String, XmlJasonObject> {
IPubService service;
public void giveConnection(IPubService connectionInterface) {
service = connectionInterface;
}
public void performRequest(IRequestListener<XmlJasonObject> listener,
HashMap<String, XmlJasonObject> storedData) {
long userId = service.GetActiveUser().getUserId();
if(storedData.containsKey("Photos"))
{
- if(!storedData.get(userId).isOutOfDate())
+ if(!storedData.get("Photos").isOutOfDate())
{
listener.onRequestComplete(storedData.get(userId));
return;
}
}
XmlJasonObject myPhotos;
try {
myPhotos = new XmlJasonObject(service.GetFacebook().request("me/photos"));
storedData.put("Photos", myPhotos);
} catch (Exception e) {
listener.onRequestFail(e);
return;
}
listener.onRequestComplete(myPhotos);
}
public String getStoredDataId() {
return "JSONObject";
}
}
| true | true | public void performRequest(IRequestListener<XmlJasonObject> listener,
HashMap<String, XmlJasonObject> storedData) {
long userId = service.GetActiveUser().getUserId();
if(storedData.containsKey("Photos"))
{
if(!storedData.get(userId).isOutOfDate())
{
listener.onRequestComplete(storedData.get(userId));
return;
}
}
XmlJasonObject myPhotos;
try {
myPhotos = new XmlJasonObject(service.GetFacebook().request("me/photos"));
storedData.put("Photos", myPhotos);
} catch (Exception e) {
listener.onRequestFail(e);
return;
}
listener.onRequestComplete(myPhotos);
}
| public void performRequest(IRequestListener<XmlJasonObject> listener,
HashMap<String, XmlJasonObject> storedData) {
long userId = service.GetActiveUser().getUserId();
if(storedData.containsKey("Photos"))
{
if(!storedData.get("Photos").isOutOfDate())
{
listener.onRequestComplete(storedData.get(userId));
return;
}
}
XmlJasonObject myPhotos;
try {
myPhotos = new XmlJasonObject(service.GetFacebook().request("me/photos"));
storedData.put("Photos", myPhotos);
} catch (Exception e) {
listener.onRequestFail(e);
return;
}
listener.onRequestComplete(myPhotos);
}
|
diff --git a/GAE/src/org/waterforpeople/mapping/app/web/TestHarnessServlet.java b/GAE/src/org/waterforpeople/mapping/app/web/TestHarnessServlet.java
index 2ec8ec86b..896af69de 100644
--- a/GAE/src/org/waterforpeople/mapping/app/web/TestHarnessServlet.java
+++ b/GAE/src/org/waterforpeople/mapping/app/web/TestHarnessServlet.java
@@ -1,2322 +1,2351 @@
/*
* Copyright (C) 2010-2013 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo FLOW.
*
* Akvo FLOW is free software: you can redistribute it and modify it under the terms of
* the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
* either version 3 of the License or any later version.
*
* Akvo FLOW 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 Affero General Public License included below for more details.
*
* The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
*/
package org.waterforpeople.mapping.app.web;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheFactory;
import net.sf.jsr107cache.CacheManager;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.RuntimeSingleton;
import org.apache.velocity.runtime.parser.node.SimpleNode;
import org.datanucleus.store.appengine.query.JDOCursorHelper;
import org.waterforpeople.mapping.analytics.dao.AccessPointMetricSummaryDao;
import org.waterforpeople.mapping.analytics.dao.AccessPointStatusSummaryDao;
import org.waterforpeople.mapping.analytics.dao.SurveyQuestionSummaryDao;
import org.waterforpeople.mapping.analytics.domain.AccessPointMetricSummary;
import org.waterforpeople.mapping.analytics.domain.AccessPointStatusSummary;
import org.waterforpeople.mapping.analytics.domain.SurveyQuestionSummary;
import org.waterforpeople.mapping.app.gwt.client.device.DeviceDto;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto.QuestionType;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionGroupDto;
import org.waterforpeople.mapping.app.gwt.client.survey.SurveyAssignmentDto;
import org.waterforpeople.mapping.app.gwt.client.survey.SurveyDto;
import org.waterforpeople.mapping.app.gwt.client.survey.SurveyGroupDto;
import org.waterforpeople.mapping.app.gwt.server.accesspoint.AccessPointManagerServiceImpl;
import org.waterforpeople.mapping.app.gwt.server.devicefiles.DeviceFilesServiceImpl;
import org.waterforpeople.mapping.app.gwt.server.survey.SurveyAssignmentServiceImpl;
import org.waterforpeople.mapping.app.gwt.server.survey.SurveyServiceImpl;
import org.waterforpeople.mapping.app.web.dto.DataProcessorRequest;
import org.waterforpeople.mapping.app.web.rest.security.AppRole;
import org.waterforpeople.mapping.app.web.test.AccessPointMetricSummaryTest;
import org.waterforpeople.mapping.app.web.test.AccessPointTest;
import org.waterforpeople.mapping.app.web.test.DeleteObjectUtil;
import org.waterforpeople.mapping.app.web.test.StandardScoringTest;
import org.waterforpeople.mapping.app.web.test.StandardTestLoader;
import org.waterforpeople.mapping.dao.AccessPointDao;
import org.waterforpeople.mapping.dao.AccessPointMetricMappingDao;
import org.waterforpeople.mapping.dao.CommunityDao;
import org.waterforpeople.mapping.dao.DeviceFilesDao;
import org.waterforpeople.mapping.dao.QuestionAnswerStoreDao;
import org.waterforpeople.mapping.dao.SurveyAttributeMappingDao;
import org.waterforpeople.mapping.dao.SurveyContainerDao;
import org.waterforpeople.mapping.dao.SurveyInstanceDAO;
import org.waterforpeople.mapping.dataexport.DeviceFilesReplicationImporter;
import org.waterforpeople.mapping.dataexport.SurveyReplicationImporter;
import org.waterforpeople.mapping.domain.AccessPoint;
import org.waterforpeople.mapping.domain.AccessPoint.AccessPointType;
import org.waterforpeople.mapping.domain.AccessPoint.Status;
import org.waterforpeople.mapping.domain.AccessPointMetricMapping;
import org.waterforpeople.mapping.domain.Community;
import org.waterforpeople.mapping.domain.QuestionAnswerStore;
import org.waterforpeople.mapping.domain.Status.StatusCode;
import org.waterforpeople.mapping.domain.SurveyAssignment;
import org.waterforpeople.mapping.domain.SurveyAttributeMapping;
import org.waterforpeople.mapping.domain.SurveyInstance;
import org.waterforpeople.mapping.domain.TechnologyType;
import org.waterforpeople.mapping.helper.AccessPointHelper;
import org.waterforpeople.mapping.helper.GeoRegionHelper;
import org.waterforpeople.mapping.helper.KMLHelper;
import com.beoui.geocell.GeocellManager;
import com.beoui.geocell.model.Point;
import com.gallatinsystems.common.Constants;
import com.gallatinsystems.common.util.ZipUtil;
import com.gallatinsystems.device.dao.DeviceDAO;
import com.gallatinsystems.device.domain.Device;
import com.gallatinsystems.device.domain.Device.DeviceType;
import com.gallatinsystems.device.domain.DeviceFiles;
import com.gallatinsystems.device.domain.DeviceSurveyJobQueue;
import com.gallatinsystems.diagnostics.dao.RemoteStacktraceDao;
import com.gallatinsystems.diagnostics.domain.RemoteStacktrace;
import com.gallatinsystems.editorial.dao.EditorialPageDao;
import com.gallatinsystems.editorial.domain.EditorialPage;
import com.gallatinsystems.editorial.domain.EditorialPageContent;
import com.gallatinsystems.framework.dao.BaseDAO;
import com.gallatinsystems.framework.domain.BaseDomain;
import com.gallatinsystems.framework.exceptions.IllegalDeletionException;
import com.gallatinsystems.gis.coordinate.utilities.Coordinate;
import com.gallatinsystems.gis.coordinate.utilities.CoordinateUtilities;
import com.gallatinsystems.gis.geography.dao.CountryDao;
import com.gallatinsystems.gis.geography.dao.SubCountryDao;
import com.gallatinsystems.gis.geography.domain.Country;
import com.gallatinsystems.gis.geography.domain.SubCountry;
import com.gallatinsystems.gis.location.GeoLocationServiceGeonamesImpl;
import com.gallatinsystems.gis.location.GeoPlace;
import com.gallatinsystems.gis.map.dao.MapFragmentDao;
import com.gallatinsystems.gis.map.dao.OGRFeatureDao;
import com.gallatinsystems.gis.map.domain.Geometry;
import com.gallatinsystems.gis.map.domain.Geometry.GeometryType;
import com.gallatinsystems.gis.map.domain.MapFragment;
import com.gallatinsystems.gis.map.domain.MapFragment.FRAGMENTTYPE;
import com.gallatinsystems.gis.map.domain.OGRFeature;
import com.gallatinsystems.gis.map.domain.OGRFeature.FeatureType;
import com.gallatinsystems.metric.dao.MetricDao;
import com.gallatinsystems.metric.domain.Metric;
import com.gallatinsystems.notification.NotificationRequest;
import com.gallatinsystems.notification.helper.NotificationHelper;
import com.gallatinsystems.standards.domain.StandardScoreBucket;
import com.gallatinsystems.survey.dao.DeviceSurveyJobQueueDAO;
import com.gallatinsystems.survey.dao.QuestionDao;
import com.gallatinsystems.survey.dao.QuestionGroupDao;
import com.gallatinsystems.survey.dao.QuestionHelpMediaDao;
import com.gallatinsystems.survey.dao.QuestionOptionDao;
import com.gallatinsystems.survey.dao.SurveyDAO;
import com.gallatinsystems.survey.dao.SurveyGroupDAO;
import com.gallatinsystems.survey.dao.SurveyTaskUtil;
import com.gallatinsystems.survey.dao.TranslationDao;
import com.gallatinsystems.survey.domain.Question;
import com.gallatinsystems.survey.domain.Question.Type;
import com.gallatinsystems.survey.domain.QuestionGroup;
import com.gallatinsystems.survey.domain.QuestionHelpMedia;
import com.gallatinsystems.survey.domain.QuestionOption;
import com.gallatinsystems.survey.domain.Survey;
import com.gallatinsystems.survey.domain.SurveyContainer;
import com.gallatinsystems.survey.domain.SurveyGroup;
import com.gallatinsystems.survey.domain.SurveyXMLFragment;
import com.gallatinsystems.survey.domain.Translation;
import com.gallatinsystems.survey.domain.Translation.ParentType;
import com.gallatinsystems.surveyal.dao.SurveyedLocaleDao;
import com.gallatinsystems.surveyal.domain.SurveyalValue;
import com.gallatinsystems.surveyal.domain.SurveyedLocale;
import com.gallatinsystems.user.dao.UserDao;
import com.gallatinsystems.user.domain.Permission;
import com.gallatinsystems.user.domain.User;
import com.google.appengine.api.backends.BackendServiceFactory;
import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
public class TestHarnessServlet extends HttpServlet {
private static Logger log = Logger.getLogger(TestHarnessServlet.class
.getName());
private static final long serialVersionUID = -5673118002247715049L;
@SuppressWarnings("unused")
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
String action = req.getParameter("action");
if ("setupTestUser".equals(action)) {
setupTestUser();
} else if ("computeDistanceAlongBearing".equals(action)) {
com.gallatinsystems.gis.coordinate.utilities.CoordinateUtilities cu = new CoordinateUtilities();
Coordinate startingPoint = new Coordinate(Double.parseDouble(req
.getParameter("lat")), Double.parseDouble(req
.getParameter("lon")));
Double distance = Double.parseDouble(req.getParameter("distance"));
Double bearing = Double.parseDouble(req.getParameter("bearing"));
Coordinate newPoint = cu.computePointAlongBearingDistance(
startingPoint, distance, bearing);
try {
resp.getWriter().println("New Point : " + newPoint.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("fixQuestionAnswerStoreDates".equals(action)) {
// DataFixes df = new DataFixes();
// df.generateTestData();
Queue queue = QueueFactory.getDefaultQueue();
queue.add(TaskOptions.Builder
.withUrl("/app_worker/questionanswerstorecleanup"));
log.info("submiting task QAS CollectionDate Cleanup");
} else if ("reprocessFiles".equalsIgnoreCase(action)) {
DeviceFilesDao dfDao = new DeviceFilesDao();
String cursor = null;
List<DeviceFiles> files = null;
do {
files = dfDao.listDeviceFilesByStatus(StatusCode.IN_PROGRESS,
cursor);
if (files != null) {
cursor = DeviceFilesDao.getCursor(files);
Queue queue = QueueFactory.getDefaultQueue();
for (DeviceFiles fi : files) {
queue.add(TaskOptions.Builder
.withUrl("/app_worker/task")
.param("action", "processFile")
.param("fileName",
fi.getURI()
.substring(
fi.getURI()
.lastIndexOf(
"/") + 1)));
}
}
} while (files != null && files.size() > 0 && cursor != null);
} else if ("testStandardScoring".equals(action)) {
StandardTestLoader stl = new StandardTestLoader(req, resp);
stl.runTest();
} else if ("listStandardScoringResults".equals(action)) {
StandardTestLoader stl = new StandardTestLoader(req, resp);
String countryCode = null;
String communityCode = null;
String accessPointCode = null;
if (req.getParameter("countryCode") != null) {
countryCode = req.getParameter("countryCode");
}
if (req.getParameter("communityCode") != null) {
communityCode = req.getParameter("communityCode");
}
if (req.getParameter("accessPointCode") != null) {
accessPointCode = req.getParameter("accessPointCode");
}
String cursorString = null;
if (req.getParameter("cursorString") != null) {
cursorString = req.getParameter("cursorString");
}
stl.listResults(countryCode, communityCode, accessPointCode,
cursorString);
} else if ("testDistanceRule".equals(action)) {
DeleteObjectUtil dou = new DeleteObjectUtil();
dou.deleteAllObjects("AccessPointScoreComputationItem");
dou.deleteAllObjects("AccessPointScoreDetail");
// AccessPointTest apt = new AccessPointTest();
// apt.loadWPDistanceTestData(resp);
// apt.loadHHDistanceTestData(resp);
// AccessPointDao apDao = new AccessPointDao();
// List<AccessPoint> apList = apDao.list("all");
// AccessPointHelper aph = new AccessPointHelper();
// for (AccessPoint ap : apList) {
// aph.computeDistanceRule(ap);
// }
// try {
// resp.getWriter().println("Completed test distance rule");
// } catch (IOException e) {
// e.printStackTrace();
// }
} else if ("setupDevEnv".equals(action)) {
try {
DeleteObjectUtil dou = new DeleteObjectUtil();
dou.deleteAllObjects("AccessPoint");
dou.deleteAllObjects("StandardScoreBucket");
dou.deleteAllObjects("StandardScoring");
resp.getWriter().println(
"About to configure development environment");
setupTestUser();
resp.getWriter().println("Completed setting up test user");
resp.getWriter().println("Completed setting up permissions");
AccessPointTest apt = new AccessPointTest();
apt.loadLots(resp, 100);
StandardScoringTest sct = new StandardScoringTest();
sct.populateData();
setupMetrics();
resp.getWriter().println("Completed setting scorebuckets");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("populateAccessPointMetric".equals(action)) {
AccessPointMetricSummaryTest apMST = new AccessPointMetricSummaryTest();
apMST.runTest(resp);
} else if ("reorderQuestionsByCollectionDate".equals(action)) {
try {
Long surveyId = Long.parseLong(req.getParameter("surveyId"));
SurveyDAO surveyDao = new SurveyDAO();
QuestionDao qDao = new QuestionDao();
Survey survey = surveyDao.loadFullSurvey(surveyId);
int i = 0;
for (Map.Entry<Integer, QuestionGroup> qGEntry : survey
.getQuestionGroupMap().entrySet()) {
List<Question> qList = qDao
.listQuestionsByQuestionGroupOrderByCreatedDateTime(qGEntry
.getValue().getKey().getId());
for (Question q : qDao
.listQuestionsByQuestionGroupOrderByCreatedDateTime(qGEntry
.getValue().getKey().getId())) {
q.setOrder(i + 1);
qDao.save(q);
resp.getWriter().println(
q.getOrder() + " :Change: " + q.getText());
++i;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("fixQuestionOrder".equals(action)) {
Long surveyId = Long.parseLong(req.getParameter("surveyId"));
QuestionDao qDao = new QuestionDao();
// this is the list in ascending order by the "order" field
List<Question> qList = qDao.listQuestionsBySurvey(surveyId);
if (qList != null) {
Map<Long, Integer> groupMaxCount = new HashMap<Long, Integer>();
for (Question q : qList) {
Integer max = groupMaxCount.get(q.getQuestionGroupId());
if (max == null) {
max = 1;
} else {
max = max + 1;
}
// since q is still attached, this should be all we need to
// do
q.setOrder(max);
groupMaxCount.put(q.getQuestionGroupId(), max);
}
}
} else if ("deleteGeoData".equals(action)) {
try {
OGRFeatureDao ogrFeatureDao = new OGRFeatureDao();
for (OGRFeature item : ogrFeatureDao.list("all")) {
resp.getWriter().println(
"deleting: " + item.getCountryCode());
ogrFeatureDao.delete(item);
}
resp.getWriter().println("Finished");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("testGeoLocation".equals(action)) {
OGRFeatureDao ogrFeatureDao = new OGRFeatureDao();
GeoLocationServiceGeonamesImpl gs = new GeoLocationServiceGeonamesImpl();
String lat = req.getParameter("lat");
String lon = req.getParameter("lon");
GeoPlace geoPlace = gs.manualLookup(lat, lon);
try {
if (geoPlace != null) {
resp.getWriter().println(
"Found: " + geoPlace.getCountryName() + ":"
+ geoPlace.getCountryCode() + " for " + lat
+ ", " + lon);
geoPlace = gs.resolveSubCountry(lat, lon,
geoPlace.getCountryCode());
}
if (geoPlace != null)
resp.getWriter().println(
"Found: " + geoPlace.getCountryCode() + ":"
+ geoPlace.getSub1() + ":"
+ geoPlace.getSub2() + ":"
+ geoPlace.getSub3() + ":"
+ geoPlace.getSub4() + ":"
+ geoPlace.getSub5() + ":"
+ geoPlace.getSub6() + " for " + lat + ", "
+ lon);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
+ } else if ("testDetailedGeoLocation".equals(action)) {
+ OGRFeatureDao ogrFeatureDao = new OGRFeatureDao();
+ GeoLocationServiceGeonamesImpl gs = new GeoLocationServiceGeonamesImpl();
+ String lat = req.getParameter("lat");
+ String lon = req.getParameter("lon");
+ GeoPlace geoPlace = gs.manualLookup(lat, lon, OGRFeature.FeatureType.SUB_COUNTRY_OTHER);
+ try {
+ if (geoPlace != null) {
+ resp.getWriter().println(
+ "Found: " + geoPlace.getCountryName() + ":"
+ + geoPlace.getCountryCode() + " for " + lat
+ + ", " + lon);
+ geoPlace = gs.resolveSubCountry(lat, lon,
+ geoPlace.getCountryCode());
+ }
+ if (geoPlace != null)
+ resp.getWriter().println(
+ "Found: " + geoPlace.getCountryCode() + ":"
+ + geoPlace.getSub1() + ":"
+ + geoPlace.getSub2() + ":"
+ + geoPlace.getSub3() + ":"
+ + geoPlace.getSub4() + ":"
+ + geoPlace.getSub5() + ":"
+ + geoPlace.getSub6() + " for " + lat + ", "
+ + lon);
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
} else if ("RemapAPToSub".equals(action)) {
AccessPointDao apDao = new AccessPointDao();
} else if ("loadOGRFeature".equals(action)) {
OGRFeature ogrFeature = new OGRFeature();
ogrFeature.setName("clan-21061011");
ogrFeature.setProjectCoordinateSystemIdentifier("World_Mercator");
ogrFeature.setGeoCoordinateSystemIdentifier("GCS_WGS_1984");
ogrFeature.setDatumIdentifier("WGS_1984");
ogrFeature.setSpheroid(6378137D);
ogrFeature.setReciprocalOfFlattening(298.257223563);
ogrFeature.setCountryCode("LR");
ogrFeature.addBoundingBox(223700.015625, 481399.468750,
680781.375000, 945462.437500);
Geometry geo = new Geometry();
geo.setType(GeometryType.POLYGON);
String coords = "497974.5625 557051.875,498219.03125 557141.75,498655.34375 557169.4375,499001.65625 557100.1875,499250.96875 556933.9375,499167.875 556615.375,499230.1875 556407.625,499392.78125 556362.75,499385.90625 556279.875,499598.5 556067.3125,499680.25 555952.8125,499218.5625 554988.875,498775.65625 554860.1875,498674.5 554832.5625,498282.0 554734.4375,498020.34375 554554.5625,497709.59375 554374.6875,497614.84375 554374.6875,497519.46875 554369.1875,497297.3125 554359.9375,496852.96875 554355.3125,496621.125 554351.375,496695.75 554454.625,496771.59375 554604.625,496836.3125 554734.0625,496868.65625 554831.125,496847.09375 554863.4375,496760.8125 554863.4375,496663.75 554928.125,496620.625 554992.875,496555.90625 555025.1875,496448.0625 554992.875,496372.5625 555025.1875,496351.0 555133.0625,496415.71875 555197.75,496480.40625 555294.8125,496480.40625 555381.0625,496430.875 555430.75,496446.0625 555547.375,496490.53125 555849.625,496526.09375 556240.75,496721.65625 556596.375,496924.90625 556774.1875,497006.125 556845.25,497281.71875 556978.625,497610.625 556969.6875,497859.53125 556969.6875,497974.5625 557051.875";
for (String item : coords.split(",")) {
String[] coord = item.split(" ");
geo.addCoordinate(Double.parseDouble(coord[0]),
Double.parseDouble(coord[1]));
}
ogrFeature.setGeometry(geo);
ogrFeature.addGeoMeasure("CLNAME", "STRING", "Loisiana Township");
ogrFeature.addGeoMeasure("COUNT", "FLOAT", "1");
BaseDAO<OGRFeature> ogrDao = new BaseDAO<OGRFeature>(
OGRFeature.class);
ogrDao.save(ogrFeature);
try {
resp.getWriter()
.println("OGRFeature: " + ogrFeature.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("printOGRFeature".equals(action)) {
OGRFeatureDao ogrFeatureDao = new OGRFeatureDao();
FeatureType featureType = FeatureType.valueOf(req
.getParameter("featureType"));
List<OGRFeature> ogrFeatureList = ogrFeatureDao
.listByCountryAndType(req.getParameter("countryCode"),
featureType, null);
try {
int i = 1;
if (ogrFeatureList != null && !ogrFeatureList.isEmpty()) {
for (OGRFeature item : ogrFeatureList) {
resp.getWriter().println(
"i: " + i + " sub1" + item.getSub1()
+ " sub2: " + item.getSub2());
resp.getWriter().println(
" OGRFeature: " + item.toString());
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("resetLRAP".equals(action)) {
try {
AccessPointDao apDao = new AccessPointDao();
Random rand = new Random();
for (AccessPoint ap : apDao.list("all")) {
if ((ap.getCountryCode() == null || ap.getCountryCode()
.equals("US"))
&& (ap.getLatitude() != null && ap.getLongitude() != null)) {
if (ap.getLatitude() > 5.0 && ap.getLatitude() < 11) {
if (ap.getLongitude() < -9
&& ap.getLongitude() > -11) {
ap.setCountryCode("LR");
apDao.save(ap);
resp.getWriter()
.println(
"Found "
+ ap.getCommunityCode()
+ "mapped to US changing mapping to LR \n");
}
}
} else if (ap.getCommunityCode() == null) {
ap.setCommunityCode(rand.nextLong() + "");
apDao.save(ap);
resp.getWriter().println(
"Found " + ap.getCommunityCode()
+ "added random community code \n");
}
}
} catch (IOException e) {
log.log(Level.SEVERE, "Could not execute test", e);
}
} else if ("populateAccessPointMetricSummary".equals(action)) {
OGRFeatureDao ogrFeatureDao = new OGRFeatureDao();
AccessPointMetricSummaryDao apmsDao = new AccessPointMetricSummaryDao();
// List<OGRFeature> ogrList =
// ogrFeatureDao.listByCountryAndType("LR",
// FeatureType.SUB_COUNTRY_OTHER);
Boolean firstTimeFlag = false;
// for (OGRFeature item : ogrList) {
// AccessPointMetricSummary apms = new AccessPointMetricSummary();
// apms.setCount(1L);
// apms.setCountry("LR");
// apms.setSubLevel(1);
// apms.setSubValue(item.getSub1());
// apms.setShardNum(1);
// apms.setParentSubName("LR");
// apms.setMetricName("WATER_POINT");
// apmsDao.save(apms);
// }
} else if ("populateStandardScoring".equals(action)) {
StandardScoringTest sst = new StandardScoringTest();
sst.populateData();
} else if ("clearSurveyInstanceQAS".equals(action)) {
// QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao();
// for (QuestionAnswerStore qas : qasDao.list("all")) {
// qasDao.delete(qas);
// }
// SurveyInstanceDAO siDao = new SurveyInstanceDAO();
// for (SurveyInstance si : siDao.list("all")) {
// siDao.delete(si);
// }
AccessPointDao apDao = new AccessPointDao();
for (AccessPoint ap : apDao.list("all"))
apDao.delete(ap);
} else if ("SurveyInstance".equals(action)) {
SurveyInstanceDAO siDao = new SurveyInstanceDAO();
List<SurveyInstance> siList = siDao.listSurveyInstanceBySurveyId(
1362011L, null);
Cursor cursor = JDOCursorHelper.getCursor(siList);
int i = 0;
while (siList.size() > 0) {
for (SurveyInstance si : siList) {
System.out.println(i++ + " " + si.toString());
String surveyInstanceId = new Long(si.getKey().getId())
.toString();
Queue queue = QueueFactory.getDefaultQueue();
queue.add(TaskOptions.Builder
.withUrl("/app_worker/surveytask")
.param("action", "reprocessMapSurveyInstance")
.param("id", surveyInstanceId));
log.info("submiting task for SurveyInstanceId: "
+ surveyInstanceId);
}
siList = siDao.listSurveyInstanceBySurveyId(1362011L,
cursor.toWebSafeString());
cursor = JDOCursorHelper.getCursor(siList);
}
System.out.println("finished");
} else if ("rotateImage".equals(action)) {
AccessPointManagerServiceImpl apmI = new AccessPointManagerServiceImpl();
String test1 = "http://waterforpeople.s3.amazonaws.com/images/wfpPhoto10062903227521.jpg";
// String test2 =
// "http://waterforpeople.s3.amazonaws.com/images/hn/ch003[1].jpg";
writeImageToResponse(resp, test1);
apmI.setUploadS3Flag(false);
// apmI.rotateImage(test2);
} else if ("clearSurveyGroupGraph".equals(action)) {
SurveyGroupDAO sgDao = new SurveyGroupDAO();
sgDao.delete(sgDao.list("all"));
SurveyDAO surveyDao = new SurveyDAO();
surveyDao.delete(surveyDao.list("all"));
QuestionGroupDao qgDao = new QuestionGroupDao();
qgDao.delete(qgDao.list("all"));
QuestionDao qDao = new QuestionDao();
qDao.delete(qDao.list("all"));
QuestionHelpMediaDao qhDao = new QuestionHelpMediaDao();
qhDao.delete(qhDao.list("all"));
QuestionOptionDao qoDao = new QuestionOptionDao();
qoDao.delete(qoDao.list("all"));
TranslationDao tDao = new TranslationDao();
tDao.delete(tDao.list("all"));
} else if ("replicateDeviceFiles".equals(action)) {
SurveyInstanceDAO siDao = new SurveyInstanceDAO();
for (SurveyInstance si : siDao.list("all")) {
siDao.delete(si);
}
QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao();
for (QuestionAnswerStore qas : qasDao.list("all")) {
qasDao.delete(qas);
}
DeviceFilesDao dfDao = new DeviceFilesDao();
for (DeviceFiles df : dfDao.list("all")) {
dfDao.delete(df);
}
DeviceFilesReplicationImporter dfri = new DeviceFilesReplicationImporter();
dfri.executeImport("http://watermapmonitordev.appspot.com",
"http://localhost:8888");
Set<String> dfSet = new HashSet<String>();
for (DeviceFiles df : dfDao.list("all")) {
dfSet.add(df.getURI());
}
DeviceFilesServiceImpl dfsi = new DeviceFilesServiceImpl();
int i = 0;
try {
resp.getWriter().println(
"Found " + dfSet.size() + " distinct files to process");
for (String s : dfSet) {
dfsi.reprocessDeviceFile(s);
resp.getWriter().println(
"submitted " + s + " for reprocessing");
i++;
if (i > 10)
break;
}
} catch (IOException e) {
log.log(Level.SEVERE, "Could not execute test", e);
}
} else if ("addDeviceFiles".equals(action)) {
DeviceFilesDao dfDao = new DeviceFilesDao();
DeviceFiles df = new DeviceFiles();
df.setURI("http://waterforpeople.s3.amazonaws.com/devicezip/wfp1737657928520.zip");
df.setCreatedDateTime(new Date());
df.setPhoneNumber("a4:ed:4e:54:ef:6d");
df.setChecksum("1149406886");
df.setProcessedStatus(StatusCode.ERROR_INFLATING_ZIP);
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd");
java.util.Date date = new java.util.Date();
String dateTime = dateFormat.format(date);
df.setProcessDate(dateTime);
dfDao.save(df);
} else if ("populateScoreBuckets".equals(action)) {
BaseDAO<StandardScoreBucket> scDao = new BaseDAO<StandardScoreBucket>(
StandardScoreBucket.class);
ArrayList<String> scoreBuckets = new ArrayList<String>();
scoreBuckets.add("WATERPOINTLEVELOFSERVICE");
scoreBuckets.add("WATERPOINTSUSTAINABILITY");
scoreBuckets.add("PUBLICINSTITUTIONLEVELOFSERVICE");
scoreBuckets.add("PUBLICINSTITUTIONSUSTAINABILITY");
for (String item : scoreBuckets) {
StandardScoreBucket sbucket = new StandardScoreBucket();
sbucket.setName(item);
scDao.save(sbucket);
}
} else if ("testSaveRegion".equals(action)) {
GeoRegionHelper geoHelp = new GeoRegionHelper();
ArrayList<String> regionLines = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
StringBuilder builder = new StringBuilder();
builder.append("1,").append("" + i).append(",test,")
.append(20 + i + ",").append(30 + i + "\n");
regionLines.add(builder.toString());
}
geoHelp.processRegionsSurvey(regionLines);
try {
resp.getWriter().print("Save complete");
} catch (IOException e) {
log.log(Level.SEVERE, "Could not save test region", e);
}
} else if ("clearAccessPoint".equals(action)) {
try {
AccessPointDao apDao = new AccessPointDao();
for (AccessPoint ap : apDao.list("all")) {
apDao.delete(ap);
try {
resp.getWriter().print(
"Finished Deleting AP: " + ap.toString());
} catch (IOException e) {
log.log(Level.SEVERE, "Could not delete ap");
}
}
resp.getWriter().print("Deleted AccessPoints complete");
BaseDAO<AccessPointStatusSummary> apsDao = new BaseDAO<AccessPointStatusSummary>(
AccessPointStatusSummary.class);
for (AccessPointStatusSummary item : apsDao.list("all")) {
apsDao.delete(item);
}
resp.getWriter().print("Deleted AccessPointStatusSummary");
MapFragmentDao mfDao = new MapFragmentDao();
for (MapFragment item : mfDao.list("all")) {
mfDao.delete(item);
}
resp.getWriter().print("Cleared MapFragment Table");
} catch (IOException e) {
log.log(Level.SEVERE, "Could not clear AP and APStatusSummary",
e);
}
} else if ("loadErrorPoints".equals(action)) {
MapFragmentDao mfDao = new MapFragmentDao();
AccessPointDao apDao = new AccessPointDao();
for (int j = 0; j < 1; j++) {
Double lat = 0.0;
Double lon = 0.0;
for (int i = 0; i < 5; i++) {
AccessPoint ap = new AccessPoint();
ap.setLatitude(lat);
ap.setLongitude(lon);
Calendar calendar = Calendar.getInstance();
Date today = new Date();
calendar.setTime(today);
calendar.add(Calendar.YEAR, -1 * i);
System.out
.println("AP: " + ap.getLatitude() + "/"
+ ap.getLongitude() + "Date: "
+ calendar.getTime());
ap.setCollectionDate(calendar.getTime());
ap.setAltitude(0.0);
ap.setCommunityCode("test" + new Date());
ap.setCommunityName("test" + new Date());
ap.setPhotoURL("http://test.com");
ap.setPointType(AccessPoint.AccessPointType.WATER_POINT);
if (i == 0)
ap.setPointStatus(AccessPoint.Status.FUNCTIONING_HIGH);
else if (i == 1)
ap.setPointStatus(AccessPoint.Status.FUNCTIONING_OK);
else if (i == 2)
ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS);
else
ap.setPointStatus(Status.NO_IMPROVED_SYSTEM);
if (i % 2 == 0)
ap.setTypeTechnologyString("Kiosk");
else
ap.setTypeTechnologyString("Afridev Handpump");
apDao.save(ap);
// ms.performSummarization("" + ap.getKey().getId(), "");
if (i % 50 == 0)
log.log(Level.INFO, "Loaded to " + i);
}
}
try {
resp.getWriter().println("Finished loading aps");
} catch (IOException e) {
e.printStackTrace();
}
} else if ("loadLots".equals(action)) {
AccessPointTest apt = new AccessPointTest();
apt.loadLots(resp, 500);
} else if ("loadCountries".equals(action)) {
Country c = new Country();
c.setIsoAlpha2Code("HN");
c.setName("Honduras");
c.setIncludeInExternal(true);
c.setCentroidLat(14.7889035);
c.setCentroidLon(-86.9500379);
c.setZoomLevel(8);
BaseDAO<Country> countryDAO = new BaseDAO<Country>(Country.class);
countryDAO.save(c);
Country c2 = new Country();
c2.setIsoAlpha2Code("MW");
c2.setName("Malawi");
c2.setIncludeInExternal(true);
c2.setCentroidLat(-13.0118377);
c2.setCentroidLon(33.9984484);
c2.setZoomLevel(7);
countryDAO.save(c2);
Country c3 = new Country();
c3.setIsoAlpha2Code("UG");
c3.setName("Uganda");
c3.setIncludeInExternal(true);
c3.setCentroidLat(1.1027);
c3.setCentroidLon(32.3968);
c3.setZoomLevel(7);
countryDAO.save(c3);
Country c4 = new Country();
c4.setIsoAlpha2Code("KE");
c4.setName("Kenya");
c4.setIncludeInExternal(true);
c4.setCentroidLat(-1.26103461);
c4.setCentroidLon(36.74724467);
c4.setZoomLevel(7);
countryDAO.save(c4);
} else if ("testAPKml".equals(action)) {
MapFragmentDao mfDao = new MapFragmentDao();
BaseDAO<TechnologyType> ttDao = new BaseDAO<TechnologyType>(
TechnologyType.class);
List<TechnologyType> ttList = ttDao.list("all");
for (TechnologyType tt : ttList)
ttDao.delete(tt);
TechnologyType tt = new TechnologyType();
tt.setCode("Afridev Handpump");
tt.setName("Afridev Handpump");
ttDao.save(tt);
TechnologyType tt2 = new TechnologyType();
tt2.setCode("Kiosk");
tt2.setName("Kiosk");
ttDao.save(tt2);
KMLHelper kmlHelper = new KMLHelper();
kmlHelper.buildMap();
List<MapFragment> mfList = mfDao
.searchMapFragments("ALL", null, null,
FRAGMENTTYPE.GLOBAL_ALL_PLACEMARKS, "all", null,
null);
try {
for (MapFragment mfItem : mfList) {
String contents = ZipUtil
.unZip(mfItem.getBlob().getBytes());
log.log(Level.INFO, "Contents Length: " + contents.length());
resp.setContentType("application/vnd.google-earth.kmz+xml");
ServletOutputStream out = resp.getOutputStream();
resp.setHeader("Content-Disposition",
"inline; filename=waterforpeoplemapping.kmz;");
out.write(mfItem.getBlob().getBytes());
out.flush();
}
} catch (IOException ie) {
log.log(Level.SEVERE, "Could not list fragment");
}
} else if ("deleteSurveyGraph".equals(action)) {
deleteAll(SurveyGroup.class);
deleteAll(Survey.class);
deleteAll(QuestionGroup.class);
deleteAll(Question.class);
deleteAll(Translation.class);
deleteAll(QuestionOption.class);
deleteAll(QuestionHelpMedia.class);
try {
resp.getWriter().println("Finished deleting survey graph");
} catch (IOException iex) {
log.log(Level.SEVERE, "couldn't delete surveyGraph" + iex);
}
}
else if ("saveSurveyGroupRefactor".equals(action)) {
SurveyGroupDAO sgDao = new SurveyGroupDAO();
createSurveyGroupGraph(resp);
try {
List<SurveyGroup> savedSurveyGroups = sgDao.list("all");
for (SurveyGroup sgItem : savedSurveyGroups) {
resp.getWriter().println("SG: " + sgItem.getCode());
for (Survey survey : sgItem.getSurveyList()) {
resp.getWriter().println(
" Survey:" + survey.getName());
for (Map.Entry<Integer, QuestionGroup> entry : survey
.getQuestionGroupMap().entrySet()) {
resp.getWriter().println(
" QuestionGroup: " + entry.getKey()
+ ":" + entry.getValue().getDesc());
for (Map.Entry<Integer, Question> questionEntry : entry
.getValue().getQuestionMap().entrySet()) {
resp.getWriter().println(
" Question"
+ questionEntry.getKey()
+ ":"
+ questionEntry.getValue()
.getText());
for (Map.Entry<Integer, QuestionHelpMedia> qhmEntry : questionEntry
.getValue().getQuestionHelpMediaMap()
.entrySet()) {
resp.getWriter().println(
" QuestionHelpMedia"
+ qhmEntry.getKey()
+ ":"
+ qhmEntry.getValue()
.getText());
/*
* for (Key tKey : qhmEntry.getValue()
* .getAltTextKeyList()) { Translation t =
* tDao.getByKey(tKey);
* resp.getWriter().println(
* " QHMAltText" +
* t.getLanguageCode() + ":" + t.getText());
* }
*/
}
}
}
}
}
} catch (IOException e) {
log.log(Level.SEVERE, "Could not save sg");
}
} else if ("createAP".equals(action)) {
AccessPoint ap = new AccessPoint();
ap.setCollectionDate(new Date());
ap.setCommunityCode(new Random().toString());
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setCountryCode("SZ");
ap.setPointType(AccessPointType.WATER_POINT);
AccessPointHelper helper = new AccessPointHelper();
helper.saveAccessPoint(ap);
} else if ("createInstance".equals(action)) {
SurveyInstance si = new SurveyInstance();
si.setCollectionDate(new Date());
ArrayList<QuestionAnswerStore> store = new ArrayList<QuestionAnswerStore>();
QuestionAnswerStore ans = new QuestionAnswerStore();
ans.setQuestionID("2166031");
ans.setValue("12.379456758498787|-85.53869247436275|548.0|1kvc9dqy");
ans.setType("GEO");
ans.setSurveyId(1360012L);
store.add(ans);
si.setQuestionAnswersStore(store);
si.setUuid("12345");
SurveyInstanceDAO dao = new SurveyInstanceDAO();
si = dao.save(si);
ans.setSurveyInstanceId(si.getKey().getId());
dao.save(ans);
// Queue summQueue = QueueFactory.getQueue("dataSummarization");
// summQueue.add(TaskOptions.Builder
// .withUrl("/app_worker/datasummarization")
// .param("objectKey", si.getKey().getId() + "")
// .param("type", "SurveyInstance"));
} else if ("createCommunity".equals(action)) {
CommunityDao dao = new CommunityDao();
Country c = new Country();
c.setIsoAlpha2Code("CA");
c.setName("Canada");
c.setDisplayName("Canada");
Community comm = new Community();
comm.setCommunityCode("ON");
dao.save(c);
comm.setCountryCode("CA");
comm.setLat(54.99);
comm.setLon(-74.72);
dao.save(comm);
c = new Country();
c.setIsoAlpha2Code("US");
c.setName("United States");
c.setDisplayName("Unites States");
comm = new Community();
comm.setCommunityCode("Omaha");
comm.setCountryCode("US");
comm.setLat(34.99);
comm.setLon(-74.72);
dao.save(c);
dao.save(comm);
} else if ("addPhone".equals(action)) {
String phoneNumber = req.getParameter("phoneNumber");
Device d = new Device();
d.setPhoneNumber(phoneNumber);
d.setDeviceType(DeviceType.CELL_PHONE_ANDROID);
if (req.getParameter("esn") != null)
d.setEsn(req.getParameter("esn"));
if (req.getParameter("gallatinSoftwareManifest") != null)
d.setGallatinSoftwareManifest(req
.getParameter("gallatinSoftwareManifest"));
d.setInServiceDate(new Date());
DeviceDAO deviceDao = new DeviceDAO();
deviceDao.save(d);
try {
resp.getWriter().println("finished adding " + phoneNumber);
} catch (Exception e) {
e.printStackTrace();
}
} else if ("createAPSummary".equals(action)) {
AccessPointStatusSummary sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2000");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
AccessPointStatusSummaryDao dao = new AccessPointStatusSummaryDao();
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2001");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2003");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2004");
sum.setStatus(AccessPoint.Status.FUNCTIONING_OK);
dao.save(sum);
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2000");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2001");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2003");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2004");
sum.setStatus(AccessPoint.Status.FUNCTIONING_OK);
dao.save(sum);
} else if ("createApHistory".equals(action)) {
GregorianCalendar cal = new GregorianCalendar();
AccessPointHelper apHelper = new AccessPointHelper();
AccessPoint ap = new AccessPoint();
cal.set(Calendar.YEAR, 2000);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(300l);
ap.setCostPer(43.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2001);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(317l);
ap.setCostPer(40.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2002);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(340l);
ap.setCostPer(37.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2003);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(340l);
ap.setCostPer(34.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2004);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(338l);
ap.setCostPer(38.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2000);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(170l);
ap.setCostPer(19.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2001);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(201l);
ap.setCostPer(19.00);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2002);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(211l);
ap.setCostPer(17.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2003);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(220l);
ap.setCostPer(25.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2004);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(175l);
ap.setCostPer(24.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
} else if ("generateGeocells".equals(action)) {
AccessPointDao apDao = new AccessPointDao();
List<AccessPoint> apList = apDao.list(null);
if (apList != null) {
for (AccessPoint ap : apList) {
if (ap.getGeocells() == null
|| ap.getGeocells().size() == 0) {
if (ap.getLatitude() != null
&& ap.getLongitude() != null) {
ap.setGeocells(GeocellManager.generateGeoCell(new Point(
ap.getLatitude(), ap.getLongitude())));
apDao.save(ap);
}
}
}
}
} else if ("loadExistingSurvey".equals(action)) {
SurveyGroup sg = new SurveyGroup();
sg.setKey(KeyFactory.createKey(SurveyGroup.class.getSimpleName(),
2L));
sg.setName("test" + new Date());
sg.setCode("test" + new Date());
SurveyGroupDAO sgDao = new SurveyGroupDAO();
sgDao.save(sg);
Survey s = new Survey();
s.setKey(KeyFactory.createKey(Survey.class.getSimpleName(), 2L));
s.setName("test" + new Date());
s.setSurveyGroupId(sg.getKey().getId());
SurveyDAO surveyDao = new SurveyDAO();
surveyDao.save(s);
} else if ("saveAPMapping".equals(action)) {
SurveyAttributeMapping mapping = new SurveyAttributeMapping();
mapping.setAttributeName("status");
mapping.setObjectName(AccessPoint.class.getCanonicalName());
mapping.setSurveyId(1L);
mapping.setSurveyQuestionId("q1");
SurveyAttributeMappingDao samDao = new SurveyAttributeMappingDao();
samDao.save(mapping);
} else if ("listAPMapping".equals(action)) {
SurveyAttributeMappingDao samDao = new SurveyAttributeMappingDao();
List<SurveyAttributeMapping> mappings = samDao
.listMappingsBySurvey(1L);
if (mappings != null) {
System.out.println(mappings.size());
}
} else if ("saveSurveyGroup".equals(action)) {
try {
SurveyGroupDAO sgDao = new SurveyGroupDAO();
List<SurveyGroup> sgList = sgDao.list("all");
for (SurveyGroup sg : sgList) {
sgDao.delete(sg);
}
resp.getWriter().println("Deleted all survey groups");
SurveyDAO surveyDao = new SurveyDAO();
List<Survey> surveyList = surveyDao.list("all");
for (Survey survey : surveyList) {
try {
surveyDao.delete(survey);
} catch (IllegalDeletionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
resp.getWriter().println("Deleted all surveys");
resp.getWriter().println("Deleted all surveysurveygroupassocs");
QuestionGroupDao qgDao = new QuestionGroupDao();
List<QuestionGroup> qgList = qgDao.list("all");
for (QuestionGroup qg : qgList) {
qgDao.delete(qg);
}
resp.getWriter().println("Deleted all question groups");
QuestionDao qDao = new QuestionDao();
List<Question> qList = qDao.list("all");
for (Question q : qList) {
try {
qDao.delete(q);
} catch (IllegalDeletionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
resp.getWriter().println("Deleted all Questions");
QuestionOptionDao qoDao = new QuestionOptionDao();
List<QuestionOption> qoList = qoDao.list("all");
for (QuestionOption qo : qoList)
qoDao.delete(qo);
resp.getWriter().println("Deleted all QuestionOptions");
resp.getWriter().println("Deleted all questions");
resp.getWriter().println(
"Finished deleting and reloading SurveyGroup graph");
} catch (IOException e) {
e.printStackTrace();
}
} else if ("testPublishSurvey".equals(action)) {
try {
SurveyGroupDto sgDto = new SurveyServiceImpl()
.listSurveyGroups(null, true, false, false)
.getPayload().get(0);
resp.getWriter().println(
"Got Survey Group: " + sgDto.getCode() + " Survey: "
+ sgDto.getSurveyList().get(0).getKeyId());
SurveyContainerDao scDao = new SurveyContainerDao();
SurveyContainer sc = scDao.findBySurveyId(sgDto.getSurveyList()
.get(0).getKeyId());
if (sc != null) {
scDao.delete(sc);
resp.getWriter().println(
"Deleted existing SurveyContainer for: "
+ sgDto.getSurveyList().get(0).getKeyId());
}
resp.getWriter().println(
"Result of publishing survey: "
+ new SurveyServiceImpl().publishSurvey(sgDto
.getSurveyList().get(0).getKeyId()));
sc = scDao.findBySurveyId(sgDto.getSurveyList().get(0)
.getKeyId());
resp.getWriter().println(
"Survey Document result from publish: \n\n\n\n"
+ sc.getSurveyDocument().getValue());
} catch (IOException ex) {
ex.printStackTrace();
}
} else if ("createTestSurveyForEndToEnd".equals(action)) {
createTestSurveyForEndToEnd();
} else if ("deleteSurveyFragments".equals(action)) {
deleteAll(SurveyXMLFragment.class);
} else if ("migratePIToSchool".equals(action)) {
try {
resp.getWriter().println(
"Has more? "
+ migratePointType(
AccessPointType.PUBLIC_INSTITUTION,
AccessPointType.SCHOOL));
} catch (IOException e) {
e.printStackTrace();
}
} else if ("createDevice".equals(action)) {
DeviceDAO devDao = new DeviceDAO();
Device device = new Device();
device.setPhoneNumber("9175667663");
device.setDeviceType(DeviceType.CELL_PHONE_ANDROID);
devDao.save(device);
} else if ("reprocessSurveys".equals(action)) {
try {
reprocessSurveys(req.getParameter("date"));
} catch (ParseException e) {
try {
resp.getWriter().println("Couldn't reprocess: " + e);
} catch (IOException e1) {
e1.printStackTrace();
}
}
} else if ("importallsurveys".equals(action)) {
// Only run in dev hence hardcoding
SurveyReplicationImporter sri = new SurveyReplicationImporter();
sri.executeImport("http://watermapmonitordev.appspot.com", null);
// sri.executeImport("http://localhost:8888",
// "http://localhost:8888");
} else if ("importsinglesurvey".equals(action)) {
TaskOptions options = TaskOptions.Builder
.withUrl("/app_worker/dataprocessor")
.param(DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.IMPORT_REMOTE_SURVEY_ACTION)
.param(DataProcessorRequest.SOURCE_PARAM,
req.getParameter("source"))
.param(DataProcessorRequest.SURVEY_ID_PARAM,
req.getParameter("surveyId"));
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
} else if ("rescoreap".equals(action)) {
TaskOptions options = TaskOptions.Builder
.withUrl("/app_worker/dataprocessor")
.param(DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.RESCORE_AP_ACTION)
.param(DataProcessorRequest.COUNTRY_PARAM,
req.getParameter("country"));
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
} else if ("deleteSurveyResponses".equals(action)) {
if (req.getParameter("surveyId") == null) {
try {
resp.getWriter()
.println("surveyId is a required parameter");
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
deleteSurveyResponses(
Integer.parseInt(req.getParameter("surveyId")),
Integer.parseInt(req.getParameter("count")));
}
} else if ("fixNameQuestion".equals(action)) {
if (req.getParameter("questionId") == null) {
try {
resp.getWriter().println(
"questionId is a required parameter");
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
fixNameQuestion(req.getParameter("questionId"));
}
} else if ("createSurveyAssignment".equals(action)) {
Device device = new Device();
device.setDeviceType(DeviceType.CELL_PHONE_ANDROID);
device.setPhoneNumber("1111111111");
device.setInServiceDate(new Date());
BaseDAO<Device> deviceDao = new BaseDAO<Device>(Device.class);
deviceDao.save(device);
SurveyAssignmentServiceImpl sasi = new SurveyAssignmentServiceImpl();
SurveyAssignmentDto dto = new SurveyAssignmentDto();
SurveyDAO surveyDao = new SurveyDAO();
List<Survey> surveyList = surveyDao.list("all");
SurveyAssignment sa = new SurveyAssignment();
BaseDAO<SurveyAssignment> surveyAssignmentDao = new BaseDAO<SurveyAssignment>(
SurveyAssignment.class);
sa.setCreatedDateTime(new Date());
sa.setCreateUserId(-1L);
ArrayList<Long> deviceList = new ArrayList<Long>();
deviceList.add(device.getKey().getId());
sa.setDeviceIds(deviceList);
ArrayList<SurveyDto> surveyDtoList = new ArrayList<SurveyDto>();
for (Survey survey : surveyList) {
sa.addSurvey(survey.getKey().getId());
SurveyDto surveyDto = new SurveyDto();
surveyDto.setKeyId(survey.getKey().getId());
surveyDtoList.add(surveyDto);
}
sa.setStartDate(new Date());
sa.setEndDate(new Date());
sa.setName(new Date().toString());
DeviceDto deviceDto = new DeviceDto();
deviceDto.setKeyId(device.getKey().getId());
deviceDto.setPhoneNumber(device.getPhoneNumber());
ArrayList<DeviceDto> deviceDtoList = new ArrayList<DeviceDto>();
deviceDtoList.add(deviceDto);
dto.setDevices(deviceDtoList);
dto.setSurveys(surveyDtoList);
dto.setEndDate(new Date());
dto.setLanguage("en");
dto.setName("Test Assignment: " + new Date().toString());
dto.setStartDate(new Date());
sasi.saveSurveyAssignment(dto);
// sasi.deleteSurveyAssignment(dto);
} else if ("populateAssignmentId".equalsIgnoreCase(action)) {
populateAssignmentId(Long.parseLong(req
.getParameter("assignmentId")));
} else if ("testDSJQDelete".equals(action)) {
DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO();
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -10);
Date then = cal.getTime();
DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue();
dsjq.setDevicePhoneNumber("2019561591");
dsjq.setEffectiveEndDate(then);
Random rand = new Random();
dsjq.setAssignmentId(rand.nextLong());
dsjDAO.save(dsjq);
DeviceSurveyJobQueue dsjq2 = new DeviceSurveyJobQueue();
dsjq2.setDevicePhoneNumber("2019561591");
cal.add(Calendar.DAY_OF_MONTH, 20);
dsjq2.setEffectiveEndDate(cal.getTime());
dsjq2.setAssignmentId(rand.nextLong());
dsjDAO.save(dsjq2);
DeviceSurveyJobQueueDAO dsjqDao = new DeviceSurveyJobQueueDAO();
List<DeviceSurveyJobQueue> dsjqList = dsjqDao
.listAssignmentsWithEarlierExpirationDate(new Date());
for (DeviceSurveyJobQueue item : dsjqList) {
SurveyTaskUtil.spawnDeleteTask("deleteDeviceSurveyJobQueue",
item.getAssignmentId());
}
} else if ("loadDSJ".equals(action)) {
SurveyDAO surveyDao = new SurveyDAO();
List<Survey> surveyList = surveyDao.list("all");
for (Survey item : surveyList) {
DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO();
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -10);
Date then = cal.getTime();
DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue();
dsjq.setDevicePhoneNumber("2019561591");
dsjq.setEffectiveEndDate(then);
Random rand = new Random();
dsjq.setAssignmentId(rand.nextLong());
dsjq.setSurveyID(item.getKey().getId());
dsjDAO.save(dsjq);
}
for (int i = 0; i < 20; i++) {
DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO();
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -10);
Date then = cal.getTime();
DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue();
dsjq.setDevicePhoneNumber("2019561591");
dsjq.setEffectiveEndDate(then);
Random rand = new Random();
dsjq.setAssignmentId(rand.nextLong());
dsjq.setSurveyID(rand.nextLong());
dsjDAO.save(dsjq);
}
try {
resp.getWriter().println("finished");
} catch (IOException e1) {
e1.printStackTrace();
}
} else if ("deleteUnusedDSJQueue".equals(action)) {
try {
SurveyDAO surveyDao = new SurveyDAO();
List<Key> surveyIdList = surveyDao.listSurveyIds();
List<Long> ids = new ArrayList<Long>();
for (Key key : surveyIdList)
ids.add(key.getId());
DeviceSurveyJobQueueDAO dsjqDao = new DeviceSurveyJobQueueDAO();
List<DeviceSurveyJobQueue> deleteList = new ArrayList<DeviceSurveyJobQueue>();
for (DeviceSurveyJobQueue item : dsjqDao.listAllJobsInQueue()) {
Long dsjqSurveyId = item.getSurveyID();
Boolean found = ids.contains(dsjqSurveyId);
if (!found) {
deleteList.add(item);
resp.getWriter().println(
"Marking " + item.getId() + " survey: "
+ item.getSurveyID() + " for deletion");
}
}
dsjqDao.delete(deleteList);
resp.getWriter().println("finished");
} catch (IOException e1) {
e1.printStackTrace();
}
} else if ("testListTrace".equals(action)) {
listStacktrace();
} else if ("createEditorialContent".equals(action)) {
createEditorialContent(req.getParameter("pageName"));
} else if ("generateEditorialContent".equals(action)) {
try {
resp.getWriter().print(
generateEditorialContent(req.getParameter("pageName")));
} catch (IOException e) {
e.printStackTrace();
}
} else if ("populateperms".equals(action)) {
populatePermissions();
} else if ("testnotif".equals(action)) {
sendNotification(req.getParameter("surveyId"));
} else if ("popsurvey".equals(action)) {
SurveyDAO sDao = new SurveyDAO();
List<Survey> sList = sDao.list(null);
QuestionDao questionDao = new QuestionDao();
List<Question> qList = questionDao.listQuestionByType(sList.get(0)
.getKey().getId(), Question.Type.FREE_TEXT);
SurveyInstanceDAO instDao = new SurveyInstanceDAO();
for (int i = 0; i < 10; i++) {
SurveyInstance instance = new SurveyInstance();
instance.setSurveyId(sList.get(0).getKey().getId());
instance = instDao.save(instance);
for (int j = 0; j < qList.size(); j++) {
QuestionAnswerStore ans = new QuestionAnswerStore();
ans.setQuestionID(qList.get(j).getKey().getId() + "");
ans.setValue("" + j * i);
ans.setSurveyInstanceId(instance.getKey().getId());
// ans.setSurveyInstance(instance);
instDao.save(ans);
}
}
try {
resp.getWriter().print(sList.get(0).getKey().getId());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("testnotifhelper".equals(action)) {
NotificationHelper helper = new NotificationHelper("rawDataReport",
null);
helper.execute();
} else if ("testremotemap".equals(action)) {
createDevice("12345", 40.78, -73.95);
createDevice("777", 43.0, -78.8);
RemoteStacktrace st = new RemoteStacktrace();
st.setAcknowleged(false);
st.setPhoneNumber("12345");
st.setErrorDate(new Date());
st.setStackTrace(new Text("blah"));
RemoteStacktraceDao dao = new RemoteStacktraceDao();
dao.save(st);
st = new RemoteStacktrace();
st.setAcknowleged(false);
st.setErrorDate(new Date());
st.setPhoneNumber("777");
st.setStackTrace(new Text("ugh"));
dao.save(st);
} else if ("createMetricMapping".equals(action)) {
createMetricMapping(req.getParameter("metric"));
} else if ("listMetricSummaries".equals(action)) {
try {
resp.getWriter().print(
listMetricSummaries(
new Integer(req.getParameter("level")),
req.getParameter("name")));
} catch (IOException e) {
e.printStackTrace();
}
} else if ("deleteMetricSummaries".equals(action)) {
deleteMetricSummaries(new Integer(req.getParameter("level")),
req.getParameter("name"));
} else if ("createSurveyQuestionSummary".equals(action)) {
SurveyQuestionSummary sum = new SurveyQuestionSummary();
sum.setCount(10L);
sum.setResponse("TEST");
sum.setQuestionId("2166031");
SurveyQuestionSummaryDao dao = new SurveyQuestionSummaryDao();
dao.save(sum);
sum = new SurveyQuestionSummary();
sum.setCount(20L);
sum.setResponse("OTHER");
sum.setQuestionId("2166031");
dao.save(sum);
sum = new SurveyQuestionSummary();
sum.setCount(30L);
sum.setResponse("GWAR");
sum.setQuestionId("2166031");
dao.save(sum);
} else if ("createCountry".equals(action)) {
Country country = new Country();
country.setIsoAlpha2Code("LR");
country.setName("Liberia");
CountryDao dao = new CountryDao();
dao.save(country);
} else if ("populateSubCountry".equals(action)) {
try {
String country = req.getParameter("country");
if (country != null) {
Queue summQueue = QueueFactory
.getQueue("dataSummarization");
summQueue.add(TaskOptions.Builder
.withUrl("/app_worker/datasummarization")
.param("objectKey", country)
.param("type", "OGRFeature"));
} else {
resp.getWriter()
.println("country is a mandatory parameter");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("listSubCountry".equals(action)) {
try {
String country = req.getParameter("country");
if (country != null) {
SubCountryDao subDao = new SubCountryDao();
List<SubCountry> results = subDao.list(null);
if (results != null) {
for (SubCountry c : results) {
resp.getWriter().println(c.toString());
}
}
} else {
resp.getWriter()
.println("country is a mandatory parameter");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("clearcache".equals(action)) {
CacheFactory cacheFactory;
try {
cacheFactory = CacheManager.getInstance().getCacheFactory();
Cache cache = cacheFactory.createCache(Collections.emptyMap());
cache.clear();
} catch (CacheException e) {
e.printStackTrace();
}
} else if ("startProjectFlagUpdate".equals(action)) {
DataProcessorRestServlet.sendProjectUpdateTask(
req.getParameter("country"), null);
} else if (DataProcessorRequest.REBUILD_QUESTION_SUMMARY_ACTION
.equals(action)) {
TaskOptions options = TaskOptions.Builder.withUrl(
"/app_worker/dataprocessor").param(
DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.REBUILD_QUESTION_SUMMARY_ACTION);
if (req.getParameter("bypassBackend") == null
|| !req.getParameter("bypassBackend").equals("true")) {
// change the host so the queue invokes the backend
options = options
.header("Host",
BackendServiceFactory.getBackendService()
.getBackendAddress("dataprocessor"));
}
String surveyId = req
.getParameter(DataProcessorRequest.SURVEY_ID_PARAM);
if (surveyId != null && surveyId.trim().length() > 0) {
options.param(DataProcessorRequest.SURVEY_ID_PARAM, surveyId);
}
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
} else if ("deleteallqsum".equals(action)) {
DeleteObjectUtil dou = new DeleteObjectUtil();
dou.deleteAllObjects("SurveyQuestionSummary");
} else if ("fixNullSubmitter".equals(action)) {
TaskOptions options = TaskOptions.Builder.withUrl(
"/app_worker/dataprocessor").param(
DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.FIX_NULL_SUBMITTER_ACTION);
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
} else if ("createVals".equals(action)) {
SurveyedLocaleDao localeDao = new SurveyedLocaleDao();
List<SurveyedLocale> lList = localeDao.list(null);
if (lList != null && lList.size() > 0) {
List<SurveyalValue> valList = new ArrayList<SurveyalValue>();
for (int i = 0; i < 50; i++) {
SurveyalValue val = new SurveyalValue();
val.setSurveyedLocaleId(lList.get(0).getKey().getId());
val.setStringValue("val:" + i);
val.setQuestionText("TEXT: " + i);
val.setLocaleType(lList.get(0).getLocaleType());
val.setQuestionType("FREE_TEXT");
val.setSurveyInstanceId(lList.get(0)
.getLastSurveyalInstanceId());
valList.add(val);
}
localeDao.save(valList);
}
} else if ("fixDuplicateOtherText".equals(action)) {
TaskOptions options = TaskOptions.Builder.withUrl(
"/app_worker/dataprocessor").param(
DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.FIX_DUPLICATE_OTHER_TEXT_ACTION);
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
} else if ("fixNullGroupNames".equals(action)) {
fixNullQuestionGroupNames();
} else if ("trimOptions".equals(action)) {
TaskOptions options = TaskOptions.Builder.withUrl(
"/app_worker/dataprocessor").param(
DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.TRIM_OPTIONS);
if (req.getParameter("bypassBackend") == null
|| !req.getParameter("bypassBackend").equals("true")) {
// change the host so the queue invokes the backend
options = options
.header("Host",
BackendServiceFactory.getBackendService()
.getBackendAddress("dataprocessor"));
}
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
} else if ("testTemplateOverride".equals(action)) {
KMLGenerator gen = new KMLGenerator();
SurveyedLocale ap = new SurveyedLocale();
ap.setAmbiguous(false);
ap.setCountryCode("US");
ap.setCreatedDateTime(new Date());
ap.setCurrentStatus("OK");
ap.setIdentifier("1234");
ap.setLastSurveyedDate(new Date());
ap.setLatitude(12d);
ap.setLongitude(12d);
try {
String result = gen.bindPlacemark(ap,
"localePlacemarkExternal.vm", null);
resp.getWriter().println(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("setSuperUser".equals(action)) {
String email = req.getParameter("email");
UserDao udao = new UserDao();
User u = udao.findUserByEmail(email);
if (u != null) {
u.setSuperAdmin(true);
}
}else if("fixImages".equals(action)){
String surveyId = req.getParameter("surveyId");
String find = req.getParameter("find");
String replace = req.getParameter("replace");
if(surveyId != null && !surveyId.trim().isEmpty() && find!=null && !find.trim().isEmpty()){
fixBadImage(surveyId,find,replace);
}
}
}
private void fixBadImage(String surveyId, String findString, String replaceString){
QuestionAnswerStoreDao dao = new QuestionAnswerStoreDao();
String replaceVal = replaceString !=null?replaceString:"";
List<QuestionAnswerStore> responses = dao.listByTypeAndDate("PHOTO", new Long(surveyId), null, Constants.ALL_RESULTS, null);
if(responses != null){
for(QuestionAnswerStore resp: responses){
if(resp.getValue()!=null && resp.getValue().contains(findString)){
resp.setValue(resp.getValue().replace(findString, replaceVal));
}
}
}
}
private void fixNullQuestionGroupNames() {
QuestionGroupDao dao = new QuestionGroupDao();
List<QuestionGroup> groups = dao.listQuestionGroupsByName(null);
if (groups != null) {
for (QuestionGroup g : groups) {
g.setName(g.getCode());
}
}
}
private void deleteMetricSummaries(Integer level, String name) {
AccessPointMetricSummaryDao sumDao = new AccessPointMetricSummaryDao();
AccessPointMetricSummary prototype = new AccessPointMetricSummary();
prototype.setMetricName(name);
prototype.setSubLevel(level);
List<AccessPointMetricSummary> sumList = sumDao.listMetrics(prototype);
if (sumList != null && sumList.size() > 0) {
sumDao.delete(sumList);
}
}
private String listMetricSummaries(Integer level, String name) {
AccessPointMetricSummaryDao sumDao = new AccessPointMetricSummaryDao();
AccessPointMetricSummary prototype = new AccessPointMetricSummary();
prototype.setMetricName(name);
prototype.setSubLevel(level);
List<AccessPointMetricSummary> sumList = sumDao.listMetrics(prototype);
StringBuilder buf = new StringBuilder();
if (sumList != null) {
for (AccessPointMetricSummary m : sumList) {
buf.append(m.toString() + ", shard: " + m.getShardNum())
.append("\n");
}
}
return buf.toString();
}
private void createMetricMapping(String name) {
AccessPointMetricMappingDao dao = new AccessPointMetricMappingDao();
List<AccessPointMetricMapping> mappingList = dao.findMappings(null,
null, name);
if (mappingList == null || mappingList.isEmpty()) {
AccessPointMetricMapping map = new AccessPointMetricMapping();
map.setFieldName(name);
map.setMetricName(name);
dao.save(map);
}
}
private Device createDevice(String num, Double lat, Double lon) {
DeviceDAO devDao = new DeviceDAO();
Device d = devDao.get(num);
if (d == null) {
d = new Device();
d.setPhoneNumber(num);
}
if (lat != null) {
d.setLastKnownLat(lat);
d.setLastKnownLon(lon);
}
return devDao.save(d);
}
private void sendNotification(String surveyId) {
// com.google.appengine.api.taskqueue.Queue queue =
// com.google.appengine.api.taskqueue.QueueFactory.getQueue("notification");
Queue queue = QueueFactory.getQueue("notification");
queue.add(TaskOptions.Builder
.withUrl("/notificationprocessor")
.param(NotificationRequest.DEST_PARAM,
"[email protected]||[email protected]")
.param(NotificationRequest.DEST_OPT_PARAM, "ATTACHMENT||LINK")
.param(NotificationRequest.SUB_ENTITY_PARAM, surveyId)
.param(NotificationRequest.TYPE_PARAM, "fieldStatusReport"));
}
private void populatePermissions() {
UserDao userDao = new UserDao();
List<Permission> permList = userDao.listPermissions();
if (permList == null) {
permList = new ArrayList<Permission>();
}
savePerm("Edit Survey", permList, userDao);
savePerm("Edit Users", permList, userDao);
savePerm("Edit Access Point", permList, userDao);
savePerm("Edit Editorial Content", permList, userDao);
savePerm("Import Survey Data", permList, userDao);
savePerm("Import Access Point Data", permList, userDao);
savePerm("Upload Survey Data", permList, userDao);
savePerm("Edit Raw Data", permList, userDao);
savePerm("Admin", permList, userDao);
savePerm("Publish Survey", permList, userDao);
savePerm("Run Reports", permList, userDao);
savePerm("Edit Immutability", permList, userDao);
savePerm("View Messages", permList, userDao);
}
private void savePerm(String name, List<Permission> permList,
UserDao userDao) {
Permission p = new Permission(name);
boolean found = false;
for (Permission perm : permList) {
if (perm.equals(p)) {
found = true;
break;
}
}
if (!found) {
userDao.save(p);
}
}
private void setupTestUser() {
UserDao userDao = new UserDao();
User user = userDao.findUserByEmail("[email protected]");
if (user == null) {
user = new User();
user.setEmailAddress("[email protected]");
}
user.setSuperAdmin(true);
user.setPermissionList(String.valueOf(AppRole.SUPER_ADMIN.getLevel()));
userDao.save(user);
}
private String generateEditorialContent(String pageName) {
String content = "";
EditorialPageDao dao = new EditorialPageDao();
EditorialPage p = dao.findByTargetPage(pageName);
List<EditorialPageContent> contentList = dao.listContentByPage(p
.getKey().getId());
try {
RuntimeServices runtimeServices = RuntimeSingleton
.getRuntimeServices();
StringReader reader = new StringReader(p.getTemplate().getValue());
SimpleNode node = runtimeServices.parse(reader, "dynamicTemplate");
Template template = new Template();
template.setRuntimeServices(runtimeServices);
template.setData(node);
template.initDocument();
Context ctx = new VelocityContext();
ctx.put("pages", contentList);
StringWriter writer = new StringWriter();
template.merge(ctx, writer);
content = writer.toString();
} catch (Exception e) {
log.log(Level.SEVERE, "Could not initialize velocity", e);
}
return content;
}
private void createEditorialContent(String pageName) {
EditorialPageDao dao = new EditorialPageDao();
EditorialPage page = new EditorialPage();
page.setTargetFileName(pageName);
page.setType("landing");
page.setTemplate(new Text(
"<html><head><title>Test Generated</title></head><body><h1>This is a test</h1><ul>#foreach( $pageContent in $pages )<li>$pageContent.heading : $pageContent.text.value</li>#end</ul>"));
page = dao.save(page);
EditorialPageContent content = new EditorialPageContent();
List<EditorialPageContent> contentList = new ArrayList<EditorialPageContent>();
content.setHeading("Heading 1");
content.setText(new Text("this is some text"));
content.setSortOrder(1L);
content.setEditorialPageId(page.getKey().getId());
contentList.add(content);
content = new EditorialPageContent();
content.setHeading("Heading 2");
content.setText(new Text("this is more text"));
content.setSortOrder(2L);
content.setEditorialPageId(page.getKey().getId());
contentList.add(content);
dao.save(contentList);
}
private void listStacktrace() {
RemoteStacktraceDao traceDao = new RemoteStacktraceDao();
List<RemoteStacktrace> result = null;
result = traceDao.listStacktrace(null, null, false, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace(null, null, true, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace("12345", null, true, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace("12345", "12345", true, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace(null, "12345", true, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace("12345", null, false, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace("12345", "12345", false, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace(null, "12345", false, null);
if (result != null) {
System.out.println(result.size() + "");
}
}
private void populateAssignmentId(Long assignmentId) {
BaseDAO<SurveyAssignment> assignmentDao = new BaseDAO<SurveyAssignment>(
SurveyAssignment.class);
SurveyAssignment assignment = assignmentDao.getByKey(assignmentId);
DeviceSurveyJobQueueDAO jobDao = new DeviceSurveyJobQueueDAO();
if (assignment != null) {
for (Long sid : assignment.getSurveyIds()) {
jobDao.updateAssignmentIdForSurvey(sid, assignmentId);
}
}
}
private void fixNameQuestion(String questionId) {
Queue summQueue = QueueFactory.getQueue("dataUpdate");
summQueue.add(TaskOptions.Builder.withUrl("/app_worker/dataupdate")
.param("objectKey", questionId + "")
.param("type", "NameQuestionFix"));
}
private boolean deleteSurveyResponses(Integer surveyId, Integer count) {
SurveyInstanceDAO dao = new SurveyInstanceDAO();
List<SurveyInstance> instances = dao.listSurveyInstanceBySurvey(
new Long(surveyId), count != null ? count : 100);
if (instances != null) {
for (SurveyInstance instance : instances) {
List<QuestionAnswerStore> questions = dao
.listQuestionAnswerStore(instance.getKey().getId(),
count);
if (questions != null) {
dao.delete(questions);
}
dao.delete(instance);
}
return true;
}
return false;
}
private void reprocessSurveys(String date) throws ParseException {
SurveyInstanceDAO dao = new SurveyInstanceDAO();
Date startDate = null;
if (date != null) {
DateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
startDate = sdf.parse(date);
List<SurveyInstance> instances = dao.listByDateRange(startDate,
null);
if (instances != null) {
AccessPointHelper aph = new AccessPointHelper();
for (SurveyInstance instance : instances) {
aph.processSurveyInstance(instance.getKey().getId() + "");
}
}
}
}
private boolean migratePointType(AccessPointType source,
AccessPointType dest) {
AccessPointDao pointDao = new AccessPointDao();
List<AccessPoint> list = pointDao.searchAccessPoints(null, null, null,
null, source.toString(), null, null, null, null, null, null,
null);
if (list != null && list.size() > 0) {
for (AccessPoint point : list) {
point.setPointType(dest);
pointDao.save(point);
}
}
if (list != null && list.size() == 20) {
return true;
} else {
return false;
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private <T extends BaseDomain> void deleteAll(Class<T> type) {
BaseDAO<T> baseDao = new BaseDAO(type);
List<T> items = baseDao.list("all");
if (items != null) {
for (T item : items) {
baseDao.delete(item);
}
}
}
private void createTestSurveyForEndToEnd() {
SurveyGroupDto sgd = new SurveyGroupDto();
sgd.setCode("E2E Test");
sgd.setDescription("end2end test");
SurveyDto surveyDto = new SurveyDto();
surveyDto.setDescription("e2e test");
SurveyServiceImpl surveySvc = new SurveyServiceImpl();
QuestionGroupDto qgd = new QuestionGroupDto();
qgd.setCode("Question Group 1");
qgd.setDescription("Question Group Desc");
QuestionDto qd = new QuestionDto();
qd.setText("Access Point Name:");
qd.setType(QuestionType.FREE_TEXT);
qgd.addQuestion(qd, 0);
qd = new QuestionDto();
qd.setText("Location:");
qd.setType(QuestionType.GEO);
qgd.addQuestion(qd, 1);
qd = new QuestionDto();
qd.setText("Photo");
qd.setType(QuestionType.PHOTO);
qgd.addQuestion(qd, 2);
surveyDto.addQuestionGroup(qgd);
surveyDto.setVersion("Version: 1");
sgd.addSurvey(surveyDto);
sgd = surveySvc.save(sgd);
System.out.println(sgd.getKeyId());
}
private void writeImageToResponse(HttpServletResponse resp, String urlString) {
resp.setContentType("image/jpeg");
try {
ServletOutputStream out = resp.getOutputStream();
URL url = new URL(urlString);
InputStream in = url.openStream();
byte[] buffer = new byte[2048];
int size;
while ((size = in.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, size);
}
in.close();
out.flush();
} catch (Exception ex) {
}
}
private void createSurveyGroupGraph(HttpServletResponse resp) {
com.gallatinsystems.survey.dao.SurveyGroupDAO sgDao = new com.gallatinsystems.survey.dao.SurveyGroupDAO();
BaseDAO<Translation> tDao = new BaseDAO<Translation>(Translation.class);
for (Translation t : tDao.list("all"))
tDao.delete(t);
// clear out old surveys
List<SurveyGroup> sgList = sgDao.list("all");
for (SurveyGroup item : sgList)
sgDao.delete(item);
try {
resp.getWriter().println("Finished clearing surveyGroup table");
} catch (IOException e1) {
e1.printStackTrace();
}
SurveyDAO surveyDao = new SurveyDAO();
QuestionGroupDao questionGroupDao = new QuestionGroupDao();
QuestionDao questionDao = new QuestionDao();
QuestionOptionDao questionOptionDao = new QuestionOptionDao();
QuestionHelpMediaDao helpDao = new QuestionHelpMediaDao();
for (int i = 0; i < 2; i++) {
com.gallatinsystems.survey.domain.SurveyGroup sg = new com.gallatinsystems.survey.domain.SurveyGroup();
sg.setCode(i + ":" + new Date());
sg.setName(i + ":" + new Date());
sg = sgDao.save(sg);
for (int j = 0; j < 2; j++) {
com.gallatinsystems.survey.domain.Survey survey = new com.gallatinsystems.survey.domain.Survey();
survey.setCode(j + ":" + new Date());
survey.setName(j + ":" + new Date());
survey.setSurveyGroupId(sg.getKey().getId());
survey.setPath(sg.getCode());
survey = surveyDao.save(survey);
Translation t = new Translation();
t.setLanguageCode("es");
t.setText(j + ":" + new Date());
t.setParentType(ParentType.SURVEY_NAME);
t.setParentId(survey.getKey().getId());
tDao.save(t);
survey.addTranslation(t);
for (int k = 0; k < 3; k++) {
com.gallatinsystems.survey.domain.QuestionGroup qg = new com.gallatinsystems.survey.domain.QuestionGroup();
qg.setName("en:" + j + new Date());
qg.setDesc("en:desc: " + j + new Date());
qg.setCode("en:" + j + new Date());
qg.setSurveyId(survey.getKey().getId());
qg.setOrder(k);
qg.setPath(sg.getCode() + "/" + survey.getCode());
qg = questionGroupDao.save(qg);
Translation t2 = new Translation();
t2.setLanguageCode("es");
t2.setParentType(ParentType.QUESTION_GROUP_NAME);
t2.setText("es:" + k + new Date());
t2.setParentId(qg.getKey().getId());
tDao.save(t2);
qg.addTranslation(t2);
for (int l = 0; l < 2; l++) {
com.gallatinsystems.survey.domain.Question q = new com.gallatinsystems.survey.domain.Question();
q.setType(Type.OPTION);
q.setAllowMultipleFlag(false);
q.setAllowOtherFlag(false);
q.setDependentFlag(false);
q.setMandatoryFlag(true);
q.setQuestionGroupId(qg.getKey().getId());
q.setOrder(l);
q.setText("en:" + l + ":" + new Date());
q.setTip("en:" + l + ":" + new Date());
q.setPath(sg.getCode() + "/" + survey.getCode() + "/"
+ qg.getCode());
q.setSurveyId(survey.getKey().getId());
q = questionDao.save(q);
Translation tq = new Translation();
tq.setLanguageCode("es");
tq.setText("es" + l + ":" + new Date());
tq.setParentType(ParentType.QUESTION_TEXT);
tq.setParentId(q.getKey().getId());
tDao.save(tq);
q.addTranslation(tq);
for (int m = 0; m < 10; m++) {
com.gallatinsystems.survey.domain.QuestionOption qo = new com.gallatinsystems.survey.domain.QuestionOption();
qo.setOrder(m);
qo.setText(m + ":" + new Date());
qo.setCode(m + ":" + new Date());
qo.setQuestionId(q.getKey().getId());
qo = questionOptionDao.save(qo);
Translation tqo = new Translation();
tqo.setLanguageCode("es");
tqo.setText("es:" + m + ":" + new Date());
tqo.setParentType(ParentType.QUESTION_OPTION);
tqo.setParentId(qo.getKey().getId());
tDao.save(tqo);
qo.addTranslation(tqo);
q.addQuestionOption(qo);
}
for (int n = 0; n < 10; n++) {
com.gallatinsystems.survey.domain.QuestionHelpMedia qhm = new com.gallatinsystems.survey.domain.QuestionHelpMedia();
qhm.setText("en:" + n + ":" + new Date());
qhm.setType(QuestionHelpMedia.Type.PHOTO);
qhm.setResourceUrl("http://test.com/" + n + ".jpg");
qhm.setQuestionId(q.getKey().getId());
qhm = helpDao.save(qhm);
Translation tqhm = new Translation();
tqhm.setLanguageCode("es");
tqhm.setText("es:" + n + ":" + new Date());
tqhm.setParentType(ParentType.QUESTION_HELP_MEDIA_TEXT);
tqhm.setParentId(qhm.getKey().getId());
tDao.save(tqhm);
qhm.addTranslation(tqhm);
q.addHelpMedia(n, qhm);
}
qg.addQuestion(l, q);
}
survey.addQuestionGroup(k, qg);
}
sg.addSurvey(survey);
}
log.log(Level.INFO, "Finished Saving sg: " + sg.getKey().toString());
}
}
private void setupMetrics() {
MetricDao metricDao = new MetricDao();
List<Metric> metrics = metricDao.listMetrics(null, null, null, "test",
null);
if (metrics != null) {
metricDao.delete(metrics);
}
List<Metric> newMetrics = new ArrayList<Metric>();
Metric m = new Metric();
m.setName("Status");
m.setOrganization("test");
newMetrics.add(m);
m = new Metric();
m.setName("Households Served");
m.setOrganization("test");
newMetrics.add(m);
metricDao.save(newMetrics);
}
}
| true | true | public void doGet(HttpServletRequest req, HttpServletResponse resp) {
String action = req.getParameter("action");
if ("setupTestUser".equals(action)) {
setupTestUser();
} else if ("computeDistanceAlongBearing".equals(action)) {
com.gallatinsystems.gis.coordinate.utilities.CoordinateUtilities cu = new CoordinateUtilities();
Coordinate startingPoint = new Coordinate(Double.parseDouble(req
.getParameter("lat")), Double.parseDouble(req
.getParameter("lon")));
Double distance = Double.parseDouble(req.getParameter("distance"));
Double bearing = Double.parseDouble(req.getParameter("bearing"));
Coordinate newPoint = cu.computePointAlongBearingDistance(
startingPoint, distance, bearing);
try {
resp.getWriter().println("New Point : " + newPoint.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("fixQuestionAnswerStoreDates".equals(action)) {
// DataFixes df = new DataFixes();
// df.generateTestData();
Queue queue = QueueFactory.getDefaultQueue();
queue.add(TaskOptions.Builder
.withUrl("/app_worker/questionanswerstorecleanup"));
log.info("submiting task QAS CollectionDate Cleanup");
} else if ("reprocessFiles".equalsIgnoreCase(action)) {
DeviceFilesDao dfDao = new DeviceFilesDao();
String cursor = null;
List<DeviceFiles> files = null;
do {
files = dfDao.listDeviceFilesByStatus(StatusCode.IN_PROGRESS,
cursor);
if (files != null) {
cursor = DeviceFilesDao.getCursor(files);
Queue queue = QueueFactory.getDefaultQueue();
for (DeviceFiles fi : files) {
queue.add(TaskOptions.Builder
.withUrl("/app_worker/task")
.param("action", "processFile")
.param("fileName",
fi.getURI()
.substring(
fi.getURI()
.lastIndexOf(
"/") + 1)));
}
}
} while (files != null && files.size() > 0 && cursor != null);
} else if ("testStandardScoring".equals(action)) {
StandardTestLoader stl = new StandardTestLoader(req, resp);
stl.runTest();
} else if ("listStandardScoringResults".equals(action)) {
StandardTestLoader stl = new StandardTestLoader(req, resp);
String countryCode = null;
String communityCode = null;
String accessPointCode = null;
if (req.getParameter("countryCode") != null) {
countryCode = req.getParameter("countryCode");
}
if (req.getParameter("communityCode") != null) {
communityCode = req.getParameter("communityCode");
}
if (req.getParameter("accessPointCode") != null) {
accessPointCode = req.getParameter("accessPointCode");
}
String cursorString = null;
if (req.getParameter("cursorString") != null) {
cursorString = req.getParameter("cursorString");
}
stl.listResults(countryCode, communityCode, accessPointCode,
cursorString);
} else if ("testDistanceRule".equals(action)) {
DeleteObjectUtil dou = new DeleteObjectUtil();
dou.deleteAllObjects("AccessPointScoreComputationItem");
dou.deleteAllObjects("AccessPointScoreDetail");
// AccessPointTest apt = new AccessPointTest();
// apt.loadWPDistanceTestData(resp);
// apt.loadHHDistanceTestData(resp);
// AccessPointDao apDao = new AccessPointDao();
// List<AccessPoint> apList = apDao.list("all");
// AccessPointHelper aph = new AccessPointHelper();
// for (AccessPoint ap : apList) {
// aph.computeDistanceRule(ap);
// }
// try {
// resp.getWriter().println("Completed test distance rule");
// } catch (IOException e) {
// e.printStackTrace();
// }
} else if ("setupDevEnv".equals(action)) {
try {
DeleteObjectUtil dou = new DeleteObjectUtil();
dou.deleteAllObjects("AccessPoint");
dou.deleteAllObjects("StandardScoreBucket");
dou.deleteAllObjects("StandardScoring");
resp.getWriter().println(
"About to configure development environment");
setupTestUser();
resp.getWriter().println("Completed setting up test user");
resp.getWriter().println("Completed setting up permissions");
AccessPointTest apt = new AccessPointTest();
apt.loadLots(resp, 100);
StandardScoringTest sct = new StandardScoringTest();
sct.populateData();
setupMetrics();
resp.getWriter().println("Completed setting scorebuckets");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("populateAccessPointMetric".equals(action)) {
AccessPointMetricSummaryTest apMST = new AccessPointMetricSummaryTest();
apMST.runTest(resp);
} else if ("reorderQuestionsByCollectionDate".equals(action)) {
try {
Long surveyId = Long.parseLong(req.getParameter("surveyId"));
SurveyDAO surveyDao = new SurveyDAO();
QuestionDao qDao = new QuestionDao();
Survey survey = surveyDao.loadFullSurvey(surveyId);
int i = 0;
for (Map.Entry<Integer, QuestionGroup> qGEntry : survey
.getQuestionGroupMap().entrySet()) {
List<Question> qList = qDao
.listQuestionsByQuestionGroupOrderByCreatedDateTime(qGEntry
.getValue().getKey().getId());
for (Question q : qDao
.listQuestionsByQuestionGroupOrderByCreatedDateTime(qGEntry
.getValue().getKey().getId())) {
q.setOrder(i + 1);
qDao.save(q);
resp.getWriter().println(
q.getOrder() + " :Change: " + q.getText());
++i;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("fixQuestionOrder".equals(action)) {
Long surveyId = Long.parseLong(req.getParameter("surveyId"));
QuestionDao qDao = new QuestionDao();
// this is the list in ascending order by the "order" field
List<Question> qList = qDao.listQuestionsBySurvey(surveyId);
if (qList != null) {
Map<Long, Integer> groupMaxCount = new HashMap<Long, Integer>();
for (Question q : qList) {
Integer max = groupMaxCount.get(q.getQuestionGroupId());
if (max == null) {
max = 1;
} else {
max = max + 1;
}
// since q is still attached, this should be all we need to
// do
q.setOrder(max);
groupMaxCount.put(q.getQuestionGroupId(), max);
}
}
} else if ("deleteGeoData".equals(action)) {
try {
OGRFeatureDao ogrFeatureDao = new OGRFeatureDao();
for (OGRFeature item : ogrFeatureDao.list("all")) {
resp.getWriter().println(
"deleting: " + item.getCountryCode());
ogrFeatureDao.delete(item);
}
resp.getWriter().println("Finished");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("testGeoLocation".equals(action)) {
OGRFeatureDao ogrFeatureDao = new OGRFeatureDao();
GeoLocationServiceGeonamesImpl gs = new GeoLocationServiceGeonamesImpl();
String lat = req.getParameter("lat");
String lon = req.getParameter("lon");
GeoPlace geoPlace = gs.manualLookup(lat, lon);
try {
if (geoPlace != null) {
resp.getWriter().println(
"Found: " + geoPlace.getCountryName() + ":"
+ geoPlace.getCountryCode() + " for " + lat
+ ", " + lon);
geoPlace = gs.resolveSubCountry(lat, lon,
geoPlace.getCountryCode());
}
if (geoPlace != null)
resp.getWriter().println(
"Found: " + geoPlace.getCountryCode() + ":"
+ geoPlace.getSub1() + ":"
+ geoPlace.getSub2() + ":"
+ geoPlace.getSub3() + ":"
+ geoPlace.getSub4() + ":"
+ geoPlace.getSub5() + ":"
+ geoPlace.getSub6() + " for " + lat + ", "
+ lon);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("RemapAPToSub".equals(action)) {
AccessPointDao apDao = new AccessPointDao();
} else if ("loadOGRFeature".equals(action)) {
OGRFeature ogrFeature = new OGRFeature();
ogrFeature.setName("clan-21061011");
ogrFeature.setProjectCoordinateSystemIdentifier("World_Mercator");
ogrFeature.setGeoCoordinateSystemIdentifier("GCS_WGS_1984");
ogrFeature.setDatumIdentifier("WGS_1984");
ogrFeature.setSpheroid(6378137D);
ogrFeature.setReciprocalOfFlattening(298.257223563);
ogrFeature.setCountryCode("LR");
ogrFeature.addBoundingBox(223700.015625, 481399.468750,
680781.375000, 945462.437500);
Geometry geo = new Geometry();
geo.setType(GeometryType.POLYGON);
String coords = "497974.5625 557051.875,498219.03125 557141.75,498655.34375 557169.4375,499001.65625 557100.1875,499250.96875 556933.9375,499167.875 556615.375,499230.1875 556407.625,499392.78125 556362.75,499385.90625 556279.875,499598.5 556067.3125,499680.25 555952.8125,499218.5625 554988.875,498775.65625 554860.1875,498674.5 554832.5625,498282.0 554734.4375,498020.34375 554554.5625,497709.59375 554374.6875,497614.84375 554374.6875,497519.46875 554369.1875,497297.3125 554359.9375,496852.96875 554355.3125,496621.125 554351.375,496695.75 554454.625,496771.59375 554604.625,496836.3125 554734.0625,496868.65625 554831.125,496847.09375 554863.4375,496760.8125 554863.4375,496663.75 554928.125,496620.625 554992.875,496555.90625 555025.1875,496448.0625 554992.875,496372.5625 555025.1875,496351.0 555133.0625,496415.71875 555197.75,496480.40625 555294.8125,496480.40625 555381.0625,496430.875 555430.75,496446.0625 555547.375,496490.53125 555849.625,496526.09375 556240.75,496721.65625 556596.375,496924.90625 556774.1875,497006.125 556845.25,497281.71875 556978.625,497610.625 556969.6875,497859.53125 556969.6875,497974.5625 557051.875";
for (String item : coords.split(",")) {
String[] coord = item.split(" ");
geo.addCoordinate(Double.parseDouble(coord[0]),
Double.parseDouble(coord[1]));
}
ogrFeature.setGeometry(geo);
ogrFeature.addGeoMeasure("CLNAME", "STRING", "Loisiana Township");
ogrFeature.addGeoMeasure("COUNT", "FLOAT", "1");
BaseDAO<OGRFeature> ogrDao = new BaseDAO<OGRFeature>(
OGRFeature.class);
ogrDao.save(ogrFeature);
try {
resp.getWriter()
.println("OGRFeature: " + ogrFeature.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("printOGRFeature".equals(action)) {
OGRFeatureDao ogrFeatureDao = new OGRFeatureDao();
FeatureType featureType = FeatureType.valueOf(req
.getParameter("featureType"));
List<OGRFeature> ogrFeatureList = ogrFeatureDao
.listByCountryAndType(req.getParameter("countryCode"),
featureType, null);
try {
int i = 1;
if (ogrFeatureList != null && !ogrFeatureList.isEmpty()) {
for (OGRFeature item : ogrFeatureList) {
resp.getWriter().println(
"i: " + i + " sub1" + item.getSub1()
+ " sub2: " + item.getSub2());
resp.getWriter().println(
" OGRFeature: " + item.toString());
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("resetLRAP".equals(action)) {
try {
AccessPointDao apDao = new AccessPointDao();
Random rand = new Random();
for (AccessPoint ap : apDao.list("all")) {
if ((ap.getCountryCode() == null || ap.getCountryCode()
.equals("US"))
&& (ap.getLatitude() != null && ap.getLongitude() != null)) {
if (ap.getLatitude() > 5.0 && ap.getLatitude() < 11) {
if (ap.getLongitude() < -9
&& ap.getLongitude() > -11) {
ap.setCountryCode("LR");
apDao.save(ap);
resp.getWriter()
.println(
"Found "
+ ap.getCommunityCode()
+ "mapped to US changing mapping to LR \n");
}
}
} else if (ap.getCommunityCode() == null) {
ap.setCommunityCode(rand.nextLong() + "");
apDao.save(ap);
resp.getWriter().println(
"Found " + ap.getCommunityCode()
+ "added random community code \n");
}
}
} catch (IOException e) {
log.log(Level.SEVERE, "Could not execute test", e);
}
} else if ("populateAccessPointMetricSummary".equals(action)) {
OGRFeatureDao ogrFeatureDao = new OGRFeatureDao();
AccessPointMetricSummaryDao apmsDao = new AccessPointMetricSummaryDao();
// List<OGRFeature> ogrList =
// ogrFeatureDao.listByCountryAndType("LR",
// FeatureType.SUB_COUNTRY_OTHER);
Boolean firstTimeFlag = false;
// for (OGRFeature item : ogrList) {
// AccessPointMetricSummary apms = new AccessPointMetricSummary();
// apms.setCount(1L);
// apms.setCountry("LR");
// apms.setSubLevel(1);
// apms.setSubValue(item.getSub1());
// apms.setShardNum(1);
// apms.setParentSubName("LR");
// apms.setMetricName("WATER_POINT");
// apmsDao.save(apms);
// }
} else if ("populateStandardScoring".equals(action)) {
StandardScoringTest sst = new StandardScoringTest();
sst.populateData();
} else if ("clearSurveyInstanceQAS".equals(action)) {
// QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao();
// for (QuestionAnswerStore qas : qasDao.list("all")) {
// qasDao.delete(qas);
// }
// SurveyInstanceDAO siDao = new SurveyInstanceDAO();
// for (SurveyInstance si : siDao.list("all")) {
// siDao.delete(si);
// }
AccessPointDao apDao = new AccessPointDao();
for (AccessPoint ap : apDao.list("all"))
apDao.delete(ap);
} else if ("SurveyInstance".equals(action)) {
SurveyInstanceDAO siDao = new SurveyInstanceDAO();
List<SurveyInstance> siList = siDao.listSurveyInstanceBySurveyId(
1362011L, null);
Cursor cursor = JDOCursorHelper.getCursor(siList);
int i = 0;
while (siList.size() > 0) {
for (SurveyInstance si : siList) {
System.out.println(i++ + " " + si.toString());
String surveyInstanceId = new Long(si.getKey().getId())
.toString();
Queue queue = QueueFactory.getDefaultQueue();
queue.add(TaskOptions.Builder
.withUrl("/app_worker/surveytask")
.param("action", "reprocessMapSurveyInstance")
.param("id", surveyInstanceId));
log.info("submiting task for SurveyInstanceId: "
+ surveyInstanceId);
}
siList = siDao.listSurveyInstanceBySurveyId(1362011L,
cursor.toWebSafeString());
cursor = JDOCursorHelper.getCursor(siList);
}
System.out.println("finished");
} else if ("rotateImage".equals(action)) {
AccessPointManagerServiceImpl apmI = new AccessPointManagerServiceImpl();
String test1 = "http://waterforpeople.s3.amazonaws.com/images/wfpPhoto10062903227521.jpg";
// String test2 =
// "http://waterforpeople.s3.amazonaws.com/images/hn/ch003[1].jpg";
writeImageToResponse(resp, test1);
apmI.setUploadS3Flag(false);
// apmI.rotateImage(test2);
} else if ("clearSurveyGroupGraph".equals(action)) {
SurveyGroupDAO sgDao = new SurveyGroupDAO();
sgDao.delete(sgDao.list("all"));
SurveyDAO surveyDao = new SurveyDAO();
surveyDao.delete(surveyDao.list("all"));
QuestionGroupDao qgDao = new QuestionGroupDao();
qgDao.delete(qgDao.list("all"));
QuestionDao qDao = new QuestionDao();
qDao.delete(qDao.list("all"));
QuestionHelpMediaDao qhDao = new QuestionHelpMediaDao();
qhDao.delete(qhDao.list("all"));
QuestionOptionDao qoDao = new QuestionOptionDao();
qoDao.delete(qoDao.list("all"));
TranslationDao tDao = new TranslationDao();
tDao.delete(tDao.list("all"));
} else if ("replicateDeviceFiles".equals(action)) {
SurveyInstanceDAO siDao = new SurveyInstanceDAO();
for (SurveyInstance si : siDao.list("all")) {
siDao.delete(si);
}
QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao();
for (QuestionAnswerStore qas : qasDao.list("all")) {
qasDao.delete(qas);
}
DeviceFilesDao dfDao = new DeviceFilesDao();
for (DeviceFiles df : dfDao.list("all")) {
dfDao.delete(df);
}
DeviceFilesReplicationImporter dfri = new DeviceFilesReplicationImporter();
dfri.executeImport("http://watermapmonitordev.appspot.com",
"http://localhost:8888");
Set<String> dfSet = new HashSet<String>();
for (DeviceFiles df : dfDao.list("all")) {
dfSet.add(df.getURI());
}
DeviceFilesServiceImpl dfsi = new DeviceFilesServiceImpl();
int i = 0;
try {
resp.getWriter().println(
"Found " + dfSet.size() + " distinct files to process");
for (String s : dfSet) {
dfsi.reprocessDeviceFile(s);
resp.getWriter().println(
"submitted " + s + " for reprocessing");
i++;
if (i > 10)
break;
}
} catch (IOException e) {
log.log(Level.SEVERE, "Could not execute test", e);
}
} else if ("addDeviceFiles".equals(action)) {
DeviceFilesDao dfDao = new DeviceFilesDao();
DeviceFiles df = new DeviceFiles();
df.setURI("http://waterforpeople.s3.amazonaws.com/devicezip/wfp1737657928520.zip");
df.setCreatedDateTime(new Date());
df.setPhoneNumber("a4:ed:4e:54:ef:6d");
df.setChecksum("1149406886");
df.setProcessedStatus(StatusCode.ERROR_INFLATING_ZIP);
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd");
java.util.Date date = new java.util.Date();
String dateTime = dateFormat.format(date);
df.setProcessDate(dateTime);
dfDao.save(df);
} else if ("populateScoreBuckets".equals(action)) {
BaseDAO<StandardScoreBucket> scDao = new BaseDAO<StandardScoreBucket>(
StandardScoreBucket.class);
ArrayList<String> scoreBuckets = new ArrayList<String>();
scoreBuckets.add("WATERPOINTLEVELOFSERVICE");
scoreBuckets.add("WATERPOINTSUSTAINABILITY");
scoreBuckets.add("PUBLICINSTITUTIONLEVELOFSERVICE");
scoreBuckets.add("PUBLICINSTITUTIONSUSTAINABILITY");
for (String item : scoreBuckets) {
StandardScoreBucket sbucket = new StandardScoreBucket();
sbucket.setName(item);
scDao.save(sbucket);
}
} else if ("testSaveRegion".equals(action)) {
GeoRegionHelper geoHelp = new GeoRegionHelper();
ArrayList<String> regionLines = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
StringBuilder builder = new StringBuilder();
builder.append("1,").append("" + i).append(",test,")
.append(20 + i + ",").append(30 + i + "\n");
regionLines.add(builder.toString());
}
geoHelp.processRegionsSurvey(regionLines);
try {
resp.getWriter().print("Save complete");
} catch (IOException e) {
log.log(Level.SEVERE, "Could not save test region", e);
}
} else if ("clearAccessPoint".equals(action)) {
try {
AccessPointDao apDao = new AccessPointDao();
for (AccessPoint ap : apDao.list("all")) {
apDao.delete(ap);
try {
resp.getWriter().print(
"Finished Deleting AP: " + ap.toString());
} catch (IOException e) {
log.log(Level.SEVERE, "Could not delete ap");
}
}
resp.getWriter().print("Deleted AccessPoints complete");
BaseDAO<AccessPointStatusSummary> apsDao = new BaseDAO<AccessPointStatusSummary>(
AccessPointStatusSummary.class);
for (AccessPointStatusSummary item : apsDao.list("all")) {
apsDao.delete(item);
}
resp.getWriter().print("Deleted AccessPointStatusSummary");
MapFragmentDao mfDao = new MapFragmentDao();
for (MapFragment item : mfDao.list("all")) {
mfDao.delete(item);
}
resp.getWriter().print("Cleared MapFragment Table");
} catch (IOException e) {
log.log(Level.SEVERE, "Could not clear AP and APStatusSummary",
e);
}
} else if ("loadErrorPoints".equals(action)) {
MapFragmentDao mfDao = new MapFragmentDao();
AccessPointDao apDao = new AccessPointDao();
for (int j = 0; j < 1; j++) {
Double lat = 0.0;
Double lon = 0.0;
for (int i = 0; i < 5; i++) {
AccessPoint ap = new AccessPoint();
ap.setLatitude(lat);
ap.setLongitude(lon);
Calendar calendar = Calendar.getInstance();
Date today = new Date();
calendar.setTime(today);
calendar.add(Calendar.YEAR, -1 * i);
System.out
.println("AP: " + ap.getLatitude() + "/"
+ ap.getLongitude() + "Date: "
+ calendar.getTime());
ap.setCollectionDate(calendar.getTime());
ap.setAltitude(0.0);
ap.setCommunityCode("test" + new Date());
ap.setCommunityName("test" + new Date());
ap.setPhotoURL("http://test.com");
ap.setPointType(AccessPoint.AccessPointType.WATER_POINT);
if (i == 0)
ap.setPointStatus(AccessPoint.Status.FUNCTIONING_HIGH);
else if (i == 1)
ap.setPointStatus(AccessPoint.Status.FUNCTIONING_OK);
else if (i == 2)
ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS);
else
ap.setPointStatus(Status.NO_IMPROVED_SYSTEM);
if (i % 2 == 0)
ap.setTypeTechnologyString("Kiosk");
else
ap.setTypeTechnologyString("Afridev Handpump");
apDao.save(ap);
// ms.performSummarization("" + ap.getKey().getId(), "");
if (i % 50 == 0)
log.log(Level.INFO, "Loaded to " + i);
}
}
try {
resp.getWriter().println("Finished loading aps");
} catch (IOException e) {
e.printStackTrace();
}
} else if ("loadLots".equals(action)) {
AccessPointTest apt = new AccessPointTest();
apt.loadLots(resp, 500);
} else if ("loadCountries".equals(action)) {
Country c = new Country();
c.setIsoAlpha2Code("HN");
c.setName("Honduras");
c.setIncludeInExternal(true);
c.setCentroidLat(14.7889035);
c.setCentroidLon(-86.9500379);
c.setZoomLevel(8);
BaseDAO<Country> countryDAO = new BaseDAO<Country>(Country.class);
countryDAO.save(c);
Country c2 = new Country();
c2.setIsoAlpha2Code("MW");
c2.setName("Malawi");
c2.setIncludeInExternal(true);
c2.setCentroidLat(-13.0118377);
c2.setCentroidLon(33.9984484);
c2.setZoomLevel(7);
countryDAO.save(c2);
Country c3 = new Country();
c3.setIsoAlpha2Code("UG");
c3.setName("Uganda");
c3.setIncludeInExternal(true);
c3.setCentroidLat(1.1027);
c3.setCentroidLon(32.3968);
c3.setZoomLevel(7);
countryDAO.save(c3);
Country c4 = new Country();
c4.setIsoAlpha2Code("KE");
c4.setName("Kenya");
c4.setIncludeInExternal(true);
c4.setCentroidLat(-1.26103461);
c4.setCentroidLon(36.74724467);
c4.setZoomLevel(7);
countryDAO.save(c4);
} else if ("testAPKml".equals(action)) {
MapFragmentDao mfDao = new MapFragmentDao();
BaseDAO<TechnologyType> ttDao = new BaseDAO<TechnologyType>(
TechnologyType.class);
List<TechnologyType> ttList = ttDao.list("all");
for (TechnologyType tt : ttList)
ttDao.delete(tt);
TechnologyType tt = new TechnologyType();
tt.setCode("Afridev Handpump");
tt.setName("Afridev Handpump");
ttDao.save(tt);
TechnologyType tt2 = new TechnologyType();
tt2.setCode("Kiosk");
tt2.setName("Kiosk");
ttDao.save(tt2);
KMLHelper kmlHelper = new KMLHelper();
kmlHelper.buildMap();
List<MapFragment> mfList = mfDao
.searchMapFragments("ALL", null, null,
FRAGMENTTYPE.GLOBAL_ALL_PLACEMARKS, "all", null,
null);
try {
for (MapFragment mfItem : mfList) {
String contents = ZipUtil
.unZip(mfItem.getBlob().getBytes());
log.log(Level.INFO, "Contents Length: " + contents.length());
resp.setContentType("application/vnd.google-earth.kmz+xml");
ServletOutputStream out = resp.getOutputStream();
resp.setHeader("Content-Disposition",
"inline; filename=waterforpeoplemapping.kmz;");
out.write(mfItem.getBlob().getBytes());
out.flush();
}
} catch (IOException ie) {
log.log(Level.SEVERE, "Could not list fragment");
}
} else if ("deleteSurveyGraph".equals(action)) {
deleteAll(SurveyGroup.class);
deleteAll(Survey.class);
deleteAll(QuestionGroup.class);
deleteAll(Question.class);
deleteAll(Translation.class);
deleteAll(QuestionOption.class);
deleteAll(QuestionHelpMedia.class);
try {
resp.getWriter().println("Finished deleting survey graph");
} catch (IOException iex) {
log.log(Level.SEVERE, "couldn't delete surveyGraph" + iex);
}
}
else if ("saveSurveyGroupRefactor".equals(action)) {
SurveyGroupDAO sgDao = new SurveyGroupDAO();
createSurveyGroupGraph(resp);
try {
List<SurveyGroup> savedSurveyGroups = sgDao.list("all");
for (SurveyGroup sgItem : savedSurveyGroups) {
resp.getWriter().println("SG: " + sgItem.getCode());
for (Survey survey : sgItem.getSurveyList()) {
resp.getWriter().println(
" Survey:" + survey.getName());
for (Map.Entry<Integer, QuestionGroup> entry : survey
.getQuestionGroupMap().entrySet()) {
resp.getWriter().println(
" QuestionGroup: " + entry.getKey()
+ ":" + entry.getValue().getDesc());
for (Map.Entry<Integer, Question> questionEntry : entry
.getValue().getQuestionMap().entrySet()) {
resp.getWriter().println(
" Question"
+ questionEntry.getKey()
+ ":"
+ questionEntry.getValue()
.getText());
for (Map.Entry<Integer, QuestionHelpMedia> qhmEntry : questionEntry
.getValue().getQuestionHelpMediaMap()
.entrySet()) {
resp.getWriter().println(
" QuestionHelpMedia"
+ qhmEntry.getKey()
+ ":"
+ qhmEntry.getValue()
.getText());
/*
* for (Key tKey : qhmEntry.getValue()
* .getAltTextKeyList()) { Translation t =
* tDao.getByKey(tKey);
* resp.getWriter().println(
* " QHMAltText" +
* t.getLanguageCode() + ":" + t.getText());
* }
*/
}
}
}
}
}
} catch (IOException e) {
log.log(Level.SEVERE, "Could not save sg");
}
} else if ("createAP".equals(action)) {
AccessPoint ap = new AccessPoint();
ap.setCollectionDate(new Date());
ap.setCommunityCode(new Random().toString());
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setCountryCode("SZ");
ap.setPointType(AccessPointType.WATER_POINT);
AccessPointHelper helper = new AccessPointHelper();
helper.saveAccessPoint(ap);
} else if ("createInstance".equals(action)) {
SurveyInstance si = new SurveyInstance();
si.setCollectionDate(new Date());
ArrayList<QuestionAnswerStore> store = new ArrayList<QuestionAnswerStore>();
QuestionAnswerStore ans = new QuestionAnswerStore();
ans.setQuestionID("2166031");
ans.setValue("12.379456758498787|-85.53869247436275|548.0|1kvc9dqy");
ans.setType("GEO");
ans.setSurveyId(1360012L);
store.add(ans);
si.setQuestionAnswersStore(store);
si.setUuid("12345");
SurveyInstanceDAO dao = new SurveyInstanceDAO();
si = dao.save(si);
ans.setSurveyInstanceId(si.getKey().getId());
dao.save(ans);
// Queue summQueue = QueueFactory.getQueue("dataSummarization");
// summQueue.add(TaskOptions.Builder
// .withUrl("/app_worker/datasummarization")
// .param("objectKey", si.getKey().getId() + "")
// .param("type", "SurveyInstance"));
} else if ("createCommunity".equals(action)) {
CommunityDao dao = new CommunityDao();
Country c = new Country();
c.setIsoAlpha2Code("CA");
c.setName("Canada");
c.setDisplayName("Canada");
Community comm = new Community();
comm.setCommunityCode("ON");
dao.save(c);
comm.setCountryCode("CA");
comm.setLat(54.99);
comm.setLon(-74.72);
dao.save(comm);
c = new Country();
c.setIsoAlpha2Code("US");
c.setName("United States");
c.setDisplayName("Unites States");
comm = new Community();
comm.setCommunityCode("Omaha");
comm.setCountryCode("US");
comm.setLat(34.99);
comm.setLon(-74.72);
dao.save(c);
dao.save(comm);
} else if ("addPhone".equals(action)) {
String phoneNumber = req.getParameter("phoneNumber");
Device d = new Device();
d.setPhoneNumber(phoneNumber);
d.setDeviceType(DeviceType.CELL_PHONE_ANDROID);
if (req.getParameter("esn") != null)
d.setEsn(req.getParameter("esn"));
if (req.getParameter("gallatinSoftwareManifest") != null)
d.setGallatinSoftwareManifest(req
.getParameter("gallatinSoftwareManifest"));
d.setInServiceDate(new Date());
DeviceDAO deviceDao = new DeviceDAO();
deviceDao.save(d);
try {
resp.getWriter().println("finished adding " + phoneNumber);
} catch (Exception e) {
e.printStackTrace();
}
} else if ("createAPSummary".equals(action)) {
AccessPointStatusSummary sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2000");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
AccessPointStatusSummaryDao dao = new AccessPointStatusSummaryDao();
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2001");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2003");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2004");
sum.setStatus(AccessPoint.Status.FUNCTIONING_OK);
dao.save(sum);
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2000");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2001");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2003");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2004");
sum.setStatus(AccessPoint.Status.FUNCTIONING_OK);
dao.save(sum);
} else if ("createApHistory".equals(action)) {
GregorianCalendar cal = new GregorianCalendar();
AccessPointHelper apHelper = new AccessPointHelper();
AccessPoint ap = new AccessPoint();
cal.set(Calendar.YEAR, 2000);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(300l);
ap.setCostPer(43.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2001);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(317l);
ap.setCostPer(40.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2002);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(340l);
ap.setCostPer(37.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2003);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(340l);
ap.setCostPer(34.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2004);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(338l);
ap.setCostPer(38.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2000);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(170l);
ap.setCostPer(19.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2001);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(201l);
ap.setCostPer(19.00);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2002);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(211l);
ap.setCostPer(17.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2003);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(220l);
ap.setCostPer(25.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2004);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(175l);
ap.setCostPer(24.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
} else if ("generateGeocells".equals(action)) {
AccessPointDao apDao = new AccessPointDao();
List<AccessPoint> apList = apDao.list(null);
if (apList != null) {
for (AccessPoint ap : apList) {
if (ap.getGeocells() == null
|| ap.getGeocells().size() == 0) {
if (ap.getLatitude() != null
&& ap.getLongitude() != null) {
ap.setGeocells(GeocellManager.generateGeoCell(new Point(
ap.getLatitude(), ap.getLongitude())));
apDao.save(ap);
}
}
}
}
} else if ("loadExistingSurvey".equals(action)) {
SurveyGroup sg = new SurveyGroup();
sg.setKey(KeyFactory.createKey(SurveyGroup.class.getSimpleName(),
2L));
sg.setName("test" + new Date());
sg.setCode("test" + new Date());
SurveyGroupDAO sgDao = new SurveyGroupDAO();
sgDao.save(sg);
Survey s = new Survey();
s.setKey(KeyFactory.createKey(Survey.class.getSimpleName(), 2L));
s.setName("test" + new Date());
s.setSurveyGroupId(sg.getKey().getId());
SurveyDAO surveyDao = new SurveyDAO();
surveyDao.save(s);
} else if ("saveAPMapping".equals(action)) {
SurveyAttributeMapping mapping = new SurveyAttributeMapping();
mapping.setAttributeName("status");
mapping.setObjectName(AccessPoint.class.getCanonicalName());
mapping.setSurveyId(1L);
mapping.setSurveyQuestionId("q1");
SurveyAttributeMappingDao samDao = new SurveyAttributeMappingDao();
samDao.save(mapping);
} else if ("listAPMapping".equals(action)) {
SurveyAttributeMappingDao samDao = new SurveyAttributeMappingDao();
List<SurveyAttributeMapping> mappings = samDao
.listMappingsBySurvey(1L);
if (mappings != null) {
System.out.println(mappings.size());
}
} else if ("saveSurveyGroup".equals(action)) {
try {
SurveyGroupDAO sgDao = new SurveyGroupDAO();
List<SurveyGroup> sgList = sgDao.list("all");
for (SurveyGroup sg : sgList) {
sgDao.delete(sg);
}
resp.getWriter().println("Deleted all survey groups");
SurveyDAO surveyDao = new SurveyDAO();
List<Survey> surveyList = surveyDao.list("all");
for (Survey survey : surveyList) {
try {
surveyDao.delete(survey);
} catch (IllegalDeletionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
resp.getWriter().println("Deleted all surveys");
resp.getWriter().println("Deleted all surveysurveygroupassocs");
QuestionGroupDao qgDao = new QuestionGroupDao();
List<QuestionGroup> qgList = qgDao.list("all");
for (QuestionGroup qg : qgList) {
qgDao.delete(qg);
}
resp.getWriter().println("Deleted all question groups");
QuestionDao qDao = new QuestionDao();
List<Question> qList = qDao.list("all");
for (Question q : qList) {
try {
qDao.delete(q);
} catch (IllegalDeletionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
resp.getWriter().println("Deleted all Questions");
QuestionOptionDao qoDao = new QuestionOptionDao();
List<QuestionOption> qoList = qoDao.list("all");
for (QuestionOption qo : qoList)
qoDao.delete(qo);
resp.getWriter().println("Deleted all QuestionOptions");
resp.getWriter().println("Deleted all questions");
resp.getWriter().println(
"Finished deleting and reloading SurveyGroup graph");
} catch (IOException e) {
e.printStackTrace();
}
} else if ("testPublishSurvey".equals(action)) {
try {
SurveyGroupDto sgDto = new SurveyServiceImpl()
.listSurveyGroups(null, true, false, false)
.getPayload().get(0);
resp.getWriter().println(
"Got Survey Group: " + sgDto.getCode() + " Survey: "
+ sgDto.getSurveyList().get(0).getKeyId());
SurveyContainerDao scDao = new SurveyContainerDao();
SurveyContainer sc = scDao.findBySurveyId(sgDto.getSurveyList()
.get(0).getKeyId());
if (sc != null) {
scDao.delete(sc);
resp.getWriter().println(
"Deleted existing SurveyContainer for: "
+ sgDto.getSurveyList().get(0).getKeyId());
}
resp.getWriter().println(
"Result of publishing survey: "
+ new SurveyServiceImpl().publishSurvey(sgDto
.getSurveyList().get(0).getKeyId()));
sc = scDao.findBySurveyId(sgDto.getSurveyList().get(0)
.getKeyId());
resp.getWriter().println(
"Survey Document result from publish: \n\n\n\n"
+ sc.getSurveyDocument().getValue());
} catch (IOException ex) {
ex.printStackTrace();
}
} else if ("createTestSurveyForEndToEnd".equals(action)) {
createTestSurveyForEndToEnd();
} else if ("deleteSurveyFragments".equals(action)) {
deleteAll(SurveyXMLFragment.class);
} else if ("migratePIToSchool".equals(action)) {
try {
resp.getWriter().println(
"Has more? "
+ migratePointType(
AccessPointType.PUBLIC_INSTITUTION,
AccessPointType.SCHOOL));
} catch (IOException e) {
e.printStackTrace();
}
} else if ("createDevice".equals(action)) {
DeviceDAO devDao = new DeviceDAO();
Device device = new Device();
device.setPhoneNumber("9175667663");
device.setDeviceType(DeviceType.CELL_PHONE_ANDROID);
devDao.save(device);
} else if ("reprocessSurveys".equals(action)) {
try {
reprocessSurveys(req.getParameter("date"));
} catch (ParseException e) {
try {
resp.getWriter().println("Couldn't reprocess: " + e);
} catch (IOException e1) {
e1.printStackTrace();
}
}
} else if ("importallsurveys".equals(action)) {
// Only run in dev hence hardcoding
SurveyReplicationImporter sri = new SurveyReplicationImporter();
sri.executeImport("http://watermapmonitordev.appspot.com", null);
// sri.executeImport("http://localhost:8888",
// "http://localhost:8888");
} else if ("importsinglesurvey".equals(action)) {
TaskOptions options = TaskOptions.Builder
.withUrl("/app_worker/dataprocessor")
.param(DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.IMPORT_REMOTE_SURVEY_ACTION)
.param(DataProcessorRequest.SOURCE_PARAM,
req.getParameter("source"))
.param(DataProcessorRequest.SURVEY_ID_PARAM,
req.getParameter("surveyId"));
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
} else if ("rescoreap".equals(action)) {
TaskOptions options = TaskOptions.Builder
.withUrl("/app_worker/dataprocessor")
.param(DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.RESCORE_AP_ACTION)
.param(DataProcessorRequest.COUNTRY_PARAM,
req.getParameter("country"));
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
} else if ("deleteSurveyResponses".equals(action)) {
if (req.getParameter("surveyId") == null) {
try {
resp.getWriter()
.println("surveyId is a required parameter");
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
deleteSurveyResponses(
Integer.parseInt(req.getParameter("surveyId")),
Integer.parseInt(req.getParameter("count")));
}
} else if ("fixNameQuestion".equals(action)) {
if (req.getParameter("questionId") == null) {
try {
resp.getWriter().println(
"questionId is a required parameter");
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
fixNameQuestion(req.getParameter("questionId"));
}
} else if ("createSurveyAssignment".equals(action)) {
Device device = new Device();
device.setDeviceType(DeviceType.CELL_PHONE_ANDROID);
device.setPhoneNumber("1111111111");
device.setInServiceDate(new Date());
BaseDAO<Device> deviceDao = new BaseDAO<Device>(Device.class);
deviceDao.save(device);
SurveyAssignmentServiceImpl sasi = new SurveyAssignmentServiceImpl();
SurveyAssignmentDto dto = new SurveyAssignmentDto();
SurveyDAO surveyDao = new SurveyDAO();
List<Survey> surveyList = surveyDao.list("all");
SurveyAssignment sa = new SurveyAssignment();
BaseDAO<SurveyAssignment> surveyAssignmentDao = new BaseDAO<SurveyAssignment>(
SurveyAssignment.class);
sa.setCreatedDateTime(new Date());
sa.setCreateUserId(-1L);
ArrayList<Long> deviceList = new ArrayList<Long>();
deviceList.add(device.getKey().getId());
sa.setDeviceIds(deviceList);
ArrayList<SurveyDto> surveyDtoList = new ArrayList<SurveyDto>();
for (Survey survey : surveyList) {
sa.addSurvey(survey.getKey().getId());
SurveyDto surveyDto = new SurveyDto();
surveyDto.setKeyId(survey.getKey().getId());
surveyDtoList.add(surveyDto);
}
sa.setStartDate(new Date());
sa.setEndDate(new Date());
sa.setName(new Date().toString());
DeviceDto deviceDto = new DeviceDto();
deviceDto.setKeyId(device.getKey().getId());
deviceDto.setPhoneNumber(device.getPhoneNumber());
ArrayList<DeviceDto> deviceDtoList = new ArrayList<DeviceDto>();
deviceDtoList.add(deviceDto);
dto.setDevices(deviceDtoList);
dto.setSurveys(surveyDtoList);
dto.setEndDate(new Date());
dto.setLanguage("en");
dto.setName("Test Assignment: " + new Date().toString());
dto.setStartDate(new Date());
sasi.saveSurveyAssignment(dto);
// sasi.deleteSurveyAssignment(dto);
} else if ("populateAssignmentId".equalsIgnoreCase(action)) {
populateAssignmentId(Long.parseLong(req
.getParameter("assignmentId")));
} else if ("testDSJQDelete".equals(action)) {
DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO();
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -10);
Date then = cal.getTime();
DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue();
dsjq.setDevicePhoneNumber("2019561591");
dsjq.setEffectiveEndDate(then);
Random rand = new Random();
dsjq.setAssignmentId(rand.nextLong());
dsjDAO.save(dsjq);
DeviceSurveyJobQueue dsjq2 = new DeviceSurveyJobQueue();
dsjq2.setDevicePhoneNumber("2019561591");
cal.add(Calendar.DAY_OF_MONTH, 20);
dsjq2.setEffectiveEndDate(cal.getTime());
dsjq2.setAssignmentId(rand.nextLong());
dsjDAO.save(dsjq2);
DeviceSurveyJobQueueDAO dsjqDao = new DeviceSurveyJobQueueDAO();
List<DeviceSurveyJobQueue> dsjqList = dsjqDao
.listAssignmentsWithEarlierExpirationDate(new Date());
for (DeviceSurveyJobQueue item : dsjqList) {
SurveyTaskUtil.spawnDeleteTask("deleteDeviceSurveyJobQueue",
item.getAssignmentId());
}
} else if ("loadDSJ".equals(action)) {
SurveyDAO surveyDao = new SurveyDAO();
List<Survey> surveyList = surveyDao.list("all");
for (Survey item : surveyList) {
DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO();
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -10);
Date then = cal.getTime();
DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue();
dsjq.setDevicePhoneNumber("2019561591");
dsjq.setEffectiveEndDate(then);
Random rand = new Random();
dsjq.setAssignmentId(rand.nextLong());
dsjq.setSurveyID(item.getKey().getId());
dsjDAO.save(dsjq);
}
for (int i = 0; i < 20; i++) {
DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO();
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -10);
Date then = cal.getTime();
DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue();
dsjq.setDevicePhoneNumber("2019561591");
dsjq.setEffectiveEndDate(then);
Random rand = new Random();
dsjq.setAssignmentId(rand.nextLong());
dsjq.setSurveyID(rand.nextLong());
dsjDAO.save(dsjq);
}
try {
resp.getWriter().println("finished");
} catch (IOException e1) {
e1.printStackTrace();
}
} else if ("deleteUnusedDSJQueue".equals(action)) {
try {
SurveyDAO surveyDao = new SurveyDAO();
List<Key> surveyIdList = surveyDao.listSurveyIds();
List<Long> ids = new ArrayList<Long>();
for (Key key : surveyIdList)
ids.add(key.getId());
DeviceSurveyJobQueueDAO dsjqDao = new DeviceSurveyJobQueueDAO();
List<DeviceSurveyJobQueue> deleteList = new ArrayList<DeviceSurveyJobQueue>();
for (DeviceSurveyJobQueue item : dsjqDao.listAllJobsInQueue()) {
Long dsjqSurveyId = item.getSurveyID();
Boolean found = ids.contains(dsjqSurveyId);
if (!found) {
deleteList.add(item);
resp.getWriter().println(
"Marking " + item.getId() + " survey: "
+ item.getSurveyID() + " for deletion");
}
}
dsjqDao.delete(deleteList);
resp.getWriter().println("finished");
} catch (IOException e1) {
e1.printStackTrace();
}
} else if ("testListTrace".equals(action)) {
listStacktrace();
} else if ("createEditorialContent".equals(action)) {
createEditorialContent(req.getParameter("pageName"));
} else if ("generateEditorialContent".equals(action)) {
try {
resp.getWriter().print(
generateEditorialContent(req.getParameter("pageName")));
} catch (IOException e) {
e.printStackTrace();
}
} else if ("populateperms".equals(action)) {
populatePermissions();
} else if ("testnotif".equals(action)) {
sendNotification(req.getParameter("surveyId"));
} else if ("popsurvey".equals(action)) {
SurveyDAO sDao = new SurveyDAO();
List<Survey> sList = sDao.list(null);
QuestionDao questionDao = new QuestionDao();
List<Question> qList = questionDao.listQuestionByType(sList.get(0)
.getKey().getId(), Question.Type.FREE_TEXT);
SurveyInstanceDAO instDao = new SurveyInstanceDAO();
for (int i = 0; i < 10; i++) {
SurveyInstance instance = new SurveyInstance();
instance.setSurveyId(sList.get(0).getKey().getId());
instance = instDao.save(instance);
for (int j = 0; j < qList.size(); j++) {
QuestionAnswerStore ans = new QuestionAnswerStore();
ans.setQuestionID(qList.get(j).getKey().getId() + "");
ans.setValue("" + j * i);
ans.setSurveyInstanceId(instance.getKey().getId());
// ans.setSurveyInstance(instance);
instDao.save(ans);
}
}
try {
resp.getWriter().print(sList.get(0).getKey().getId());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("testnotifhelper".equals(action)) {
NotificationHelper helper = new NotificationHelper("rawDataReport",
null);
helper.execute();
} else if ("testremotemap".equals(action)) {
createDevice("12345", 40.78, -73.95);
createDevice("777", 43.0, -78.8);
RemoteStacktrace st = new RemoteStacktrace();
st.setAcknowleged(false);
st.setPhoneNumber("12345");
st.setErrorDate(new Date());
st.setStackTrace(new Text("blah"));
RemoteStacktraceDao dao = new RemoteStacktraceDao();
dao.save(st);
st = new RemoteStacktrace();
st.setAcknowleged(false);
st.setErrorDate(new Date());
st.setPhoneNumber("777");
st.setStackTrace(new Text("ugh"));
dao.save(st);
} else if ("createMetricMapping".equals(action)) {
createMetricMapping(req.getParameter("metric"));
} else if ("listMetricSummaries".equals(action)) {
try {
resp.getWriter().print(
listMetricSummaries(
new Integer(req.getParameter("level")),
req.getParameter("name")));
} catch (IOException e) {
e.printStackTrace();
}
} else if ("deleteMetricSummaries".equals(action)) {
deleteMetricSummaries(new Integer(req.getParameter("level")),
req.getParameter("name"));
} else if ("createSurveyQuestionSummary".equals(action)) {
SurveyQuestionSummary sum = new SurveyQuestionSummary();
sum.setCount(10L);
sum.setResponse("TEST");
sum.setQuestionId("2166031");
SurveyQuestionSummaryDao dao = new SurveyQuestionSummaryDao();
dao.save(sum);
sum = new SurveyQuestionSummary();
sum.setCount(20L);
sum.setResponse("OTHER");
sum.setQuestionId("2166031");
dao.save(sum);
sum = new SurveyQuestionSummary();
sum.setCount(30L);
sum.setResponse("GWAR");
sum.setQuestionId("2166031");
dao.save(sum);
} else if ("createCountry".equals(action)) {
Country country = new Country();
country.setIsoAlpha2Code("LR");
country.setName("Liberia");
CountryDao dao = new CountryDao();
dao.save(country);
} else if ("populateSubCountry".equals(action)) {
try {
String country = req.getParameter("country");
if (country != null) {
Queue summQueue = QueueFactory
.getQueue("dataSummarization");
summQueue.add(TaskOptions.Builder
.withUrl("/app_worker/datasummarization")
.param("objectKey", country)
.param("type", "OGRFeature"));
} else {
resp.getWriter()
.println("country is a mandatory parameter");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("listSubCountry".equals(action)) {
try {
String country = req.getParameter("country");
if (country != null) {
SubCountryDao subDao = new SubCountryDao();
List<SubCountry> results = subDao.list(null);
if (results != null) {
for (SubCountry c : results) {
resp.getWriter().println(c.toString());
}
}
} else {
resp.getWriter()
.println("country is a mandatory parameter");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("clearcache".equals(action)) {
CacheFactory cacheFactory;
try {
cacheFactory = CacheManager.getInstance().getCacheFactory();
Cache cache = cacheFactory.createCache(Collections.emptyMap());
cache.clear();
} catch (CacheException e) {
e.printStackTrace();
}
} else if ("startProjectFlagUpdate".equals(action)) {
DataProcessorRestServlet.sendProjectUpdateTask(
req.getParameter("country"), null);
} else if (DataProcessorRequest.REBUILD_QUESTION_SUMMARY_ACTION
.equals(action)) {
TaskOptions options = TaskOptions.Builder.withUrl(
"/app_worker/dataprocessor").param(
DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.REBUILD_QUESTION_SUMMARY_ACTION);
if (req.getParameter("bypassBackend") == null
|| !req.getParameter("bypassBackend").equals("true")) {
// change the host so the queue invokes the backend
options = options
.header("Host",
BackendServiceFactory.getBackendService()
.getBackendAddress("dataprocessor"));
}
String surveyId = req
.getParameter(DataProcessorRequest.SURVEY_ID_PARAM);
if (surveyId != null && surveyId.trim().length() > 0) {
options.param(DataProcessorRequest.SURVEY_ID_PARAM, surveyId);
}
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
} else if ("deleteallqsum".equals(action)) {
DeleteObjectUtil dou = new DeleteObjectUtil();
dou.deleteAllObjects("SurveyQuestionSummary");
} else if ("fixNullSubmitter".equals(action)) {
TaskOptions options = TaskOptions.Builder.withUrl(
"/app_worker/dataprocessor").param(
DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.FIX_NULL_SUBMITTER_ACTION);
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
} else if ("createVals".equals(action)) {
SurveyedLocaleDao localeDao = new SurveyedLocaleDao();
List<SurveyedLocale> lList = localeDao.list(null);
if (lList != null && lList.size() > 0) {
List<SurveyalValue> valList = new ArrayList<SurveyalValue>();
for (int i = 0; i < 50; i++) {
SurveyalValue val = new SurveyalValue();
val.setSurveyedLocaleId(lList.get(0).getKey().getId());
val.setStringValue("val:" + i);
val.setQuestionText("TEXT: " + i);
val.setLocaleType(lList.get(0).getLocaleType());
val.setQuestionType("FREE_TEXT");
val.setSurveyInstanceId(lList.get(0)
.getLastSurveyalInstanceId());
valList.add(val);
}
localeDao.save(valList);
}
} else if ("fixDuplicateOtherText".equals(action)) {
TaskOptions options = TaskOptions.Builder.withUrl(
"/app_worker/dataprocessor").param(
DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.FIX_DUPLICATE_OTHER_TEXT_ACTION);
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
} else if ("fixNullGroupNames".equals(action)) {
fixNullQuestionGroupNames();
} else if ("trimOptions".equals(action)) {
TaskOptions options = TaskOptions.Builder.withUrl(
"/app_worker/dataprocessor").param(
DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.TRIM_OPTIONS);
if (req.getParameter("bypassBackend") == null
|| !req.getParameter("bypassBackend").equals("true")) {
// change the host so the queue invokes the backend
options = options
.header("Host",
BackendServiceFactory.getBackendService()
.getBackendAddress("dataprocessor"));
}
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
} else if ("testTemplateOverride".equals(action)) {
KMLGenerator gen = new KMLGenerator();
SurveyedLocale ap = new SurveyedLocale();
ap.setAmbiguous(false);
ap.setCountryCode("US");
ap.setCreatedDateTime(new Date());
ap.setCurrentStatus("OK");
ap.setIdentifier("1234");
ap.setLastSurveyedDate(new Date());
ap.setLatitude(12d);
ap.setLongitude(12d);
try {
String result = gen.bindPlacemark(ap,
"localePlacemarkExternal.vm", null);
resp.getWriter().println(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("setSuperUser".equals(action)) {
String email = req.getParameter("email");
UserDao udao = new UserDao();
User u = udao.findUserByEmail(email);
if (u != null) {
u.setSuperAdmin(true);
}
}else if("fixImages".equals(action)){
String surveyId = req.getParameter("surveyId");
String find = req.getParameter("find");
String replace = req.getParameter("replace");
if(surveyId != null && !surveyId.trim().isEmpty() && find!=null && !find.trim().isEmpty()){
fixBadImage(surveyId,find,replace);
}
}
}
| public void doGet(HttpServletRequest req, HttpServletResponse resp) {
String action = req.getParameter("action");
if ("setupTestUser".equals(action)) {
setupTestUser();
} else if ("computeDistanceAlongBearing".equals(action)) {
com.gallatinsystems.gis.coordinate.utilities.CoordinateUtilities cu = new CoordinateUtilities();
Coordinate startingPoint = new Coordinate(Double.parseDouble(req
.getParameter("lat")), Double.parseDouble(req
.getParameter("lon")));
Double distance = Double.parseDouble(req.getParameter("distance"));
Double bearing = Double.parseDouble(req.getParameter("bearing"));
Coordinate newPoint = cu.computePointAlongBearingDistance(
startingPoint, distance, bearing);
try {
resp.getWriter().println("New Point : " + newPoint.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("fixQuestionAnswerStoreDates".equals(action)) {
// DataFixes df = new DataFixes();
// df.generateTestData();
Queue queue = QueueFactory.getDefaultQueue();
queue.add(TaskOptions.Builder
.withUrl("/app_worker/questionanswerstorecleanup"));
log.info("submiting task QAS CollectionDate Cleanup");
} else if ("reprocessFiles".equalsIgnoreCase(action)) {
DeviceFilesDao dfDao = new DeviceFilesDao();
String cursor = null;
List<DeviceFiles> files = null;
do {
files = dfDao.listDeviceFilesByStatus(StatusCode.IN_PROGRESS,
cursor);
if (files != null) {
cursor = DeviceFilesDao.getCursor(files);
Queue queue = QueueFactory.getDefaultQueue();
for (DeviceFiles fi : files) {
queue.add(TaskOptions.Builder
.withUrl("/app_worker/task")
.param("action", "processFile")
.param("fileName",
fi.getURI()
.substring(
fi.getURI()
.lastIndexOf(
"/") + 1)));
}
}
} while (files != null && files.size() > 0 && cursor != null);
} else if ("testStandardScoring".equals(action)) {
StandardTestLoader stl = new StandardTestLoader(req, resp);
stl.runTest();
} else if ("listStandardScoringResults".equals(action)) {
StandardTestLoader stl = new StandardTestLoader(req, resp);
String countryCode = null;
String communityCode = null;
String accessPointCode = null;
if (req.getParameter("countryCode") != null) {
countryCode = req.getParameter("countryCode");
}
if (req.getParameter("communityCode") != null) {
communityCode = req.getParameter("communityCode");
}
if (req.getParameter("accessPointCode") != null) {
accessPointCode = req.getParameter("accessPointCode");
}
String cursorString = null;
if (req.getParameter("cursorString") != null) {
cursorString = req.getParameter("cursorString");
}
stl.listResults(countryCode, communityCode, accessPointCode,
cursorString);
} else if ("testDistanceRule".equals(action)) {
DeleteObjectUtil dou = new DeleteObjectUtil();
dou.deleteAllObjects("AccessPointScoreComputationItem");
dou.deleteAllObjects("AccessPointScoreDetail");
// AccessPointTest apt = new AccessPointTest();
// apt.loadWPDistanceTestData(resp);
// apt.loadHHDistanceTestData(resp);
// AccessPointDao apDao = new AccessPointDao();
// List<AccessPoint> apList = apDao.list("all");
// AccessPointHelper aph = new AccessPointHelper();
// for (AccessPoint ap : apList) {
// aph.computeDistanceRule(ap);
// }
// try {
// resp.getWriter().println("Completed test distance rule");
// } catch (IOException e) {
// e.printStackTrace();
// }
} else if ("setupDevEnv".equals(action)) {
try {
DeleteObjectUtil dou = new DeleteObjectUtil();
dou.deleteAllObjects("AccessPoint");
dou.deleteAllObjects("StandardScoreBucket");
dou.deleteAllObjects("StandardScoring");
resp.getWriter().println(
"About to configure development environment");
setupTestUser();
resp.getWriter().println("Completed setting up test user");
resp.getWriter().println("Completed setting up permissions");
AccessPointTest apt = new AccessPointTest();
apt.loadLots(resp, 100);
StandardScoringTest sct = new StandardScoringTest();
sct.populateData();
setupMetrics();
resp.getWriter().println("Completed setting scorebuckets");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("populateAccessPointMetric".equals(action)) {
AccessPointMetricSummaryTest apMST = new AccessPointMetricSummaryTest();
apMST.runTest(resp);
} else if ("reorderQuestionsByCollectionDate".equals(action)) {
try {
Long surveyId = Long.parseLong(req.getParameter("surveyId"));
SurveyDAO surveyDao = new SurveyDAO();
QuestionDao qDao = new QuestionDao();
Survey survey = surveyDao.loadFullSurvey(surveyId);
int i = 0;
for (Map.Entry<Integer, QuestionGroup> qGEntry : survey
.getQuestionGroupMap().entrySet()) {
List<Question> qList = qDao
.listQuestionsByQuestionGroupOrderByCreatedDateTime(qGEntry
.getValue().getKey().getId());
for (Question q : qDao
.listQuestionsByQuestionGroupOrderByCreatedDateTime(qGEntry
.getValue().getKey().getId())) {
q.setOrder(i + 1);
qDao.save(q);
resp.getWriter().println(
q.getOrder() + " :Change: " + q.getText());
++i;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("fixQuestionOrder".equals(action)) {
Long surveyId = Long.parseLong(req.getParameter("surveyId"));
QuestionDao qDao = new QuestionDao();
// this is the list in ascending order by the "order" field
List<Question> qList = qDao.listQuestionsBySurvey(surveyId);
if (qList != null) {
Map<Long, Integer> groupMaxCount = new HashMap<Long, Integer>();
for (Question q : qList) {
Integer max = groupMaxCount.get(q.getQuestionGroupId());
if (max == null) {
max = 1;
} else {
max = max + 1;
}
// since q is still attached, this should be all we need to
// do
q.setOrder(max);
groupMaxCount.put(q.getQuestionGroupId(), max);
}
}
} else if ("deleteGeoData".equals(action)) {
try {
OGRFeatureDao ogrFeatureDao = new OGRFeatureDao();
for (OGRFeature item : ogrFeatureDao.list("all")) {
resp.getWriter().println(
"deleting: " + item.getCountryCode());
ogrFeatureDao.delete(item);
}
resp.getWriter().println("Finished");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("testGeoLocation".equals(action)) {
OGRFeatureDao ogrFeatureDao = new OGRFeatureDao();
GeoLocationServiceGeonamesImpl gs = new GeoLocationServiceGeonamesImpl();
String lat = req.getParameter("lat");
String lon = req.getParameter("lon");
GeoPlace geoPlace = gs.manualLookup(lat, lon);
try {
if (geoPlace != null) {
resp.getWriter().println(
"Found: " + geoPlace.getCountryName() + ":"
+ geoPlace.getCountryCode() + " for " + lat
+ ", " + lon);
geoPlace = gs.resolveSubCountry(lat, lon,
geoPlace.getCountryCode());
}
if (geoPlace != null)
resp.getWriter().println(
"Found: " + geoPlace.getCountryCode() + ":"
+ geoPlace.getSub1() + ":"
+ geoPlace.getSub2() + ":"
+ geoPlace.getSub3() + ":"
+ geoPlace.getSub4() + ":"
+ geoPlace.getSub5() + ":"
+ geoPlace.getSub6() + " for " + lat + ", "
+ lon);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("testDetailedGeoLocation".equals(action)) {
OGRFeatureDao ogrFeatureDao = new OGRFeatureDao();
GeoLocationServiceGeonamesImpl gs = new GeoLocationServiceGeonamesImpl();
String lat = req.getParameter("lat");
String lon = req.getParameter("lon");
GeoPlace geoPlace = gs.manualLookup(lat, lon, OGRFeature.FeatureType.SUB_COUNTRY_OTHER);
try {
if (geoPlace != null) {
resp.getWriter().println(
"Found: " + geoPlace.getCountryName() + ":"
+ geoPlace.getCountryCode() + " for " + lat
+ ", " + lon);
geoPlace = gs.resolveSubCountry(lat, lon,
geoPlace.getCountryCode());
}
if (geoPlace != null)
resp.getWriter().println(
"Found: " + geoPlace.getCountryCode() + ":"
+ geoPlace.getSub1() + ":"
+ geoPlace.getSub2() + ":"
+ geoPlace.getSub3() + ":"
+ geoPlace.getSub4() + ":"
+ geoPlace.getSub5() + ":"
+ geoPlace.getSub6() + " for " + lat + ", "
+ lon);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("RemapAPToSub".equals(action)) {
AccessPointDao apDao = new AccessPointDao();
} else if ("loadOGRFeature".equals(action)) {
OGRFeature ogrFeature = new OGRFeature();
ogrFeature.setName("clan-21061011");
ogrFeature.setProjectCoordinateSystemIdentifier("World_Mercator");
ogrFeature.setGeoCoordinateSystemIdentifier("GCS_WGS_1984");
ogrFeature.setDatumIdentifier("WGS_1984");
ogrFeature.setSpheroid(6378137D);
ogrFeature.setReciprocalOfFlattening(298.257223563);
ogrFeature.setCountryCode("LR");
ogrFeature.addBoundingBox(223700.015625, 481399.468750,
680781.375000, 945462.437500);
Geometry geo = new Geometry();
geo.setType(GeometryType.POLYGON);
String coords = "497974.5625 557051.875,498219.03125 557141.75,498655.34375 557169.4375,499001.65625 557100.1875,499250.96875 556933.9375,499167.875 556615.375,499230.1875 556407.625,499392.78125 556362.75,499385.90625 556279.875,499598.5 556067.3125,499680.25 555952.8125,499218.5625 554988.875,498775.65625 554860.1875,498674.5 554832.5625,498282.0 554734.4375,498020.34375 554554.5625,497709.59375 554374.6875,497614.84375 554374.6875,497519.46875 554369.1875,497297.3125 554359.9375,496852.96875 554355.3125,496621.125 554351.375,496695.75 554454.625,496771.59375 554604.625,496836.3125 554734.0625,496868.65625 554831.125,496847.09375 554863.4375,496760.8125 554863.4375,496663.75 554928.125,496620.625 554992.875,496555.90625 555025.1875,496448.0625 554992.875,496372.5625 555025.1875,496351.0 555133.0625,496415.71875 555197.75,496480.40625 555294.8125,496480.40625 555381.0625,496430.875 555430.75,496446.0625 555547.375,496490.53125 555849.625,496526.09375 556240.75,496721.65625 556596.375,496924.90625 556774.1875,497006.125 556845.25,497281.71875 556978.625,497610.625 556969.6875,497859.53125 556969.6875,497974.5625 557051.875";
for (String item : coords.split(",")) {
String[] coord = item.split(" ");
geo.addCoordinate(Double.parseDouble(coord[0]),
Double.parseDouble(coord[1]));
}
ogrFeature.setGeometry(geo);
ogrFeature.addGeoMeasure("CLNAME", "STRING", "Loisiana Township");
ogrFeature.addGeoMeasure("COUNT", "FLOAT", "1");
BaseDAO<OGRFeature> ogrDao = new BaseDAO<OGRFeature>(
OGRFeature.class);
ogrDao.save(ogrFeature);
try {
resp.getWriter()
.println("OGRFeature: " + ogrFeature.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("printOGRFeature".equals(action)) {
OGRFeatureDao ogrFeatureDao = new OGRFeatureDao();
FeatureType featureType = FeatureType.valueOf(req
.getParameter("featureType"));
List<OGRFeature> ogrFeatureList = ogrFeatureDao
.listByCountryAndType(req.getParameter("countryCode"),
featureType, null);
try {
int i = 1;
if (ogrFeatureList != null && !ogrFeatureList.isEmpty()) {
for (OGRFeature item : ogrFeatureList) {
resp.getWriter().println(
"i: " + i + " sub1" + item.getSub1()
+ " sub2: " + item.getSub2());
resp.getWriter().println(
" OGRFeature: " + item.toString());
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("resetLRAP".equals(action)) {
try {
AccessPointDao apDao = new AccessPointDao();
Random rand = new Random();
for (AccessPoint ap : apDao.list("all")) {
if ((ap.getCountryCode() == null || ap.getCountryCode()
.equals("US"))
&& (ap.getLatitude() != null && ap.getLongitude() != null)) {
if (ap.getLatitude() > 5.0 && ap.getLatitude() < 11) {
if (ap.getLongitude() < -9
&& ap.getLongitude() > -11) {
ap.setCountryCode("LR");
apDao.save(ap);
resp.getWriter()
.println(
"Found "
+ ap.getCommunityCode()
+ "mapped to US changing mapping to LR \n");
}
}
} else if (ap.getCommunityCode() == null) {
ap.setCommunityCode(rand.nextLong() + "");
apDao.save(ap);
resp.getWriter().println(
"Found " + ap.getCommunityCode()
+ "added random community code \n");
}
}
} catch (IOException e) {
log.log(Level.SEVERE, "Could not execute test", e);
}
} else if ("populateAccessPointMetricSummary".equals(action)) {
OGRFeatureDao ogrFeatureDao = new OGRFeatureDao();
AccessPointMetricSummaryDao apmsDao = new AccessPointMetricSummaryDao();
// List<OGRFeature> ogrList =
// ogrFeatureDao.listByCountryAndType("LR",
// FeatureType.SUB_COUNTRY_OTHER);
Boolean firstTimeFlag = false;
// for (OGRFeature item : ogrList) {
// AccessPointMetricSummary apms = new AccessPointMetricSummary();
// apms.setCount(1L);
// apms.setCountry("LR");
// apms.setSubLevel(1);
// apms.setSubValue(item.getSub1());
// apms.setShardNum(1);
// apms.setParentSubName("LR");
// apms.setMetricName("WATER_POINT");
// apmsDao.save(apms);
// }
} else if ("populateStandardScoring".equals(action)) {
StandardScoringTest sst = new StandardScoringTest();
sst.populateData();
} else if ("clearSurveyInstanceQAS".equals(action)) {
// QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao();
// for (QuestionAnswerStore qas : qasDao.list("all")) {
// qasDao.delete(qas);
// }
// SurveyInstanceDAO siDao = new SurveyInstanceDAO();
// for (SurveyInstance si : siDao.list("all")) {
// siDao.delete(si);
// }
AccessPointDao apDao = new AccessPointDao();
for (AccessPoint ap : apDao.list("all"))
apDao.delete(ap);
} else if ("SurveyInstance".equals(action)) {
SurveyInstanceDAO siDao = new SurveyInstanceDAO();
List<SurveyInstance> siList = siDao.listSurveyInstanceBySurveyId(
1362011L, null);
Cursor cursor = JDOCursorHelper.getCursor(siList);
int i = 0;
while (siList.size() > 0) {
for (SurveyInstance si : siList) {
System.out.println(i++ + " " + si.toString());
String surveyInstanceId = new Long(si.getKey().getId())
.toString();
Queue queue = QueueFactory.getDefaultQueue();
queue.add(TaskOptions.Builder
.withUrl("/app_worker/surveytask")
.param("action", "reprocessMapSurveyInstance")
.param("id", surveyInstanceId));
log.info("submiting task for SurveyInstanceId: "
+ surveyInstanceId);
}
siList = siDao.listSurveyInstanceBySurveyId(1362011L,
cursor.toWebSafeString());
cursor = JDOCursorHelper.getCursor(siList);
}
System.out.println("finished");
} else if ("rotateImage".equals(action)) {
AccessPointManagerServiceImpl apmI = new AccessPointManagerServiceImpl();
String test1 = "http://waterforpeople.s3.amazonaws.com/images/wfpPhoto10062903227521.jpg";
// String test2 =
// "http://waterforpeople.s3.amazonaws.com/images/hn/ch003[1].jpg";
writeImageToResponse(resp, test1);
apmI.setUploadS3Flag(false);
// apmI.rotateImage(test2);
} else if ("clearSurveyGroupGraph".equals(action)) {
SurveyGroupDAO sgDao = new SurveyGroupDAO();
sgDao.delete(sgDao.list("all"));
SurveyDAO surveyDao = new SurveyDAO();
surveyDao.delete(surveyDao.list("all"));
QuestionGroupDao qgDao = new QuestionGroupDao();
qgDao.delete(qgDao.list("all"));
QuestionDao qDao = new QuestionDao();
qDao.delete(qDao.list("all"));
QuestionHelpMediaDao qhDao = new QuestionHelpMediaDao();
qhDao.delete(qhDao.list("all"));
QuestionOptionDao qoDao = new QuestionOptionDao();
qoDao.delete(qoDao.list("all"));
TranslationDao tDao = new TranslationDao();
tDao.delete(tDao.list("all"));
} else if ("replicateDeviceFiles".equals(action)) {
SurveyInstanceDAO siDao = new SurveyInstanceDAO();
for (SurveyInstance si : siDao.list("all")) {
siDao.delete(si);
}
QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao();
for (QuestionAnswerStore qas : qasDao.list("all")) {
qasDao.delete(qas);
}
DeviceFilesDao dfDao = new DeviceFilesDao();
for (DeviceFiles df : dfDao.list("all")) {
dfDao.delete(df);
}
DeviceFilesReplicationImporter dfri = new DeviceFilesReplicationImporter();
dfri.executeImport("http://watermapmonitordev.appspot.com",
"http://localhost:8888");
Set<String> dfSet = new HashSet<String>();
for (DeviceFiles df : dfDao.list("all")) {
dfSet.add(df.getURI());
}
DeviceFilesServiceImpl dfsi = new DeviceFilesServiceImpl();
int i = 0;
try {
resp.getWriter().println(
"Found " + dfSet.size() + " distinct files to process");
for (String s : dfSet) {
dfsi.reprocessDeviceFile(s);
resp.getWriter().println(
"submitted " + s + " for reprocessing");
i++;
if (i > 10)
break;
}
} catch (IOException e) {
log.log(Level.SEVERE, "Could not execute test", e);
}
} else if ("addDeviceFiles".equals(action)) {
DeviceFilesDao dfDao = new DeviceFilesDao();
DeviceFiles df = new DeviceFiles();
df.setURI("http://waterforpeople.s3.amazonaws.com/devicezip/wfp1737657928520.zip");
df.setCreatedDateTime(new Date());
df.setPhoneNumber("a4:ed:4e:54:ef:6d");
df.setChecksum("1149406886");
df.setProcessedStatus(StatusCode.ERROR_INFLATING_ZIP);
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd");
java.util.Date date = new java.util.Date();
String dateTime = dateFormat.format(date);
df.setProcessDate(dateTime);
dfDao.save(df);
} else if ("populateScoreBuckets".equals(action)) {
BaseDAO<StandardScoreBucket> scDao = new BaseDAO<StandardScoreBucket>(
StandardScoreBucket.class);
ArrayList<String> scoreBuckets = new ArrayList<String>();
scoreBuckets.add("WATERPOINTLEVELOFSERVICE");
scoreBuckets.add("WATERPOINTSUSTAINABILITY");
scoreBuckets.add("PUBLICINSTITUTIONLEVELOFSERVICE");
scoreBuckets.add("PUBLICINSTITUTIONSUSTAINABILITY");
for (String item : scoreBuckets) {
StandardScoreBucket sbucket = new StandardScoreBucket();
sbucket.setName(item);
scDao.save(sbucket);
}
} else if ("testSaveRegion".equals(action)) {
GeoRegionHelper geoHelp = new GeoRegionHelper();
ArrayList<String> regionLines = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
StringBuilder builder = new StringBuilder();
builder.append("1,").append("" + i).append(",test,")
.append(20 + i + ",").append(30 + i + "\n");
regionLines.add(builder.toString());
}
geoHelp.processRegionsSurvey(regionLines);
try {
resp.getWriter().print("Save complete");
} catch (IOException e) {
log.log(Level.SEVERE, "Could not save test region", e);
}
} else if ("clearAccessPoint".equals(action)) {
try {
AccessPointDao apDao = new AccessPointDao();
for (AccessPoint ap : apDao.list("all")) {
apDao.delete(ap);
try {
resp.getWriter().print(
"Finished Deleting AP: " + ap.toString());
} catch (IOException e) {
log.log(Level.SEVERE, "Could not delete ap");
}
}
resp.getWriter().print("Deleted AccessPoints complete");
BaseDAO<AccessPointStatusSummary> apsDao = new BaseDAO<AccessPointStatusSummary>(
AccessPointStatusSummary.class);
for (AccessPointStatusSummary item : apsDao.list("all")) {
apsDao.delete(item);
}
resp.getWriter().print("Deleted AccessPointStatusSummary");
MapFragmentDao mfDao = new MapFragmentDao();
for (MapFragment item : mfDao.list("all")) {
mfDao.delete(item);
}
resp.getWriter().print("Cleared MapFragment Table");
} catch (IOException e) {
log.log(Level.SEVERE, "Could not clear AP and APStatusSummary",
e);
}
} else if ("loadErrorPoints".equals(action)) {
MapFragmentDao mfDao = new MapFragmentDao();
AccessPointDao apDao = new AccessPointDao();
for (int j = 0; j < 1; j++) {
Double lat = 0.0;
Double lon = 0.0;
for (int i = 0; i < 5; i++) {
AccessPoint ap = new AccessPoint();
ap.setLatitude(lat);
ap.setLongitude(lon);
Calendar calendar = Calendar.getInstance();
Date today = new Date();
calendar.setTime(today);
calendar.add(Calendar.YEAR, -1 * i);
System.out
.println("AP: " + ap.getLatitude() + "/"
+ ap.getLongitude() + "Date: "
+ calendar.getTime());
ap.setCollectionDate(calendar.getTime());
ap.setAltitude(0.0);
ap.setCommunityCode("test" + new Date());
ap.setCommunityName("test" + new Date());
ap.setPhotoURL("http://test.com");
ap.setPointType(AccessPoint.AccessPointType.WATER_POINT);
if (i == 0)
ap.setPointStatus(AccessPoint.Status.FUNCTIONING_HIGH);
else if (i == 1)
ap.setPointStatus(AccessPoint.Status.FUNCTIONING_OK);
else if (i == 2)
ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS);
else
ap.setPointStatus(Status.NO_IMPROVED_SYSTEM);
if (i % 2 == 0)
ap.setTypeTechnologyString("Kiosk");
else
ap.setTypeTechnologyString("Afridev Handpump");
apDao.save(ap);
// ms.performSummarization("" + ap.getKey().getId(), "");
if (i % 50 == 0)
log.log(Level.INFO, "Loaded to " + i);
}
}
try {
resp.getWriter().println("Finished loading aps");
} catch (IOException e) {
e.printStackTrace();
}
} else if ("loadLots".equals(action)) {
AccessPointTest apt = new AccessPointTest();
apt.loadLots(resp, 500);
} else if ("loadCountries".equals(action)) {
Country c = new Country();
c.setIsoAlpha2Code("HN");
c.setName("Honduras");
c.setIncludeInExternal(true);
c.setCentroidLat(14.7889035);
c.setCentroidLon(-86.9500379);
c.setZoomLevel(8);
BaseDAO<Country> countryDAO = new BaseDAO<Country>(Country.class);
countryDAO.save(c);
Country c2 = new Country();
c2.setIsoAlpha2Code("MW");
c2.setName("Malawi");
c2.setIncludeInExternal(true);
c2.setCentroidLat(-13.0118377);
c2.setCentroidLon(33.9984484);
c2.setZoomLevel(7);
countryDAO.save(c2);
Country c3 = new Country();
c3.setIsoAlpha2Code("UG");
c3.setName("Uganda");
c3.setIncludeInExternal(true);
c3.setCentroidLat(1.1027);
c3.setCentroidLon(32.3968);
c3.setZoomLevel(7);
countryDAO.save(c3);
Country c4 = new Country();
c4.setIsoAlpha2Code("KE");
c4.setName("Kenya");
c4.setIncludeInExternal(true);
c4.setCentroidLat(-1.26103461);
c4.setCentroidLon(36.74724467);
c4.setZoomLevel(7);
countryDAO.save(c4);
} else if ("testAPKml".equals(action)) {
MapFragmentDao mfDao = new MapFragmentDao();
BaseDAO<TechnologyType> ttDao = new BaseDAO<TechnologyType>(
TechnologyType.class);
List<TechnologyType> ttList = ttDao.list("all");
for (TechnologyType tt : ttList)
ttDao.delete(tt);
TechnologyType tt = new TechnologyType();
tt.setCode("Afridev Handpump");
tt.setName("Afridev Handpump");
ttDao.save(tt);
TechnologyType tt2 = new TechnologyType();
tt2.setCode("Kiosk");
tt2.setName("Kiosk");
ttDao.save(tt2);
KMLHelper kmlHelper = new KMLHelper();
kmlHelper.buildMap();
List<MapFragment> mfList = mfDao
.searchMapFragments("ALL", null, null,
FRAGMENTTYPE.GLOBAL_ALL_PLACEMARKS, "all", null,
null);
try {
for (MapFragment mfItem : mfList) {
String contents = ZipUtil
.unZip(mfItem.getBlob().getBytes());
log.log(Level.INFO, "Contents Length: " + contents.length());
resp.setContentType("application/vnd.google-earth.kmz+xml");
ServletOutputStream out = resp.getOutputStream();
resp.setHeader("Content-Disposition",
"inline; filename=waterforpeoplemapping.kmz;");
out.write(mfItem.getBlob().getBytes());
out.flush();
}
} catch (IOException ie) {
log.log(Level.SEVERE, "Could not list fragment");
}
} else if ("deleteSurveyGraph".equals(action)) {
deleteAll(SurveyGroup.class);
deleteAll(Survey.class);
deleteAll(QuestionGroup.class);
deleteAll(Question.class);
deleteAll(Translation.class);
deleteAll(QuestionOption.class);
deleteAll(QuestionHelpMedia.class);
try {
resp.getWriter().println("Finished deleting survey graph");
} catch (IOException iex) {
log.log(Level.SEVERE, "couldn't delete surveyGraph" + iex);
}
}
else if ("saveSurveyGroupRefactor".equals(action)) {
SurveyGroupDAO sgDao = new SurveyGroupDAO();
createSurveyGroupGraph(resp);
try {
List<SurveyGroup> savedSurveyGroups = sgDao.list("all");
for (SurveyGroup sgItem : savedSurveyGroups) {
resp.getWriter().println("SG: " + sgItem.getCode());
for (Survey survey : sgItem.getSurveyList()) {
resp.getWriter().println(
" Survey:" + survey.getName());
for (Map.Entry<Integer, QuestionGroup> entry : survey
.getQuestionGroupMap().entrySet()) {
resp.getWriter().println(
" QuestionGroup: " + entry.getKey()
+ ":" + entry.getValue().getDesc());
for (Map.Entry<Integer, Question> questionEntry : entry
.getValue().getQuestionMap().entrySet()) {
resp.getWriter().println(
" Question"
+ questionEntry.getKey()
+ ":"
+ questionEntry.getValue()
.getText());
for (Map.Entry<Integer, QuestionHelpMedia> qhmEntry : questionEntry
.getValue().getQuestionHelpMediaMap()
.entrySet()) {
resp.getWriter().println(
" QuestionHelpMedia"
+ qhmEntry.getKey()
+ ":"
+ qhmEntry.getValue()
.getText());
/*
* for (Key tKey : qhmEntry.getValue()
* .getAltTextKeyList()) { Translation t =
* tDao.getByKey(tKey);
* resp.getWriter().println(
* " QHMAltText" +
* t.getLanguageCode() + ":" + t.getText());
* }
*/
}
}
}
}
}
} catch (IOException e) {
log.log(Level.SEVERE, "Could not save sg");
}
} else if ("createAP".equals(action)) {
AccessPoint ap = new AccessPoint();
ap.setCollectionDate(new Date());
ap.setCommunityCode(new Random().toString());
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setCountryCode("SZ");
ap.setPointType(AccessPointType.WATER_POINT);
AccessPointHelper helper = new AccessPointHelper();
helper.saveAccessPoint(ap);
} else if ("createInstance".equals(action)) {
SurveyInstance si = new SurveyInstance();
si.setCollectionDate(new Date());
ArrayList<QuestionAnswerStore> store = new ArrayList<QuestionAnswerStore>();
QuestionAnswerStore ans = new QuestionAnswerStore();
ans.setQuestionID("2166031");
ans.setValue("12.379456758498787|-85.53869247436275|548.0|1kvc9dqy");
ans.setType("GEO");
ans.setSurveyId(1360012L);
store.add(ans);
si.setQuestionAnswersStore(store);
si.setUuid("12345");
SurveyInstanceDAO dao = new SurveyInstanceDAO();
si = dao.save(si);
ans.setSurveyInstanceId(si.getKey().getId());
dao.save(ans);
// Queue summQueue = QueueFactory.getQueue("dataSummarization");
// summQueue.add(TaskOptions.Builder
// .withUrl("/app_worker/datasummarization")
// .param("objectKey", si.getKey().getId() + "")
// .param("type", "SurveyInstance"));
} else if ("createCommunity".equals(action)) {
CommunityDao dao = new CommunityDao();
Country c = new Country();
c.setIsoAlpha2Code("CA");
c.setName("Canada");
c.setDisplayName("Canada");
Community comm = new Community();
comm.setCommunityCode("ON");
dao.save(c);
comm.setCountryCode("CA");
comm.setLat(54.99);
comm.setLon(-74.72);
dao.save(comm);
c = new Country();
c.setIsoAlpha2Code("US");
c.setName("United States");
c.setDisplayName("Unites States");
comm = new Community();
comm.setCommunityCode("Omaha");
comm.setCountryCode("US");
comm.setLat(34.99);
comm.setLon(-74.72);
dao.save(c);
dao.save(comm);
} else if ("addPhone".equals(action)) {
String phoneNumber = req.getParameter("phoneNumber");
Device d = new Device();
d.setPhoneNumber(phoneNumber);
d.setDeviceType(DeviceType.CELL_PHONE_ANDROID);
if (req.getParameter("esn") != null)
d.setEsn(req.getParameter("esn"));
if (req.getParameter("gallatinSoftwareManifest") != null)
d.setGallatinSoftwareManifest(req
.getParameter("gallatinSoftwareManifest"));
d.setInServiceDate(new Date());
DeviceDAO deviceDao = new DeviceDAO();
deviceDao.save(d);
try {
resp.getWriter().println("finished adding " + phoneNumber);
} catch (Exception e) {
e.printStackTrace();
}
} else if ("createAPSummary".equals(action)) {
AccessPointStatusSummary sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2000");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
AccessPointStatusSummaryDao dao = new AccessPointStatusSummaryDao();
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2001");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2003");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2004");
sum.setStatus(AccessPoint.Status.FUNCTIONING_OK);
dao.save(sum);
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2000");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2001");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2003");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2004");
sum.setStatus(AccessPoint.Status.FUNCTIONING_OK);
dao.save(sum);
} else if ("createApHistory".equals(action)) {
GregorianCalendar cal = new GregorianCalendar();
AccessPointHelper apHelper = new AccessPointHelper();
AccessPoint ap = new AccessPoint();
cal.set(Calendar.YEAR, 2000);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(300l);
ap.setCostPer(43.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2001);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(317l);
ap.setCostPer(40.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2002);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(340l);
ap.setCostPer(37.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2003);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(340l);
ap.setCostPer(34.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2004);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(338l);
ap.setCostPer(38.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2000);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(170l);
ap.setCostPer(19.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2001);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(201l);
ap.setCostPer(19.00);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2002);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(211l);
ap.setCostPer(17.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2003);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(220l);
ap.setCostPer(25.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2004);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(175l);
ap.setCostPer(24.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
} else if ("generateGeocells".equals(action)) {
AccessPointDao apDao = new AccessPointDao();
List<AccessPoint> apList = apDao.list(null);
if (apList != null) {
for (AccessPoint ap : apList) {
if (ap.getGeocells() == null
|| ap.getGeocells().size() == 0) {
if (ap.getLatitude() != null
&& ap.getLongitude() != null) {
ap.setGeocells(GeocellManager.generateGeoCell(new Point(
ap.getLatitude(), ap.getLongitude())));
apDao.save(ap);
}
}
}
}
} else if ("loadExistingSurvey".equals(action)) {
SurveyGroup sg = new SurveyGroup();
sg.setKey(KeyFactory.createKey(SurveyGroup.class.getSimpleName(),
2L));
sg.setName("test" + new Date());
sg.setCode("test" + new Date());
SurveyGroupDAO sgDao = new SurveyGroupDAO();
sgDao.save(sg);
Survey s = new Survey();
s.setKey(KeyFactory.createKey(Survey.class.getSimpleName(), 2L));
s.setName("test" + new Date());
s.setSurveyGroupId(sg.getKey().getId());
SurveyDAO surveyDao = new SurveyDAO();
surveyDao.save(s);
} else if ("saveAPMapping".equals(action)) {
SurveyAttributeMapping mapping = new SurveyAttributeMapping();
mapping.setAttributeName("status");
mapping.setObjectName(AccessPoint.class.getCanonicalName());
mapping.setSurveyId(1L);
mapping.setSurveyQuestionId("q1");
SurveyAttributeMappingDao samDao = new SurveyAttributeMappingDao();
samDao.save(mapping);
} else if ("listAPMapping".equals(action)) {
SurveyAttributeMappingDao samDao = new SurveyAttributeMappingDao();
List<SurveyAttributeMapping> mappings = samDao
.listMappingsBySurvey(1L);
if (mappings != null) {
System.out.println(mappings.size());
}
} else if ("saveSurveyGroup".equals(action)) {
try {
SurveyGroupDAO sgDao = new SurveyGroupDAO();
List<SurveyGroup> sgList = sgDao.list("all");
for (SurveyGroup sg : sgList) {
sgDao.delete(sg);
}
resp.getWriter().println("Deleted all survey groups");
SurveyDAO surveyDao = new SurveyDAO();
List<Survey> surveyList = surveyDao.list("all");
for (Survey survey : surveyList) {
try {
surveyDao.delete(survey);
} catch (IllegalDeletionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
resp.getWriter().println("Deleted all surveys");
resp.getWriter().println("Deleted all surveysurveygroupassocs");
QuestionGroupDao qgDao = new QuestionGroupDao();
List<QuestionGroup> qgList = qgDao.list("all");
for (QuestionGroup qg : qgList) {
qgDao.delete(qg);
}
resp.getWriter().println("Deleted all question groups");
QuestionDao qDao = new QuestionDao();
List<Question> qList = qDao.list("all");
for (Question q : qList) {
try {
qDao.delete(q);
} catch (IllegalDeletionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
resp.getWriter().println("Deleted all Questions");
QuestionOptionDao qoDao = new QuestionOptionDao();
List<QuestionOption> qoList = qoDao.list("all");
for (QuestionOption qo : qoList)
qoDao.delete(qo);
resp.getWriter().println("Deleted all QuestionOptions");
resp.getWriter().println("Deleted all questions");
resp.getWriter().println(
"Finished deleting and reloading SurveyGroup graph");
} catch (IOException e) {
e.printStackTrace();
}
} else if ("testPublishSurvey".equals(action)) {
try {
SurveyGroupDto sgDto = new SurveyServiceImpl()
.listSurveyGroups(null, true, false, false)
.getPayload().get(0);
resp.getWriter().println(
"Got Survey Group: " + sgDto.getCode() + " Survey: "
+ sgDto.getSurveyList().get(0).getKeyId());
SurveyContainerDao scDao = new SurveyContainerDao();
SurveyContainer sc = scDao.findBySurveyId(sgDto.getSurveyList()
.get(0).getKeyId());
if (sc != null) {
scDao.delete(sc);
resp.getWriter().println(
"Deleted existing SurveyContainer for: "
+ sgDto.getSurveyList().get(0).getKeyId());
}
resp.getWriter().println(
"Result of publishing survey: "
+ new SurveyServiceImpl().publishSurvey(sgDto
.getSurveyList().get(0).getKeyId()));
sc = scDao.findBySurveyId(sgDto.getSurveyList().get(0)
.getKeyId());
resp.getWriter().println(
"Survey Document result from publish: \n\n\n\n"
+ sc.getSurveyDocument().getValue());
} catch (IOException ex) {
ex.printStackTrace();
}
} else if ("createTestSurveyForEndToEnd".equals(action)) {
createTestSurveyForEndToEnd();
} else if ("deleteSurveyFragments".equals(action)) {
deleteAll(SurveyXMLFragment.class);
} else if ("migratePIToSchool".equals(action)) {
try {
resp.getWriter().println(
"Has more? "
+ migratePointType(
AccessPointType.PUBLIC_INSTITUTION,
AccessPointType.SCHOOL));
} catch (IOException e) {
e.printStackTrace();
}
} else if ("createDevice".equals(action)) {
DeviceDAO devDao = new DeviceDAO();
Device device = new Device();
device.setPhoneNumber("9175667663");
device.setDeviceType(DeviceType.CELL_PHONE_ANDROID);
devDao.save(device);
} else if ("reprocessSurveys".equals(action)) {
try {
reprocessSurveys(req.getParameter("date"));
} catch (ParseException e) {
try {
resp.getWriter().println("Couldn't reprocess: " + e);
} catch (IOException e1) {
e1.printStackTrace();
}
}
} else if ("importallsurveys".equals(action)) {
// Only run in dev hence hardcoding
SurveyReplicationImporter sri = new SurveyReplicationImporter();
sri.executeImport("http://watermapmonitordev.appspot.com", null);
// sri.executeImport("http://localhost:8888",
// "http://localhost:8888");
} else if ("importsinglesurvey".equals(action)) {
TaskOptions options = TaskOptions.Builder
.withUrl("/app_worker/dataprocessor")
.param(DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.IMPORT_REMOTE_SURVEY_ACTION)
.param(DataProcessorRequest.SOURCE_PARAM,
req.getParameter("source"))
.param(DataProcessorRequest.SURVEY_ID_PARAM,
req.getParameter("surveyId"));
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
} else if ("rescoreap".equals(action)) {
TaskOptions options = TaskOptions.Builder
.withUrl("/app_worker/dataprocessor")
.param(DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.RESCORE_AP_ACTION)
.param(DataProcessorRequest.COUNTRY_PARAM,
req.getParameter("country"));
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
} else if ("deleteSurveyResponses".equals(action)) {
if (req.getParameter("surveyId") == null) {
try {
resp.getWriter()
.println("surveyId is a required parameter");
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
deleteSurveyResponses(
Integer.parseInt(req.getParameter("surveyId")),
Integer.parseInt(req.getParameter("count")));
}
} else if ("fixNameQuestion".equals(action)) {
if (req.getParameter("questionId") == null) {
try {
resp.getWriter().println(
"questionId is a required parameter");
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
fixNameQuestion(req.getParameter("questionId"));
}
} else if ("createSurveyAssignment".equals(action)) {
Device device = new Device();
device.setDeviceType(DeviceType.CELL_PHONE_ANDROID);
device.setPhoneNumber("1111111111");
device.setInServiceDate(new Date());
BaseDAO<Device> deviceDao = new BaseDAO<Device>(Device.class);
deviceDao.save(device);
SurveyAssignmentServiceImpl sasi = new SurveyAssignmentServiceImpl();
SurveyAssignmentDto dto = new SurveyAssignmentDto();
SurveyDAO surveyDao = new SurveyDAO();
List<Survey> surveyList = surveyDao.list("all");
SurveyAssignment sa = new SurveyAssignment();
BaseDAO<SurveyAssignment> surveyAssignmentDao = new BaseDAO<SurveyAssignment>(
SurveyAssignment.class);
sa.setCreatedDateTime(new Date());
sa.setCreateUserId(-1L);
ArrayList<Long> deviceList = new ArrayList<Long>();
deviceList.add(device.getKey().getId());
sa.setDeviceIds(deviceList);
ArrayList<SurveyDto> surveyDtoList = new ArrayList<SurveyDto>();
for (Survey survey : surveyList) {
sa.addSurvey(survey.getKey().getId());
SurveyDto surveyDto = new SurveyDto();
surveyDto.setKeyId(survey.getKey().getId());
surveyDtoList.add(surveyDto);
}
sa.setStartDate(new Date());
sa.setEndDate(new Date());
sa.setName(new Date().toString());
DeviceDto deviceDto = new DeviceDto();
deviceDto.setKeyId(device.getKey().getId());
deviceDto.setPhoneNumber(device.getPhoneNumber());
ArrayList<DeviceDto> deviceDtoList = new ArrayList<DeviceDto>();
deviceDtoList.add(deviceDto);
dto.setDevices(deviceDtoList);
dto.setSurveys(surveyDtoList);
dto.setEndDate(new Date());
dto.setLanguage("en");
dto.setName("Test Assignment: " + new Date().toString());
dto.setStartDate(new Date());
sasi.saveSurveyAssignment(dto);
// sasi.deleteSurveyAssignment(dto);
} else if ("populateAssignmentId".equalsIgnoreCase(action)) {
populateAssignmentId(Long.parseLong(req
.getParameter("assignmentId")));
} else if ("testDSJQDelete".equals(action)) {
DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO();
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -10);
Date then = cal.getTime();
DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue();
dsjq.setDevicePhoneNumber("2019561591");
dsjq.setEffectiveEndDate(then);
Random rand = new Random();
dsjq.setAssignmentId(rand.nextLong());
dsjDAO.save(dsjq);
DeviceSurveyJobQueue dsjq2 = new DeviceSurveyJobQueue();
dsjq2.setDevicePhoneNumber("2019561591");
cal.add(Calendar.DAY_OF_MONTH, 20);
dsjq2.setEffectiveEndDate(cal.getTime());
dsjq2.setAssignmentId(rand.nextLong());
dsjDAO.save(dsjq2);
DeviceSurveyJobQueueDAO dsjqDao = new DeviceSurveyJobQueueDAO();
List<DeviceSurveyJobQueue> dsjqList = dsjqDao
.listAssignmentsWithEarlierExpirationDate(new Date());
for (DeviceSurveyJobQueue item : dsjqList) {
SurveyTaskUtil.spawnDeleteTask("deleteDeviceSurveyJobQueue",
item.getAssignmentId());
}
} else if ("loadDSJ".equals(action)) {
SurveyDAO surveyDao = new SurveyDAO();
List<Survey> surveyList = surveyDao.list("all");
for (Survey item : surveyList) {
DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO();
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -10);
Date then = cal.getTime();
DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue();
dsjq.setDevicePhoneNumber("2019561591");
dsjq.setEffectiveEndDate(then);
Random rand = new Random();
dsjq.setAssignmentId(rand.nextLong());
dsjq.setSurveyID(item.getKey().getId());
dsjDAO.save(dsjq);
}
for (int i = 0; i < 20; i++) {
DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO();
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -10);
Date then = cal.getTime();
DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue();
dsjq.setDevicePhoneNumber("2019561591");
dsjq.setEffectiveEndDate(then);
Random rand = new Random();
dsjq.setAssignmentId(rand.nextLong());
dsjq.setSurveyID(rand.nextLong());
dsjDAO.save(dsjq);
}
try {
resp.getWriter().println("finished");
} catch (IOException e1) {
e1.printStackTrace();
}
} else if ("deleteUnusedDSJQueue".equals(action)) {
try {
SurveyDAO surveyDao = new SurveyDAO();
List<Key> surveyIdList = surveyDao.listSurveyIds();
List<Long> ids = new ArrayList<Long>();
for (Key key : surveyIdList)
ids.add(key.getId());
DeviceSurveyJobQueueDAO dsjqDao = new DeviceSurveyJobQueueDAO();
List<DeviceSurveyJobQueue> deleteList = new ArrayList<DeviceSurveyJobQueue>();
for (DeviceSurveyJobQueue item : dsjqDao.listAllJobsInQueue()) {
Long dsjqSurveyId = item.getSurveyID();
Boolean found = ids.contains(dsjqSurveyId);
if (!found) {
deleteList.add(item);
resp.getWriter().println(
"Marking " + item.getId() + " survey: "
+ item.getSurveyID() + " for deletion");
}
}
dsjqDao.delete(deleteList);
resp.getWriter().println("finished");
} catch (IOException e1) {
e1.printStackTrace();
}
} else if ("testListTrace".equals(action)) {
listStacktrace();
} else if ("createEditorialContent".equals(action)) {
createEditorialContent(req.getParameter("pageName"));
} else if ("generateEditorialContent".equals(action)) {
try {
resp.getWriter().print(
generateEditorialContent(req.getParameter("pageName")));
} catch (IOException e) {
e.printStackTrace();
}
} else if ("populateperms".equals(action)) {
populatePermissions();
} else if ("testnotif".equals(action)) {
sendNotification(req.getParameter("surveyId"));
} else if ("popsurvey".equals(action)) {
SurveyDAO sDao = new SurveyDAO();
List<Survey> sList = sDao.list(null);
QuestionDao questionDao = new QuestionDao();
List<Question> qList = questionDao.listQuestionByType(sList.get(0)
.getKey().getId(), Question.Type.FREE_TEXT);
SurveyInstanceDAO instDao = new SurveyInstanceDAO();
for (int i = 0; i < 10; i++) {
SurveyInstance instance = new SurveyInstance();
instance.setSurveyId(sList.get(0).getKey().getId());
instance = instDao.save(instance);
for (int j = 0; j < qList.size(); j++) {
QuestionAnswerStore ans = new QuestionAnswerStore();
ans.setQuestionID(qList.get(j).getKey().getId() + "");
ans.setValue("" + j * i);
ans.setSurveyInstanceId(instance.getKey().getId());
// ans.setSurveyInstance(instance);
instDao.save(ans);
}
}
try {
resp.getWriter().print(sList.get(0).getKey().getId());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("testnotifhelper".equals(action)) {
NotificationHelper helper = new NotificationHelper("rawDataReport",
null);
helper.execute();
} else if ("testremotemap".equals(action)) {
createDevice("12345", 40.78, -73.95);
createDevice("777", 43.0, -78.8);
RemoteStacktrace st = new RemoteStacktrace();
st.setAcknowleged(false);
st.setPhoneNumber("12345");
st.setErrorDate(new Date());
st.setStackTrace(new Text("blah"));
RemoteStacktraceDao dao = new RemoteStacktraceDao();
dao.save(st);
st = new RemoteStacktrace();
st.setAcknowleged(false);
st.setErrorDate(new Date());
st.setPhoneNumber("777");
st.setStackTrace(new Text("ugh"));
dao.save(st);
} else if ("createMetricMapping".equals(action)) {
createMetricMapping(req.getParameter("metric"));
} else if ("listMetricSummaries".equals(action)) {
try {
resp.getWriter().print(
listMetricSummaries(
new Integer(req.getParameter("level")),
req.getParameter("name")));
} catch (IOException e) {
e.printStackTrace();
}
} else if ("deleteMetricSummaries".equals(action)) {
deleteMetricSummaries(new Integer(req.getParameter("level")),
req.getParameter("name"));
} else if ("createSurveyQuestionSummary".equals(action)) {
SurveyQuestionSummary sum = new SurveyQuestionSummary();
sum.setCount(10L);
sum.setResponse("TEST");
sum.setQuestionId("2166031");
SurveyQuestionSummaryDao dao = new SurveyQuestionSummaryDao();
dao.save(sum);
sum = new SurveyQuestionSummary();
sum.setCount(20L);
sum.setResponse("OTHER");
sum.setQuestionId("2166031");
dao.save(sum);
sum = new SurveyQuestionSummary();
sum.setCount(30L);
sum.setResponse("GWAR");
sum.setQuestionId("2166031");
dao.save(sum);
} else if ("createCountry".equals(action)) {
Country country = new Country();
country.setIsoAlpha2Code("LR");
country.setName("Liberia");
CountryDao dao = new CountryDao();
dao.save(country);
} else if ("populateSubCountry".equals(action)) {
try {
String country = req.getParameter("country");
if (country != null) {
Queue summQueue = QueueFactory
.getQueue("dataSummarization");
summQueue.add(TaskOptions.Builder
.withUrl("/app_worker/datasummarization")
.param("objectKey", country)
.param("type", "OGRFeature"));
} else {
resp.getWriter()
.println("country is a mandatory parameter");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("listSubCountry".equals(action)) {
try {
String country = req.getParameter("country");
if (country != null) {
SubCountryDao subDao = new SubCountryDao();
List<SubCountry> results = subDao.list(null);
if (results != null) {
for (SubCountry c : results) {
resp.getWriter().println(c.toString());
}
}
} else {
resp.getWriter()
.println("country is a mandatory parameter");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("clearcache".equals(action)) {
CacheFactory cacheFactory;
try {
cacheFactory = CacheManager.getInstance().getCacheFactory();
Cache cache = cacheFactory.createCache(Collections.emptyMap());
cache.clear();
} catch (CacheException e) {
e.printStackTrace();
}
} else if ("startProjectFlagUpdate".equals(action)) {
DataProcessorRestServlet.sendProjectUpdateTask(
req.getParameter("country"), null);
} else if (DataProcessorRequest.REBUILD_QUESTION_SUMMARY_ACTION
.equals(action)) {
TaskOptions options = TaskOptions.Builder.withUrl(
"/app_worker/dataprocessor").param(
DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.REBUILD_QUESTION_SUMMARY_ACTION);
if (req.getParameter("bypassBackend") == null
|| !req.getParameter("bypassBackend").equals("true")) {
// change the host so the queue invokes the backend
options = options
.header("Host",
BackendServiceFactory.getBackendService()
.getBackendAddress("dataprocessor"));
}
String surveyId = req
.getParameter(DataProcessorRequest.SURVEY_ID_PARAM);
if (surveyId != null && surveyId.trim().length() > 0) {
options.param(DataProcessorRequest.SURVEY_ID_PARAM, surveyId);
}
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
} else if ("deleteallqsum".equals(action)) {
DeleteObjectUtil dou = new DeleteObjectUtil();
dou.deleteAllObjects("SurveyQuestionSummary");
} else if ("fixNullSubmitter".equals(action)) {
TaskOptions options = TaskOptions.Builder.withUrl(
"/app_worker/dataprocessor").param(
DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.FIX_NULL_SUBMITTER_ACTION);
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
} else if ("createVals".equals(action)) {
SurveyedLocaleDao localeDao = new SurveyedLocaleDao();
List<SurveyedLocale> lList = localeDao.list(null);
if (lList != null && lList.size() > 0) {
List<SurveyalValue> valList = new ArrayList<SurveyalValue>();
for (int i = 0; i < 50; i++) {
SurveyalValue val = new SurveyalValue();
val.setSurveyedLocaleId(lList.get(0).getKey().getId());
val.setStringValue("val:" + i);
val.setQuestionText("TEXT: " + i);
val.setLocaleType(lList.get(0).getLocaleType());
val.setQuestionType("FREE_TEXT");
val.setSurveyInstanceId(lList.get(0)
.getLastSurveyalInstanceId());
valList.add(val);
}
localeDao.save(valList);
}
} else if ("fixDuplicateOtherText".equals(action)) {
TaskOptions options = TaskOptions.Builder.withUrl(
"/app_worker/dataprocessor").param(
DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.FIX_DUPLICATE_OTHER_TEXT_ACTION);
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
} else if ("fixNullGroupNames".equals(action)) {
fixNullQuestionGroupNames();
} else if ("trimOptions".equals(action)) {
TaskOptions options = TaskOptions.Builder.withUrl(
"/app_worker/dataprocessor").param(
DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.TRIM_OPTIONS);
if (req.getParameter("bypassBackend") == null
|| !req.getParameter("bypassBackend").equals("true")) {
// change the host so the queue invokes the backend
options = options
.header("Host",
BackendServiceFactory.getBackendService()
.getBackendAddress("dataprocessor"));
}
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
} else if ("testTemplateOverride".equals(action)) {
KMLGenerator gen = new KMLGenerator();
SurveyedLocale ap = new SurveyedLocale();
ap.setAmbiguous(false);
ap.setCountryCode("US");
ap.setCreatedDateTime(new Date());
ap.setCurrentStatus("OK");
ap.setIdentifier("1234");
ap.setLastSurveyedDate(new Date());
ap.setLatitude(12d);
ap.setLongitude(12d);
try {
String result = gen.bindPlacemark(ap,
"localePlacemarkExternal.vm", null);
resp.getWriter().println(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("setSuperUser".equals(action)) {
String email = req.getParameter("email");
UserDao udao = new UserDao();
User u = udao.findUserByEmail(email);
if (u != null) {
u.setSuperAdmin(true);
}
}else if("fixImages".equals(action)){
String surveyId = req.getParameter("surveyId");
String find = req.getParameter("find");
String replace = req.getParameter("replace");
if(surveyId != null && !surveyId.trim().isEmpty() && find!=null && !find.trim().isEmpty()){
fixBadImage(surveyId,find,replace);
}
}
}
|
diff --git a/src/test/java/com/wikia/webdriver/PageObjects/PageObject/WikiPage/MessageWallPageObject.java b/src/test/java/com/wikia/webdriver/PageObjects/PageObject/WikiPage/MessageWallPageObject.java
index 67e6a4d..b456e8a 100644
--- a/src/test/java/com/wikia/webdriver/PageObjects/PageObject/WikiPage/MessageWallPageObject.java
+++ b/src/test/java/com/wikia/webdriver/PageObjects/PageObject/WikiPage/MessageWallPageObject.java
@@ -1,529 +1,530 @@
package com.wikia.webdriver.PageObjects.PageObject.WikiPage;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.internal.seleniumemulation.WaitForPageToLoad;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.FindBys;
import org.openqa.selenium.support.PageFactory;
import com.wikia.webdriver.Common.Core.Global;
import com.wikia.webdriver.Common.Logging.PageObjectLogging;
import com.wikia.webdriver.PageObjects.PageObject.WikiBasePageObject;
public class MessageWallPageObject extends WikiBasePageObject{
@FindBy(css="[id*='cke_contents_WallMessage'] iframe")
private WebElement messageWallIFrame;
@FindBy(css="div.cke_wrapper.cke_ltr iframe")
private WebElement messageWallEditIFrame;
@FindBy(css="#WallMessageTitle")
private WebElement messageTitleField;
@FindBy(css="ul .msg-title textarea:nth-child(2)")
private WebElement messageTitleEditField2;
@FindBy(xpath="//ul[@class='comments']//textarea[2]")
private WebElement messageTitleEditField;
@FindBy(css="body#bodyContent")
private WebElement messageBodyField;
@FindBy(css=".wikia-button.save-edit")
private WebElement saveEditButton;
@FindBy(css="#WallMessageSubmit")
private WebElement postButton;
@FindBy(css="#WallMessagePreview")
private WebElement previewButton;
@FindBy(css=".buttonswrapper .wikia-menu-button.secondary.combined span")
private WebElement moreButton;
@FindBy(css="a.thread-history")
private WebElement historyButton;
@FindBy(css="a.edit-message")
private WebElement editMessageButton;
@FindBy(css="a.remove-message")
private WebElement removeMessageButton;
@FindBy(css="#WikiaConfirm")
private WebElement removeMessageOverLay;
@FindBy(css="#reason")
private WebElement removeMessageReason;
@FindBy(css="#WikiaConfirmOk")
private WebElement removeMessageConfirmButton;
@FindBy(css=".speech-bubble-message-removed")
private WebElement removeMessageConfirmation;
@FindBy(css=".RTEImageButton .cke_icon")
private WebElement addImageButton;
@FindBy(css="img.image.thumb")
private WebElement imageInMessageEditMode;
@FindBy(css="img.video.thumb")
private WebElement videoInMessageEditMode;
@FindBy(css=".RTEVideoButton .cke_icon")
private WebElement addVideoButton;
@FindBy(css=".cke_toolbar_formatmini span.cke_button.cke_button_link a .cke_icon")
private WebElement addLinkButton;
@FindBy(css="span.cke_button.cke_off.cke_button_bold a .cke_icon")
private WebElement boldButton;
@FindBy(css="span.cke_button.cke_off.cke_button_itallic a .cke_icon")
private WebElement italicButton;
@FindBy(css="div.msg-title a")
private WebElement messageTitle;
@FindBy(css="div.edited-by a")
private WebElement messageAuthor;
@FindBys(@FindBy(css="div.msg-body p"))
private List<WebElement> messageBody;
@FindBy(css="a#publish")
private WebElement publishButton;
@FindBy(css="input.cke_dialog_ui_input_text")
private WebElement targetPageOrURL;
@FindBy(css="p.link-type-note span")
private WebElement linkPageStatus;
@FindBy(css="span.cke_dialog_ui_button")
private WebElement linkModalOkButton;
@FindBy(css="input[value='ext']")
private WebElement externalLinkOption;
@FindBy(css="a.cke_button_ModeSource .cke_icon")
private WebElement sourceModeButton;
@FindBy(css="textarea.cke_source")
private WebElement sourceModeTextarea;
@FindBy(css=".SortingSelected")
private WebElement sortingMenu;
By messageList = By.cssSelector("div.msg-body");
By sortingList = By.cssSelector("ul.SortingList li a");
String moreButtonCss = "div.msg-toolbar nav.wikia-menu-button.secondary.combined";
String removeMessageConfirmButtonCSS = "#WikiaConfirmOk";
// By messageTitle = By.cssSelector(".msg-title");
public MessageWallPageObject(WebDriver driver, String Domain) {
super(driver, Domain);
PageFactory.initElements(driver, this);
}
public MessageWallPageObject openMessageWall(String userName)
{
getUrl(Global.DOMAIN+"wiki/Message_Wall:"+userName);
waitForElementByXPath("//h1[@itemprop='name' and contains(text(), '"+userName+"')]");
PageObjectLogging.log("openMessageWall", "message wall for user "+userName+" was opened", true, driver);
return new MessageWallPageObject(driver, userName);
}
private void triggerMessageArea()
{
jQueryFocus("#WallMessageBody");
waitForElementByElement(messageWallIFrame);
PageObjectLogging.log("triggerMessageArea", "message area is triggered", true, driver);
}
public void writeMessage(String title, String message)
{
clickAndWait(messageTitleField);
messageTitleField.sendKeys(title);
triggerMessageArea();
waitForElementByElement(messageWallIFrame);
messageTitleField.sendKeys(Keys.TAB);
driver.switchTo().frame(messageWallIFrame);
waitForElementByElement(messageBodyField);
messageBodyField.sendKeys(message);
driver.switchTo().defaultContent();
PageObjectLogging.log("writeMessage", "message is written, title: "+title+" body: "+message, true, driver);
}
public void writeBoldMessage(String title, String message) {
writeSpecialMessage(title, message, "Bold");
}
public void writeItalicMessage(String title, String message) {
writeSpecialMessage(title, message, "Italic");
}
public void writeSpecialMessage(String title, String message, String special) {
String specialKey = "Not Initialized";
if (special.equals("Bold")) {
specialKey = "b";
}
if (special.equals("Italic")) {
specialKey = "i";
}
messageTitleField.sendKeys(title);
triggerMessageArea();
waitForElementByElement(messageWallIFrame);
jQueryClick("span.cke_button.cke_off.cke_button_bold a .cke_icon");
messageTitleField.sendKeys(Keys.TAB);
driver.switchTo().frame(messageWallIFrame);
waitForElementByElement(messageBodyField);
messageBodyField.sendKeys(message);
messageBodyField.sendKeys(Keys.LEFT_CONTROL + "a" );
messageBodyField.sendKeys(Keys.LEFT_CONTROL + specialKey );
driver.switchTo().defaultContent();
PageObjectLogging.log("write"+special+"Message", special + " message is written, title: "+title+" body: "+message, true, driver);
}
public void writeMessageNoTitle(String message)
{
clickAndWait(messageTitleField);
triggerMessageArea();
waitForElementByElement(messageWallIFrame);
messageTitleField.sendKeys(Keys.TAB);
driver.switchTo().frame(messageWallIFrame);
messageBodyField.sendKeys(message);
driver.switchTo().defaultContent();
PageObjectLogging.log("writeMessage", "message is written, body: "+message, true, driver);
}
private void verifyImageInMessageEditMode()
{
waitForElementByElement(messageWallIFrame);
driver.switchTo().frame(messageWallIFrame);
waitForElementByElement(imageInMessageEditMode);
driver.switchTo().defaultContent();
}
private void verifyVideoInMessageEditMode()
{
waitForElementByElement(messageWallIFrame);
driver.switchTo().frame(messageWallIFrame);
waitForElementByElement(videoInMessageEditMode);
driver.switchTo().defaultContent();
}
public void writeMessageImage(String title)
{
clickAndWait(messageTitleField);
messageTitleField.sendKeys(title);
triggerMessageArea();
waitForElementByElement(addImageButton);
clickAndWait(addImageButton);
waitForModalAndClickAddThisPhoto();
clickOnAddPhotoButton2();
verifyImageInMessageEditMode();
PageObjectLogging.log("writeMessageImage", "message is written, with image "+title, true, driver);
}
public void writeMessageVideo(String title, String url)
{
clickAndWait(messageTitleField);
messageTitleField.sendKeys(title);
triggerMessageArea();
waitForElementByElement(addVideoButton);
clickAndWait(addVideoButton);
waitForVideoModalAndTypeVideoURL(url);
clickVideoNextButton();
waitForVideoDialog();
clickAddAvideo();
waitForSuccesDialogAndReturnToEditing();
verifyVideoInMessageEditMode();
PageObjectLogging.log("writeMessageVideo", "message is written, with video "+title, true, driver);
}
public void writeMessageLink(String title, String url)
{
clickAndWait(messageTitleField);
messageTitleField.sendKeys(title);
triggerMessageArea();
waitForElementByElement(addLinkButton);
clickAndWait(addLinkButton);
waitForVideoModalAndTypeVideoURL(url);
clickVideoNextButton();
waitForVideoDialog();
clickAddAvideo();
waitForSuccesDialogAndReturnToEditing();
verifyVideoInMessageEditMode();
PageObjectLogging.log("writeMessageVideo", "message is written, with video "+title, true, driver);
}
public void clickPostButton()
{
executeScript("WikiaEditor.getInstance('WallMessageBody').getEditbox().trigger('keyup')");
waitForElementByElement(postButton);
jQueryClick("#WallMessageSubmit");
PageObjectLogging.log("clickPostButton", "post button is clicked", true, driver);
}
public void clickPreviewButton() {
executeScript("WikiaEditor.getInstance('WallMessageBody').getEditbox().trigger('keyup')");
waitForElementByElement(previewButton);
clickAndWait(previewButton);
PageObjectLogging.log("clickPreviewButton", "preview button is clicked", true, driver);
}
public void clickPostNotitleButton()
{
waitForElementByElement(postButton);
jQueryClick("#WallMessageSubmit");
waitForElementByXPath("//button[@id='WallMessageSubmit' and contains(text(), 'Post without a title')]");
waitForElementByXPath("//div[@class='no-title-warning' and contains(text(), 'You did not specify any title')]");
jQueryClick("#WallMessageSubmit");
PageObjectLogging.log("clickPostButton", "post button is clicked", true, driver);
}
public void verifyPostedMessageWithTitle(String title, String message)
{
waitForTextToBePresentInElementByElement(messageTitle, title);
waitForTextToBePresentInElementByElement(messageBody.get(0), message);
// waitForElementByXPath("//div[@class='msg-title']/a[contains(text(), '"+title+"')]");
// waitForElementByXPath("//div[@class='msg-body']/p[contains(text(), '"+message+"')]");
PageObjectLogging.log("verifyPostedMessageWithTitle", "message with title verified", true, driver);
}
public void verifyPostedBoldMessageWithTitle(String title, String message) {
waitForTextToBePresentInElementByElement(messageTitle, title);
waitForTextToBePresentInElementByElement(messageBody.get(0), message);
PageObjectLogging.log("verifyPostedBoldMessageWithTitle", "bold message with title verified", true, driver);
}
public void verifyPostedItalicMessageWithTitle(String title, String message) {
waitForTextToBePresentInElementByElement(messageTitle, title);
waitForTextToBePresentInElementByElement(messageBody.get(0), message);
PageObjectLogging.log("verifyPostedItalicMessageWithTitle", "italic message with title verified", true, driver);
}
public void verifyPostedMessageWithLinks(String internallink, String externallink){//, String articleName) {
// List<WebElement> links = messageBody.findElements(By.cssSelector("a"));
// waitForTextToBePresentInElementByElement(links.get(0), internallink);
// waitForTextToBePresentInElementByElement(links.get(1), externallink);
// List<WebElement> links = messageBody.findElements(By.cssSelector("a"));
waitForTextToBePresentInElementByElement(messageBody.get(0), internallink);
waitForTextToBePresentInElementByElement(messageBody.get(1), externallink);
}
public void verifyPostedMessageWithoutTitle(String userName, String message)
{
waitForElementByXPath("//div[@class='msg-title']/a[contains(text(), 'Message from "+userName+"')]");
waitForElementByXPath("//div[@class='msg-body']/p[contains(text(), '"+message+"')]");
PageObjectLogging.log("verifyPostedMessageWithTitle", "message without title verified", true, driver);
}
public void verifyPostedMessageVideo(String title)
{
waitForElementByXPath("//div[@class='msg-title']/a[contains(text(), '"+title+"')]/../../div[@class='editarea']//a[@class='image video']");
PageObjectLogging.log("verifyPostedMessageImage", "message with image title verified", true, driver);
}
public void verifyPostedMessageImage(String title)
{
waitForElementByXPath("//div[@class='msg-title']/a[contains(text(), '"+title+"')]/../../div[@class='editarea']//img[@class='thumbimage']");
PageObjectLogging.log("verifyPostedMessageImage", "message with image title verified", true, driver);
}
public void removeMessage(String reason)
{
waitForElementByCss("div.msg-toolbar");
executeScript("document.getElementsByClassName(\"buttons\")[1].style.display = \"block\"");
waitForElementByElement(moreButton);
mouseOver(moreButtonCss);
executeScript("document.querySelectorAll(\"div.msg-toolbar nav.wikia-menu-button.secondary.combined\")[0].click()");
mouseOver(".WikiaMenuElement .remove-message");
// jQueryClick(".WikiaMenuElement .remove-message");
jQueryNthElemClick(".WikiaMenuElement .remove-message", 0);
waitForElementByElement(removeMessageOverLay);
waitForElementByElement(removeMessageConfirmButton);
if (Global.BROWSER.equals("IE")) {
WebElement removeMessageReasonParent = getParentElement(removeMessageReason);
clickAndWait(removeMessageReasonParent);
removeMessageReasonParent.sendKeys(reason);
clickAndWait(removeMessageConfirmButton);
}
else {
removeMessageReason.sendKeys(reason);
clickAndWait(removeMessageConfirmButton);
}
waitForElementByElement(removeMessageConfirmation);
driver.navigate().refresh();
// waitForElementNotVisibleByBy(messageTitle);
PageObjectLogging.log("removeMessage", "message is removed", true, driver);
}
private void clickEditMessage()
{
waitForElementByCss("div.msg-toolbar");
executeScript("document.getElementsByClassName(\"buttons\")[1].style.display = \"block\"");
waitForElementByElement(moreButton);
mouseOver(moreButtonCss);
executeScript("document.querySelectorAll(\"div.msg-toolbar nav.wikia-menu-button.secondary.combined\")[0].click()");
waitForElementByElement(editMessageButton);
clickAndWait(editMessageButton);
executeScript("document.getElementsByClassName(\"buttons\")[1].style.display = \"\"");
// jQueryClick(".edit-message");
// waitForElementByElement(messageWallEditIFrame);
PageObjectLogging.log("clickEditMessage", "edit message button is clicked", true, driver);
}
public MessageWallHistoryPageObject openHistory() {
waitForElementByCss("div.msg-toolbar");
executeScript("document.getElementsByClassName(\"buttons\")[1].style.display = \"block\"");
waitForElementByElement(moreButton);
mouseOver(moreButtonCss);
executeScript("document.querySelectorAll(\"div.msg-toolbar nav.wikia-menu-button.secondary.combined\")[0].click()");
waitForElementByElement(historyButton);
clickAndWait(historyButton);
PageObjectLogging.log("openHistory", "open History page of the newest thread", true, driver);
return new MessageWallHistoryPageObject(driver, Domain);
}
private void writeEditMessage(String title, String message)
{
WebElement elem = driver.switchTo().activeElement();
messageWallIFrame = elem;
driver.switchTo().frame(messageWallIFrame);
messageBodyField.clear();
messageBodyField.sendKeys(message);
driver.switchTo().defaultContent();
waitForElementByElement(messageWallIFrame);
clickAndWait(messageTitleEditField2);
messageTitleEditField2.sendKeys(Keys.TAB);
driver.switchTo().frame(messageWallIFrame);
messageBodyField.sendKeys(message);
driver.switchTo().defaultContent();
waitForElementByElement(messageTitleEditField);
messageTitleEditField2.clear();
messageTitleEditField2.sendKeys(title);
waitForElementByElement(saveEditButton);
if (Global.BROWSER.equals("IE")) {
driver.switchTo().frame(messageWallIFrame);
clickAndWait(messageBodyField);
messageBodyField.sendKeys(Keys.TAB);
- messageBodyField.sendKeys(Keys.TAB);
+// messageBodyField.sendKeys(Keys.TAB);
+// messageBodyField.sendKeys(Keys.TAB);
messageBodyField.sendKeys(Keys.ENTER);
driver.switchTo().defaultContent();
}
else {
clickAndWait(saveEditButton);
}
PageObjectLogging.log("writeEditMessage", "message edited", true, driver);
}
public void editMessage(String title, String message)
{
refreshPage();
clickEditMessage();
writeEditMessage(title, message);
}
public void clickPublishButton() {
waitForElementByElement(publishButton);
clickAndWait(publishButton);
PageObjectLogging.log("clickPublishButton", "publish button is clicked", true, driver);
}
public void writeMessageWithLink(String internallink, String externallink, String title) {
clickAndWait(messageTitleField);
messageTitleField.sendKeys(title);
triggerMessageArea();
// add internal wikia link
waitForElementByElement(addLinkButton);
clickAndWait(addLinkButton);
waitForElementByElement(targetPageOrURL);
targetPageOrURL.sendKeys(internallink);
waitForTextToBePresentInElementByElement(linkPageStatus, "Page exists");
waitForElementByElement(linkModalOkButton);
clickAndWait(linkModalOkButton);
// add external link
driver.switchTo().frame(messageWallIFrame);
messageBodyField.sendKeys(Keys.END);
messageBodyField.sendKeys(Keys.ENTER);
driver.switchTo().defaultContent();
waitForElementByElement(addLinkButton);
clickAndWait(addLinkButton);
waitForElementByElement(externalLinkOption);
clickAndWait(externalLinkOption);
targetPageOrURL.sendKeys(externallink);
waitForTextToBePresentInElementByElement(linkPageStatus, "External link");
clickAndWait(linkModalOkButton);
PageObjectLogging.log("writeMessageWithLink", "internal and external links: "+internallink+" and" +externallink+ "added", true, driver);
}
public void writeMessageSourceMode(String title, String message) {
clickAndWait(messageTitleField);
messageTitleField.sendKeys(title);
triggerMessageArea();
waitForElementByElement(messageWallIFrame);
clickAndWait(sourceModeButton);
waitForElementByElement(sourceModeTextarea);
sourceModeTextarea.sendKeys(message);
PageObjectLogging.log("writeMessageSourceMode", "message in source mode is written, title: "+title+" body: "+message, true, driver);
}
/**
* verifies order of first two messages
*
* @author Michal Nowierski
* @param message1 - first message to be checked
* @param message2 - second message to be checked
* */
public void verifyMessagesOrderIs(String message1, String message2) {
List<WebElement> list = driver.findElements(messageList);
waitForTextToBePresentInElementByElement(list.get(0), message1);
waitForTextToBePresentInElementByElement(list.get(1), message2);
PageObjectLogging.log("verifyMessagesOrderIs", "order of messages is appropriate: "+message1+", then "+message2, true, driver);
}
/**
* sort threads (wall messages = threads) in specified order<br>
*
* @author Michal Nowierski
* @param order - specifies order of sorting <br><br> possible values: <br> "NewestThreads", "OldestThreads", "NewestReplies"}
* */
public void sortThreads(String order) {
// clickAndWait(sortingMenu);
executeScript("document.getElementsByClassName('SortingList')[0].style.display=\"block\"");
List<WebElement> list = driver.findElements(sortingList);
if (order.equals("NewestThreads")) {
waitForElementByElement(list.get(0));
clickAndWait(list.get(0));
}
if (order.equals("OldestThreads")) {
waitForElementByElement(list.get(1));
clickAndWait(list.get(1));
}
if (order.equals("NewestReplies")) {
waitForElementByElement(list.get(2));
clickAndWait(list.get(2));
}
PageObjectLogging.log("sortThreads", "order of messages sorted: "+order, true, driver);
}
}
| true | true | public void verifyPostedMessageWithLinks(String internallink, String externallink){//, String articleName) {
// List<WebElement> links = messageBody.findElements(By.cssSelector("a"));
// waitForTextToBePresentInElementByElement(links.get(0), internallink);
// waitForTextToBePresentInElementByElement(links.get(1), externallink);
// List<WebElement> links = messageBody.findElements(By.cssSelector("a"));
waitForTextToBePresentInElementByElement(messageBody.get(0), internallink);
waitForTextToBePresentInElementByElement(messageBody.get(1), externallink);
}
public void verifyPostedMessageWithoutTitle(String userName, String message)
{
waitForElementByXPath("//div[@class='msg-title']/a[contains(text(), 'Message from "+userName+"')]");
waitForElementByXPath("//div[@class='msg-body']/p[contains(text(), '"+message+"')]");
PageObjectLogging.log("verifyPostedMessageWithTitle", "message without title verified", true, driver);
}
public void verifyPostedMessageVideo(String title)
{
waitForElementByXPath("//div[@class='msg-title']/a[contains(text(), '"+title+"')]/../../div[@class='editarea']//a[@class='image video']");
PageObjectLogging.log("verifyPostedMessageImage", "message with image title verified", true, driver);
}
public void verifyPostedMessageImage(String title)
{
waitForElementByXPath("//div[@class='msg-title']/a[contains(text(), '"+title+"')]/../../div[@class='editarea']//img[@class='thumbimage']");
PageObjectLogging.log("verifyPostedMessageImage", "message with image title verified", true, driver);
}
public void removeMessage(String reason)
{
waitForElementByCss("div.msg-toolbar");
executeScript("document.getElementsByClassName(\"buttons\")[1].style.display = \"block\"");
waitForElementByElement(moreButton);
mouseOver(moreButtonCss);
executeScript("document.querySelectorAll(\"div.msg-toolbar nav.wikia-menu-button.secondary.combined\")[0].click()");
mouseOver(".WikiaMenuElement .remove-message");
// jQueryClick(".WikiaMenuElement .remove-message");
jQueryNthElemClick(".WikiaMenuElement .remove-message", 0);
waitForElementByElement(removeMessageOverLay);
waitForElementByElement(removeMessageConfirmButton);
if (Global.BROWSER.equals("IE")) {
WebElement removeMessageReasonParent = getParentElement(removeMessageReason);
clickAndWait(removeMessageReasonParent);
removeMessageReasonParent.sendKeys(reason);
clickAndWait(removeMessageConfirmButton);
}
else {
removeMessageReason.sendKeys(reason);
clickAndWait(removeMessageConfirmButton);
}
waitForElementByElement(removeMessageConfirmation);
driver.navigate().refresh();
// waitForElementNotVisibleByBy(messageTitle);
PageObjectLogging.log("removeMessage", "message is removed", true, driver);
}
private void clickEditMessage()
{
waitForElementByCss("div.msg-toolbar");
executeScript("document.getElementsByClassName(\"buttons\")[1].style.display = \"block\"");
waitForElementByElement(moreButton);
mouseOver(moreButtonCss);
executeScript("document.querySelectorAll(\"div.msg-toolbar nav.wikia-menu-button.secondary.combined\")[0].click()");
waitForElementByElement(editMessageButton);
clickAndWait(editMessageButton);
executeScript("document.getElementsByClassName(\"buttons\")[1].style.display = \"\"");
// jQueryClick(".edit-message");
// waitForElementByElement(messageWallEditIFrame);
PageObjectLogging.log("clickEditMessage", "edit message button is clicked", true, driver);
}
public MessageWallHistoryPageObject openHistory() {
waitForElementByCss("div.msg-toolbar");
executeScript("document.getElementsByClassName(\"buttons\")[1].style.display = \"block\"");
waitForElementByElement(moreButton);
mouseOver(moreButtonCss);
executeScript("document.querySelectorAll(\"div.msg-toolbar nav.wikia-menu-button.secondary.combined\")[0].click()");
waitForElementByElement(historyButton);
clickAndWait(historyButton);
PageObjectLogging.log("openHistory", "open History page of the newest thread", true, driver);
return new MessageWallHistoryPageObject(driver, Domain);
}
private void writeEditMessage(String title, String message)
{
WebElement elem = driver.switchTo().activeElement();
messageWallIFrame = elem;
driver.switchTo().frame(messageWallIFrame);
messageBodyField.clear();
messageBodyField.sendKeys(message);
driver.switchTo().defaultContent();
waitForElementByElement(messageWallIFrame);
clickAndWait(messageTitleEditField2);
messageTitleEditField2.sendKeys(Keys.TAB);
driver.switchTo().frame(messageWallIFrame);
messageBodyField.sendKeys(message);
driver.switchTo().defaultContent();
waitForElementByElement(messageTitleEditField);
messageTitleEditField2.clear();
messageTitleEditField2.sendKeys(title);
waitForElementByElement(saveEditButton);
if (Global.BROWSER.equals("IE")) {
driver.switchTo().frame(messageWallIFrame);
clickAndWait(messageBodyField);
messageBodyField.sendKeys(Keys.TAB);
messageBodyField.sendKeys(Keys.TAB);
messageBodyField.sendKeys(Keys.ENTER);
driver.switchTo().defaultContent();
}
else {
clickAndWait(saveEditButton);
}
PageObjectLogging.log("writeEditMessage", "message edited", true, driver);
}
public void editMessage(String title, String message)
{
refreshPage();
clickEditMessage();
writeEditMessage(title, message);
}
public void clickPublishButton() {
waitForElementByElement(publishButton);
clickAndWait(publishButton);
PageObjectLogging.log("clickPublishButton", "publish button is clicked", true, driver);
}
public void writeMessageWithLink(String internallink, String externallink, String title) {
clickAndWait(messageTitleField);
messageTitleField.sendKeys(title);
triggerMessageArea();
// add internal wikia link
waitForElementByElement(addLinkButton);
clickAndWait(addLinkButton);
waitForElementByElement(targetPageOrURL);
targetPageOrURL.sendKeys(internallink);
waitForTextToBePresentInElementByElement(linkPageStatus, "Page exists");
waitForElementByElement(linkModalOkButton);
clickAndWait(linkModalOkButton);
// add external link
driver.switchTo().frame(messageWallIFrame);
messageBodyField.sendKeys(Keys.END);
messageBodyField.sendKeys(Keys.ENTER);
driver.switchTo().defaultContent();
waitForElementByElement(addLinkButton);
clickAndWait(addLinkButton);
waitForElementByElement(externalLinkOption);
clickAndWait(externalLinkOption);
targetPageOrURL.sendKeys(externallink);
waitForTextToBePresentInElementByElement(linkPageStatus, "External link");
clickAndWait(linkModalOkButton);
PageObjectLogging.log("writeMessageWithLink", "internal and external links: "+internallink+" and" +externallink+ "added", true, driver);
}
public void writeMessageSourceMode(String title, String message) {
clickAndWait(messageTitleField);
messageTitleField.sendKeys(title);
triggerMessageArea();
waitForElementByElement(messageWallIFrame);
clickAndWait(sourceModeButton);
waitForElementByElement(sourceModeTextarea);
sourceModeTextarea.sendKeys(message);
PageObjectLogging.log("writeMessageSourceMode", "message in source mode is written, title: "+title+" body: "+message, true, driver);
}
/**
* verifies order of first two messages
*
* @author Michal Nowierski
* @param message1 - first message to be checked
* @param message2 - second message to be checked
* */
public void verifyMessagesOrderIs(String message1, String message2) {
List<WebElement> list = driver.findElements(messageList);
waitForTextToBePresentInElementByElement(list.get(0), message1);
waitForTextToBePresentInElementByElement(list.get(1), message2);
PageObjectLogging.log("verifyMessagesOrderIs", "order of messages is appropriate: "+message1+", then "+message2, true, driver);
}
/**
* sort threads (wall messages = threads) in specified order<br>
*
* @author Michal Nowierski
* @param order - specifies order of sorting <br><br> possible values: <br> "NewestThreads", "OldestThreads", "NewestReplies"}
* */
public void sortThreads(String order) {
// clickAndWait(sortingMenu);
executeScript("document.getElementsByClassName('SortingList')[0].style.display=\"block\"");
List<WebElement> list = driver.findElements(sortingList);
if (order.equals("NewestThreads")) {
waitForElementByElement(list.get(0));
clickAndWait(list.get(0));
}
if (order.equals("OldestThreads")) {
waitForElementByElement(list.get(1));
clickAndWait(list.get(1));
}
if (order.equals("NewestReplies")) {
waitForElementByElement(list.get(2));
clickAndWait(list.get(2));
}
PageObjectLogging.log("sortThreads", "order of messages sorted: "+order, true, driver);
}
}
| public void verifyPostedMessageWithLinks(String internallink, String externallink){//, String articleName) {
// List<WebElement> links = messageBody.findElements(By.cssSelector("a"));
// waitForTextToBePresentInElementByElement(links.get(0), internallink);
// waitForTextToBePresentInElementByElement(links.get(1), externallink);
// List<WebElement> links = messageBody.findElements(By.cssSelector("a"));
waitForTextToBePresentInElementByElement(messageBody.get(0), internallink);
waitForTextToBePresentInElementByElement(messageBody.get(1), externallink);
}
public void verifyPostedMessageWithoutTitle(String userName, String message)
{
waitForElementByXPath("//div[@class='msg-title']/a[contains(text(), 'Message from "+userName+"')]");
waitForElementByXPath("//div[@class='msg-body']/p[contains(text(), '"+message+"')]");
PageObjectLogging.log("verifyPostedMessageWithTitle", "message without title verified", true, driver);
}
public void verifyPostedMessageVideo(String title)
{
waitForElementByXPath("//div[@class='msg-title']/a[contains(text(), '"+title+"')]/../../div[@class='editarea']//a[@class='image video']");
PageObjectLogging.log("verifyPostedMessageImage", "message with image title verified", true, driver);
}
public void verifyPostedMessageImage(String title)
{
waitForElementByXPath("//div[@class='msg-title']/a[contains(text(), '"+title+"')]/../../div[@class='editarea']//img[@class='thumbimage']");
PageObjectLogging.log("verifyPostedMessageImage", "message with image title verified", true, driver);
}
public void removeMessage(String reason)
{
waitForElementByCss("div.msg-toolbar");
executeScript("document.getElementsByClassName(\"buttons\")[1].style.display = \"block\"");
waitForElementByElement(moreButton);
mouseOver(moreButtonCss);
executeScript("document.querySelectorAll(\"div.msg-toolbar nav.wikia-menu-button.secondary.combined\")[0].click()");
mouseOver(".WikiaMenuElement .remove-message");
// jQueryClick(".WikiaMenuElement .remove-message");
jQueryNthElemClick(".WikiaMenuElement .remove-message", 0);
waitForElementByElement(removeMessageOverLay);
waitForElementByElement(removeMessageConfirmButton);
if (Global.BROWSER.equals("IE")) {
WebElement removeMessageReasonParent = getParentElement(removeMessageReason);
clickAndWait(removeMessageReasonParent);
removeMessageReasonParent.sendKeys(reason);
clickAndWait(removeMessageConfirmButton);
}
else {
removeMessageReason.sendKeys(reason);
clickAndWait(removeMessageConfirmButton);
}
waitForElementByElement(removeMessageConfirmation);
driver.navigate().refresh();
// waitForElementNotVisibleByBy(messageTitle);
PageObjectLogging.log("removeMessage", "message is removed", true, driver);
}
private void clickEditMessage()
{
waitForElementByCss("div.msg-toolbar");
executeScript("document.getElementsByClassName(\"buttons\")[1].style.display = \"block\"");
waitForElementByElement(moreButton);
mouseOver(moreButtonCss);
executeScript("document.querySelectorAll(\"div.msg-toolbar nav.wikia-menu-button.secondary.combined\")[0].click()");
waitForElementByElement(editMessageButton);
clickAndWait(editMessageButton);
executeScript("document.getElementsByClassName(\"buttons\")[1].style.display = \"\"");
// jQueryClick(".edit-message");
// waitForElementByElement(messageWallEditIFrame);
PageObjectLogging.log("clickEditMessage", "edit message button is clicked", true, driver);
}
public MessageWallHistoryPageObject openHistory() {
waitForElementByCss("div.msg-toolbar");
executeScript("document.getElementsByClassName(\"buttons\")[1].style.display = \"block\"");
waitForElementByElement(moreButton);
mouseOver(moreButtonCss);
executeScript("document.querySelectorAll(\"div.msg-toolbar nav.wikia-menu-button.secondary.combined\")[0].click()");
waitForElementByElement(historyButton);
clickAndWait(historyButton);
PageObjectLogging.log("openHistory", "open History page of the newest thread", true, driver);
return new MessageWallHistoryPageObject(driver, Domain);
}
private void writeEditMessage(String title, String message)
{
WebElement elem = driver.switchTo().activeElement();
messageWallIFrame = elem;
driver.switchTo().frame(messageWallIFrame);
messageBodyField.clear();
messageBodyField.sendKeys(message);
driver.switchTo().defaultContent();
waitForElementByElement(messageWallIFrame);
clickAndWait(messageTitleEditField2);
messageTitleEditField2.sendKeys(Keys.TAB);
driver.switchTo().frame(messageWallIFrame);
messageBodyField.sendKeys(message);
driver.switchTo().defaultContent();
waitForElementByElement(messageTitleEditField);
messageTitleEditField2.clear();
messageTitleEditField2.sendKeys(title);
waitForElementByElement(saveEditButton);
if (Global.BROWSER.equals("IE")) {
driver.switchTo().frame(messageWallIFrame);
clickAndWait(messageBodyField);
messageBodyField.sendKeys(Keys.TAB);
// messageBodyField.sendKeys(Keys.TAB);
// messageBodyField.sendKeys(Keys.TAB);
messageBodyField.sendKeys(Keys.ENTER);
driver.switchTo().defaultContent();
}
else {
clickAndWait(saveEditButton);
}
PageObjectLogging.log("writeEditMessage", "message edited", true, driver);
}
public void editMessage(String title, String message)
{
refreshPage();
clickEditMessage();
writeEditMessage(title, message);
}
public void clickPublishButton() {
waitForElementByElement(publishButton);
clickAndWait(publishButton);
PageObjectLogging.log("clickPublishButton", "publish button is clicked", true, driver);
}
public void writeMessageWithLink(String internallink, String externallink, String title) {
clickAndWait(messageTitleField);
messageTitleField.sendKeys(title);
triggerMessageArea();
// add internal wikia link
waitForElementByElement(addLinkButton);
clickAndWait(addLinkButton);
waitForElementByElement(targetPageOrURL);
targetPageOrURL.sendKeys(internallink);
waitForTextToBePresentInElementByElement(linkPageStatus, "Page exists");
waitForElementByElement(linkModalOkButton);
clickAndWait(linkModalOkButton);
// add external link
driver.switchTo().frame(messageWallIFrame);
messageBodyField.sendKeys(Keys.END);
messageBodyField.sendKeys(Keys.ENTER);
driver.switchTo().defaultContent();
waitForElementByElement(addLinkButton);
clickAndWait(addLinkButton);
waitForElementByElement(externalLinkOption);
clickAndWait(externalLinkOption);
targetPageOrURL.sendKeys(externallink);
waitForTextToBePresentInElementByElement(linkPageStatus, "External link");
clickAndWait(linkModalOkButton);
PageObjectLogging.log("writeMessageWithLink", "internal and external links: "+internallink+" and" +externallink+ "added", true, driver);
}
public void writeMessageSourceMode(String title, String message) {
clickAndWait(messageTitleField);
messageTitleField.sendKeys(title);
triggerMessageArea();
waitForElementByElement(messageWallIFrame);
clickAndWait(sourceModeButton);
waitForElementByElement(sourceModeTextarea);
sourceModeTextarea.sendKeys(message);
PageObjectLogging.log("writeMessageSourceMode", "message in source mode is written, title: "+title+" body: "+message, true, driver);
}
/**
* verifies order of first two messages
*
* @author Michal Nowierski
* @param message1 - first message to be checked
* @param message2 - second message to be checked
* */
public void verifyMessagesOrderIs(String message1, String message2) {
List<WebElement> list = driver.findElements(messageList);
waitForTextToBePresentInElementByElement(list.get(0), message1);
waitForTextToBePresentInElementByElement(list.get(1), message2);
PageObjectLogging.log("verifyMessagesOrderIs", "order of messages is appropriate: "+message1+", then "+message2, true, driver);
}
/**
* sort threads (wall messages = threads) in specified order<br>
*
* @author Michal Nowierski
* @param order - specifies order of sorting <br><br> possible values: <br> "NewestThreads", "OldestThreads", "NewestReplies"}
* */
public void sortThreads(String order) {
// clickAndWait(sortingMenu);
executeScript("document.getElementsByClassName('SortingList')[0].style.display=\"block\"");
List<WebElement> list = driver.findElements(sortingList);
if (order.equals("NewestThreads")) {
waitForElementByElement(list.get(0));
clickAndWait(list.get(0));
}
if (order.equals("OldestThreads")) {
waitForElementByElement(list.get(1));
clickAndWait(list.get(1));
}
if (order.equals("NewestReplies")) {
waitForElementByElement(list.get(2));
clickAndWait(list.get(2));
}
PageObjectLogging.log("sortThreads", "order of messages sorted: "+order, true, driver);
}
}
|
diff --git a/src/main/java/edu/bu/AtroposStateReader.java b/src/main/java/edu/bu/AtroposStateReader.java
index 86be144..861cca7 100644
--- a/src/main/java/edu/bu/AtroposStateReader.java
+++ b/src/main/java/edu/bu/AtroposStateReader.java
@@ -1,449 +1,449 @@
package edu.bu;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
/**
* Reads in an {@link AtroposState} from an {@link InputStream}.
*
* @author dml
*
*/
public class AtroposStateReader {
private final Reader input;
/**
* @param input
* - the {@link Reader} this {@link AtroposStateReader} will
* read from.
*/
public AtroposStateReader(Reader input) {
this.input = input;
}
public AtroposState read() throws IOException {
StringBuilder result = new StringBuilder();
while (true) {
int read = input.read();
if (read < 0) {
break;
}
result.append((char) read);
}
Pair<List<List<Integer>>, List<Integer>> state = seq(rows, lastPlay).parse(result.toString()).token;
int size = state.first.size();
AtroposCircle[][] board = new AtroposCircle[size][size];
for (int i = 0; i < size - 1; ++i) {
List<Integer> row = state.first.get(i);
for (int j = 0; j < size; ++j) {
int height = size - i - 1;
board[height][j] = new AtroposCircle(j < row.size() ? row.get(j) : Colors.Uncolored.getValue(), size - i - 1, j, size - height - j);
}
}
// unroll last iteration
List<Integer> row = state.first.get(size - 1);
- board[0][0] = new AtroposCircle(Colors.Uncolored.getValue(), 0, 0, size - 1);
- for (int j = 1; j < size; ++j) {
- board[0][j] = new AtroposCircle(j < row.size() ? row.get(j)
- : Colors.Uncolored.getValue(), 0, j, size - 1 - j);
+ board[0][0] = new AtroposCircle(Colors.Uncolored.getValue(), 0, 0, size);
+ for (int j = 0; j < row.size(); ++j) {
+ board[0][j + 1] = new AtroposCircle(j < row.size() ? row.get(j)
+ : Colors.Uncolored.getValue(), 0, j + 1, size - 1 - j);
}
return new AtroposState(board, new AtroposCircle(state.second.get(0),
state.second.get(1), state.second.get(2), state.second.get(3)));
}
private static class ParseResult<T> {
public final T token;
public final String rest;
public ParseResult(T token, String rest) {
this.token = token;
this.rest = rest;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "<<" + token + ", \"" + rest + "\">>";
}
}
public static class ParseException extends RuntimeException {
private static final long serialVersionUID = -5822709037165835325L;
public ParseException() {
super();
}
public ParseException(String message, Throwable cause) {
super(message, cause);
}
public ParseException(String message) {
super(message);
}
public ParseException(Throwable cause) {
super(cause);
}
}
public static interface Parser<T> {
ParseResult<T> parse(String toParse);
boolean isValid(String toParse);
}
public static final class Unit {
public static Unit unit = new Unit();
private Unit() {};
}
public static class Pair<A, B> {
public final A first;
public final B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
}
public static Parser<String> token(String token) {
return new Token(token);
}
public static class Token implements Parser<String> {
private final String token;
/**
* @param token
* - the constant token to consume
*/
public Token(String token) {
this.token = token;
}
@Override
public ParseResult<String> parse(String toParse) {
if (!isValid(toParse)) {
throw new ParseException("Expected token \"" + token
+ "\" when parsing \"" + toParse + "\"");
}
return new ParseResult<String>(token, toParse.substring(token.length()));
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "\"" + token + "\"";
}
@Override
public boolean isValid(String toParse) {
return toParse.startsWith(token);
}
}
public static class OneOfParser<T> implements Parser<T> {
private final List<Parser<T>> options;
/**
* @param options
*/
public OneOfParser(List<Parser<T>> options) {
this.options = options;
}
@Override
public ParseResult<T> parse(String toParse) {
ParseResult<T> result = null;
for (Parser<T> option : options) {
if (option.isValid(toParse)) {
result = option.parse(toParse);
break;
}
}
if(result == null) {
throw new ParseException("Couldn't find " + options.toString() + " in \"" + toParse + "\"");
}
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return options.toString();
}
@Override
public boolean isValid(String toParse) {
for (Parser<T> option : options) {
if (option.isValid(toParse)) {
return true;
}
}
return false;
}
}
public static final Parser<String> zero = new Token("0");
public static final Parser<String> one = new Token("1");
public static final Parser<String> two = new Token("2");
public static final Parser<String> three = new Token("3");
public static final Parser<String> four = new Token("4");
public static final Parser<String> five = new Token("5");
public static final Parser<String> six = new Token("6");
public static final Parser<String> seven = new Token("7");
public static final Parser<String> eight = new Token("8");
public static final Parser<String> nine = new Token("9");
private static final List<Parser<String>> digitList = new ArrayList<Parser<String>>();
static {
digitList.add(zero);
digitList.add(one);
digitList.add(two);
digitList.add(three);
digitList.add(four);
digitList.add(five);
digitList.add(six);
digitList.add(seven);
digitList.add(eight);
digitList.add(nine);
}
public static final Parser<String> digit = new OneOfParser<String>(digitList);
public static <T> Parser<List<T>> many(Parser<T> component) {
return new Many<T>(component);
}
public static class Many<T> implements Parser<List<T>> {
private final Parser<T> parser;
public Many(Parser<T> parser) {
this.parser = parser;
}
@Override
public ParseResult<List<T>> parse(String toParse) {
List<T> results = new ArrayList<T>();
String remaining = toParse;
while(parser.isValid(remaining)) {
ParseResult<T> parsed = parser.parse(remaining);
remaining = parsed.rest;
results.add(parsed.token);
}
return new ParseResult<List<T>>(results, remaining);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "(" + parser + ")*";
}
@Override
public boolean isValid(String toParse) {
return true;
}
}
public static <A, B> Sequence<A, B> seq(Parser<A> first, Parser<B> second) {
return new Sequence<A, B>(first, second);
}
public static final class Sequence<A, B> implements Parser<Pair<A, B>> {
private final Parser<A> first;
private final Parser<B> second;
private Sequence(Parser<A> first, Parser<B> second) {
this.first = first;
this.second = second;
}
@Override
public ParseResult<Pair<A, B>> parse(String toParse) {
ParseResult<A> r0 = first.parse(toParse);
ParseResult<B> r1 = second.parse(r0.rest);
return new ParseResult<Pair<A, B>>(new Pair<A, B>(r0.token,
r1.token), r1.rest);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return first + " " + second;
}
@Override
public boolean isValid(String toParse) {
return first.isValid(toParse)
&& second.isValid(first.parse(toParse).rest);
}
}
public static <A, B> Parser<A> asFirst(Sequence<A, B> sequence) {
return new AsFirst<A, B>(sequence);
}
public static final class AsFirst<A, B> implements Parser<A> {
public final Sequence<A, B> sequence;
public AsFirst(Sequence<A, B> sequence) {
this.sequence = sequence;
}
@Override
public ParseResult<A> parse(String toParse) {
ParseResult<Pair<A, B>> parsed = sequence.parse(toParse);
return new ParseResult<A>(parsed.token.first, parsed.rest);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "(" + sequence + ")[0]";
}
@Override
public boolean isValid(String toParse) {
return sequence.isValid(toParse);
}
}
public static <A, B> Parser<B> asSecond(Sequence<A, B> sequence) {
return new AsSecond<A, B>(sequence);
}
public static final class AsSecond<A, B> implements Parser<B> {
public final Sequence<A, B> sequence;
public AsSecond(Sequence<A, B> sequence) {
this.sequence = sequence;
}
@Override
public ParseResult<B> parse(String toParse) {
ParseResult<Pair<A, B>> parsed = sequence.parse(toParse);
return new ParseResult<B>(parsed.token.second, parsed.rest);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "(" + sequence + ")[1]";
}
@Override
public boolean isValid(String toParse) {
return sequence.isValid(toParse);
}
}
public static <T> OneOrMore<T> oneOrMore(Parser<T> component) {
return new OneOrMore<T>(component);
}
public static class OneOrMore<T> implements Parser<List<T>> {
private final Parser<T> parser;
public OneOrMore(Parser<T> parser) {
this.parser = parser;
}
@Override
public ParseResult<List<T>> parse(String toParse) {
ParseResult<Pair<T, List<T>>> parsed = seq(parser, new Many<T>(parser)).parse(toParse);
List<T> results = parsed.token.second;
results.add(0, parsed.token.first);
return new ParseResult<List<T>>(results, parsed.rest);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return parser + "+";
}
@Override
public boolean isValid(String toParse) {
return parser.isValid(toParse);
}
}
public static <T> Parser<List<T>> separatedBy(Parser<T> element, String separator) {
return new SeparatedBy<T>(element, new Token(separator));
}
public static class SeparatedBy<T> implements Parser<List<T>> {
private final Parser<T> component;
private final Parser<String> separator;
public SeparatedBy(Parser<T> component, Parser<String> separator) {
this.component = component;
this.separator = separator;
}
@Override
public ParseResult<List<T>> parse(String toParse) {
ParseResult<Pair<List<T>, T>> parsed = seq(
many(asFirst(seq(component, separator))), component).parse(
toParse);
List<T> results = parsed.token.first;
results.add(parsed.token.second);
return new ParseResult<List<T>>(results, parsed.rest);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "(" + component + separator + ")*";
}
@Override
public boolean isValid(String toParse) {
return component.isValid(toParse);
}
}
public static class Joined implements Parser<String> {
private final Parser<List<String>> chars;
public Joined(Parser<List<String>> chars) {
this.chars = chars;
}
@Override
public ParseResult<String> parse(String toParse) {
ParseResult<List<String>> parsed = chars.parse(toParse);
StringBuilder joined = new StringBuilder();
for (String digit : parsed.token) {
joined.append(digit);
}
return new ParseResult<String>(joined.toString(), parsed.rest);
}
@Override
public boolean isValid(String toParse) {
return chars.isValid(toParse);
}
}
public static final Parser<String> digits = new Joined(new OneOrMore<String>(digit));
public static Parser<Integer> integer = new IntegerParser();
private static class IntegerParser implements Parser<Integer> {
@Override
public ParseResult<Integer> parse(String toParse) {
ParseResult<String> parsed = digits.parse(toParse);
int result;
try {
result = Integer.parseInt(parsed.token);
} catch (NumberFormatException nfe) {
throw new ParseException("Unable to parse integer from \""
+ toParse + "\"", nfe);
}
return new ParseResult<Integer>(result, parsed.rest);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "<integer>";
}
@Override
public boolean isValid(String toParse) {
return digit.isValid(toParse);
}
}
public static Parser<Integer> baseTen = new Parser<Integer>() {
@Override
public boolean isValid(String toParse) {
return digit.isValid(toParse);
}
@Override
public ParseResult<Integer> parse(String toParse) {
ParseResult<String> parsed = digit.parse(toParse);
int result;
try {
result = Integer.parseInt(parsed.token);
} catch (NumberFormatException nfe) {
throw new ParseException("Failed parsing base 10 digit from \""
+ parsed.token + "\". Remaining: " + parsed.rest, nfe);
}
return new ParseResult<Integer>(result, parsed.rest);
}};
public static Parser<List<Integer>> row = asFirst(seq(asSecond(seq(
token("["), oneOrMore(baseTen))), token("]")));
public static Parser<List<List<Integer>>> rows = many(row);
public static Parser<List<Integer>> lastPlay = asFirst(seq(asSecond(seq(
token("LastPlay:("), separatedBy(integer, ","))), token(")")));
}
| true | true | public AtroposState read() throws IOException {
StringBuilder result = new StringBuilder();
while (true) {
int read = input.read();
if (read < 0) {
break;
}
result.append((char) read);
}
Pair<List<List<Integer>>, List<Integer>> state = seq(rows, lastPlay).parse(result.toString()).token;
int size = state.first.size();
AtroposCircle[][] board = new AtroposCircle[size][size];
for (int i = 0; i < size - 1; ++i) {
List<Integer> row = state.first.get(i);
for (int j = 0; j < size; ++j) {
int height = size - i - 1;
board[height][j] = new AtroposCircle(j < row.size() ? row.get(j) : Colors.Uncolored.getValue(), size - i - 1, j, size - height - j);
}
}
// unroll last iteration
List<Integer> row = state.first.get(size - 1);
board[0][0] = new AtroposCircle(Colors.Uncolored.getValue(), 0, 0, size - 1);
for (int j = 1; j < size; ++j) {
board[0][j] = new AtroposCircle(j < row.size() ? row.get(j)
: Colors.Uncolored.getValue(), 0, j, size - 1 - j);
}
return new AtroposState(board, new AtroposCircle(state.second.get(0),
state.second.get(1), state.second.get(2), state.second.get(3)));
}
| public AtroposState read() throws IOException {
StringBuilder result = new StringBuilder();
while (true) {
int read = input.read();
if (read < 0) {
break;
}
result.append((char) read);
}
Pair<List<List<Integer>>, List<Integer>> state = seq(rows, lastPlay).parse(result.toString()).token;
int size = state.first.size();
AtroposCircle[][] board = new AtroposCircle[size][size];
for (int i = 0; i < size - 1; ++i) {
List<Integer> row = state.first.get(i);
for (int j = 0; j < size; ++j) {
int height = size - i - 1;
board[height][j] = new AtroposCircle(j < row.size() ? row.get(j) : Colors.Uncolored.getValue(), size - i - 1, j, size - height - j);
}
}
// unroll last iteration
List<Integer> row = state.first.get(size - 1);
board[0][0] = new AtroposCircle(Colors.Uncolored.getValue(), 0, 0, size);
for (int j = 0; j < row.size(); ++j) {
board[0][j + 1] = new AtroposCircle(j < row.size() ? row.get(j)
: Colors.Uncolored.getValue(), 0, j + 1, size - 1 - j);
}
return new AtroposState(board, new AtroposCircle(state.second.get(0),
state.second.get(1), state.second.get(2), state.second.get(3)));
}
|
diff --git a/src/main/java/net/rootdev/javardfa/Parser.java b/src/main/java/net/rootdev/javardfa/Parser.java
index 457854c..edfe1f8 100644
--- a/src/main/java/net/rootdev/javardfa/Parser.java
+++ b/src/main/java/net/rootdev/javardfa/Parser.java
@@ -1,501 +1,504 @@
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa;
import net.rootdev.javardfa.uri.URIExtractor10;
import net.rootdev.javardfa.uri.URIExtractor;
import net.rootdev.javardfa.uri.IRIResolver;
import net.rootdev.javardfa.literal.LiteralCollector;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
/**
* @author Damian Steer <[email protected]>
*/
public class Parser implements ContentHandler {
private final XMLEventFactory eventFactory;
private final StatementSink sink;
private final Set<Setting> settings;
private final LiteralCollector literalCollector;
private final URIExtractor extractor;
private final ProfileCollector profileCollector;
public Parser(StatementSink sink) {
this( sink,
XMLOutputFactory.newInstance(),
XMLEventFactory.newInstance(),
new URIExtractor10(new IRIResolver()),
ProfileCollector.EMPTY_COLLECTOR);
}
public Parser(StatementSink sink,
XMLOutputFactory outputFactory,
XMLEventFactory eventFactory,
URIExtractor extractor,
ProfileCollector profileCollector) {
this.sink = sink;
this.eventFactory = eventFactory;
this.settings = EnumSet.noneOf(Setting.class);
this.extractor = extractor;
this.literalCollector = new LiteralCollector(this, eventFactory, outputFactory);
this.profileCollector = profileCollector;
extractor.setSettings(settings);
// Important, although I guess the caller doesn't get total control
outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
}
public void enable(Setting setting) {
settings.add(setting);
}
public void disable(Setting setting) {
settings.remove(setting);
}
public void setBase(String base) {
this.context = new EvalContext(base);
}
EvalContext parse(EvalContext context, StartElement element)
throws XMLStreamException {
boolean skipElement = false;
String newSubject = null;
String currentObject = null;
List<String> forwardProperties = new LinkedList();
List<String> backwardProperties = new LinkedList();
String currentLanguage = context.language;
if (settings.contains(Setting.OnePointOne)) {
if (element.getAttributeByName(Constants.vocab) != null) {
context.vocab =
element.getAttributeByName(Constants.vocab).getValue().trim();
}
if (element.getAttributeByName(Constants.prefix) != null) {
parsePrefixes(element.getAttributeByName(Constants.prefix).getValue(), context);
}
if (element.getAttributeByName(Constants.profile) != null) {
String profileURI = extractor.resolveURI(
element.getAttributeByName(Constants.profile).getValue(),
context);
profileCollector.getProfile(
profileURI,
context);
}
}
// The xml / html namespace matching is a bit ropey. I wonder if the html 5
// parser has a setting for this?
if (settings.contains(Setting.ManualNamespaces)) {
if (element.getAttributeByName(Constants.xmllang) != null) {
currentLanguage = element.getAttributeByName(Constants.xmllang).getValue();
+ if (currentLanguage.length() == 0) currentLanguage = null;
} else if (element.getAttributeByName(Constants.lang) != null) {
currentLanguage = element.getAttributeByName(Constants.lang).getValue();
+ if (currentLanguage.length() == 0) currentLanguage = null;
}
} else if (element.getAttributeByName(Constants.xmllangNS) != null) {
currentLanguage = element.getAttributeByName(Constants.xmllangNS).getValue();
+ if (currentLanguage.length() == 0) currentLanguage = null;
}
if (Constants.base.equals(element.getName()) &&
element.getAttributeByName(Constants.href) != null) {
context.setBase(element.getAttributeByName(Constants.href).getValue());
}
if (element.getAttributeByName(Constants.rev) == null &&
element.getAttributeByName(Constants.rel) == null) {
Attribute nSubj = findAttribute(element, Constants.about, Constants.src,
Constants.resource, Constants.href);
if (nSubj != null) {
newSubject = extractor.getURI(element, nSubj, context);
}
if (newSubject == null) {
if (Constants.body.equals(element.getName()) ||
Constants.head.equals(element.getName())) {
newSubject = context.base;
}
else if (element.getAttributeByName(Constants.typeof) != null) {
newSubject = createBNode();
} else {
if (context.parentObject != null) {
newSubject = context.parentObject;
}
if (element.getAttributeByName(Constants.property) == null) {
skipElement = true;
}
}
}
} else {
Attribute nSubj = findAttribute(element, Constants.about, Constants.src);
if (nSubj != null) {
newSubject = extractor.getURI(element, nSubj, context);
}
if (newSubject == null) {
// if element is head or body assume about=""
if (Constants.head.equals(element.getName()) ||
Constants.body.equals(element.getName())) {
newSubject = context.base;
} else if (element.getAttributeByName(Constants.typeof) != null) {
newSubject = createBNode();
} else if (context.parentObject != null) {
newSubject = context.parentObject;
}
}
Attribute cObj = findAttribute(element, Constants.resource, Constants.href);
if (cObj != null) {
currentObject = extractor.getURI(element, cObj, context);
}
}
if (newSubject != null && element.getAttributeByName(Constants.typeof) != null) {
List<String> types = extractor.getURIs(element,
element.getAttributeByName(Constants.typeof), context);
for (String type : types) {
emitTriples(newSubject,
Constants.rdfType,
type);
}
}
// Dodgy extension
if (settings.contains(Setting.FormMode)) {
if (Constants.form.equals(element.getName())) {
emitTriples(newSubject, Constants.rdfType, "http://www.w3.org/1999/xhtml/vocab/#form"); // Signal entering form
}
if (Constants.input.equals(element.getName()) &&
element.getAttributeByName(Constants.name) != null) {
currentObject = "?" + element.getAttributeByName(Constants.name).getValue();
}
}
if (currentObject != null) {
if (element.getAttributeByName(Constants.rel) != null) {
emitTriples(newSubject,
extractor.getURIs(element,
element.getAttributeByName(Constants.rel), context),
currentObject);
}
if (element.getAttributeByName(Constants.rev) != null) {
emitTriples(currentObject,
extractor.getURIs(element, element.getAttributeByName(Constants.rev), context),
newSubject);
}
} else {
if (element.getAttributeByName(Constants.rel) != null) {
forwardProperties.addAll(extractor.getURIs(element,
element.getAttributeByName(Constants.rel), context));
}
if (element.getAttributeByName(Constants.rev) != null) {
backwardProperties.addAll(extractor.getURIs(element,
element.getAttributeByName(Constants.rev), context));
}
if (!forwardProperties.isEmpty() || !backwardProperties.isEmpty()) {
// if predicate present
currentObject = createBNode();
}
}
// Getting literal values. Complicated!
if (element.getAttributeByName(Constants.property) != null) {
List<String> props = extractor.getURIs(element,
element.getAttributeByName(Constants.property), context);
String dt = getDatatype(element);
if (element.getAttributeByName(Constants.content) != null) { // The easy bit
String lex = element.getAttributeByName(Constants.content).getValue();
if (dt == null || dt.length() == 0) {
emitTriplesPlainLiteral(newSubject, props, lex, currentLanguage);
} else {
emitTriplesDatatypeLiteral(newSubject, props, lex, dt);
}
} else {
literalCollector.collect(newSubject, props, dt, currentLanguage);
}
}
if (!skipElement && newSubject != null) {
emitTriples(context.parentSubject,
context.forwardProperties,
newSubject);
emitTriples(newSubject,
context.backwardProperties,
context.parentSubject);
}
EvalContext ec = new EvalContext(context);
if (skipElement) {
ec.language = currentLanguage;
} else {
if (newSubject != null) {
ec.parentSubject = newSubject;
} else {
ec.parentSubject = context.parentSubject;
}
if (currentObject != null) {
ec.parentObject = currentObject;
} else if (newSubject != null) {
ec.parentObject = newSubject;
} else {
ec.parentObject = context.parentSubject;
}
ec.language = currentLanguage;
ec.forwardProperties = forwardProperties;
ec.backwardProperties = backwardProperties;
}
return ec;
}
private Attribute findAttribute(StartElement element, QName... names) {
for (QName aName : names) {
Attribute a = element.getAttributeByName(aName);
if (a != null) {
return a;
}
}
return null;
}
public void emitTriples(String subj, Collection<String> props, String obj) {
for (String prop : props) {
sink.addObject(subj, prop, obj);
}
}
public void emitTriplesPlainLiteral(String subj, Collection<String> props, String lex, String language) {
for (String prop : props) {
sink.addLiteral(subj, prop, lex, language, null);
}
}
public void emitTriplesDatatypeLiteral(String subj, Collection<String> props, String lex, String datatype) {
for (String prop : props) {
sink.addLiteral(subj, prop, lex, null, datatype);
}
}
int bnodeId = 0;
private String createBNode() // TODO probably broken? Can you write bnodes in rdfa directly?
{
return "_:node" + (bnodeId++);
}
private String getDatatype(StartElement element) {
Attribute de = element.getAttributeByName(Constants.datatype);
if (de == null) {
return null;
}
String dt = de.getValue();
if (dt.length() == 0) {
return dt;
}
return extractor.expandCURIE(element, dt, context);
}
private void getNamespaces(Attributes attrs) {
for (int i = 0; i < attrs.getLength(); i++) {
String qname = attrs.getQName(i);
String prefix = getPrefix(qname);
if ("xmlns".equals(prefix)) {
String pre = getLocal(prefix, qname);
String uri = attrs.getValue(i);
if (!settings.contains(Setting.ManualNamespaces) && pre.contains("_"))
continue; // not permitted
context.setNamespaceURI(pre, uri);
sink.addPrefix(pre, uri);
}
}
}
private String getPrefix(String qname) {
if (!qname.contains(":")) {
return "";
}
return qname.substring(0, qname.indexOf(":"));
}
private String getLocal(String prefix, String qname) {
if (prefix.length() == 0) {
return qname;
}
return qname.substring(prefix.length() + 1);
}
/**
* SAX methods
*/
private Locator locator;
private EvalContext context;
public void setDocumentLocator(Locator arg0) {
this.locator = arg0;
if (locator.getSystemId() != null)
this.setBase(arg0.getSystemId());
}
public void startDocument() throws SAXException {
sink.start();
}
public void endDocument() throws SAXException {
sink.end();
}
public void startPrefixMapping(String arg0, String arg1)
throws SAXException {
context.setNamespaceURI(arg0, arg1);
sink.addPrefix(arg0, arg1);
}
public void endPrefixMapping(String arg0) throws SAXException {
}
public void startElement(String arg0, String localname, String qname, Attributes arg3) throws SAXException {
try {
//System.err.println("Start element: " + arg0 + " " + arg1 + " " + arg2);
// This is set very late in some html5 cases (not even ready by document start)
if (context == null) {
this.setBase(locator.getSystemId());
}
// Dammit, not quite the same as XMLEventFactory
String prefix = /*(localname.equals(qname))*/
(qname.indexOf(':') == -1 ) ? ""
: qname.substring(0, qname.indexOf(':'));
if (settings.contains(Setting.ManualNamespaces)) {
getNamespaces(arg3);
if (prefix.length() != 0) {
arg0 = context.getNamespaceURI(prefix);
localname = localname.substring(prefix.length() + 1);
}
}
StartElement e = eventFactory.createStartElement(
prefix, arg0, localname,
fromAttributes(arg3), null, context);
if (literalCollector.isCollecting()) literalCollector.handleEvent(e);
// If we are gathering XML we stop parsing
if (!literalCollector.isCollectingXML()) context = parse(context, e);
} catch (XMLStreamException ex) {
throw new RuntimeException("Streaming issue", ex);
}
}
public void endElement(String arg0, String localname, String qname) throws SAXException {
//System.err.println("End element: " + arg0 + " " + arg1 + " " + arg2);
if (literalCollector.isCollecting()) {
String prefix = (localname.equals(qname)) ? ""
: qname.substring(0, qname.indexOf(':'));
XMLEvent e = eventFactory.createEndElement(prefix, arg0, localname);
literalCollector.handleEvent(e);
}
// If we aren't collecting an XML literal keep parsing
if (!literalCollector.isCollectingXML()) context = context.parent;
}
public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
if (literalCollector.isCollecting()) {
XMLEvent e = eventFactory.createCharacters(String.valueOf(arg0, arg1, arg2));
literalCollector.handleEvent(e);
}
}
public void ignorableWhitespace(char[] arg0, int arg1, int arg2) throws SAXException {
//System.err.println("Whitespace...");
if (literalCollector.isCollecting()) {
XMLEvent e = eventFactory.createIgnorableSpace(String.valueOf(arg0, arg1, arg2));
literalCollector.handleEvent(e);
}
}
public void processingInstruction(String arg0, String arg1) throws SAXException {
}
public void skippedEntity(String arg0) throws SAXException {
}
private Iterator fromAttributes(Attributes attributes) {
List toReturn = new LinkedList();
for (int i = 0; i < attributes.getLength(); i++) {
String qname = attributes.getQName(i);
String prefix = qname.contains(":") ? qname.substring(0, qname.indexOf(":")) : "";
Attribute attr = eventFactory.createAttribute(
prefix, attributes.getURI(i),
attributes.getLocalName(i), attributes.getValue(i));
if (!qname.equals("xmlns") && !qname.startsWith("xmlns:"))
toReturn.add(attr);
}
return toReturn.iterator();
}
// 1.1 method
private void parsePrefixes(String value, EvalContext context) {
String[] parts = value.split("\\s+");
for (int i = 0; i < parts.length; i += 2) {
String prefix = parts[i];
if (i + 1 < parts.length && prefix.endsWith(":")) {
String prefixFix = prefix.substring(0, prefix.length() - 1);
context.setPrefix(prefixFix, parts[i+1]);
sink.addPrefix(prefixFix, parts[i+1]);
}
}
}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
| false | true | EvalContext parse(EvalContext context, StartElement element)
throws XMLStreamException {
boolean skipElement = false;
String newSubject = null;
String currentObject = null;
List<String> forwardProperties = new LinkedList();
List<String> backwardProperties = new LinkedList();
String currentLanguage = context.language;
if (settings.contains(Setting.OnePointOne)) {
if (element.getAttributeByName(Constants.vocab) != null) {
context.vocab =
element.getAttributeByName(Constants.vocab).getValue().trim();
}
if (element.getAttributeByName(Constants.prefix) != null) {
parsePrefixes(element.getAttributeByName(Constants.prefix).getValue(), context);
}
if (element.getAttributeByName(Constants.profile) != null) {
String profileURI = extractor.resolveURI(
element.getAttributeByName(Constants.profile).getValue(),
context);
profileCollector.getProfile(
profileURI,
context);
}
}
// The xml / html namespace matching is a bit ropey. I wonder if the html 5
// parser has a setting for this?
if (settings.contains(Setting.ManualNamespaces)) {
if (element.getAttributeByName(Constants.xmllang) != null) {
currentLanguage = element.getAttributeByName(Constants.xmllang).getValue();
} else if (element.getAttributeByName(Constants.lang) != null) {
currentLanguage = element.getAttributeByName(Constants.lang).getValue();
}
} else if (element.getAttributeByName(Constants.xmllangNS) != null) {
currentLanguage = element.getAttributeByName(Constants.xmllangNS).getValue();
}
if (Constants.base.equals(element.getName()) &&
element.getAttributeByName(Constants.href) != null) {
context.setBase(element.getAttributeByName(Constants.href).getValue());
}
if (element.getAttributeByName(Constants.rev) == null &&
element.getAttributeByName(Constants.rel) == null) {
Attribute nSubj = findAttribute(element, Constants.about, Constants.src,
Constants.resource, Constants.href);
if (nSubj != null) {
newSubject = extractor.getURI(element, nSubj, context);
}
if (newSubject == null) {
if (Constants.body.equals(element.getName()) ||
Constants.head.equals(element.getName())) {
newSubject = context.base;
}
else if (element.getAttributeByName(Constants.typeof) != null) {
newSubject = createBNode();
} else {
if (context.parentObject != null) {
newSubject = context.parentObject;
}
if (element.getAttributeByName(Constants.property) == null) {
skipElement = true;
}
}
}
} else {
Attribute nSubj = findAttribute(element, Constants.about, Constants.src);
if (nSubj != null) {
newSubject = extractor.getURI(element, nSubj, context);
}
if (newSubject == null) {
// if element is head or body assume about=""
if (Constants.head.equals(element.getName()) ||
Constants.body.equals(element.getName())) {
newSubject = context.base;
} else if (element.getAttributeByName(Constants.typeof) != null) {
newSubject = createBNode();
} else if (context.parentObject != null) {
newSubject = context.parentObject;
}
}
Attribute cObj = findAttribute(element, Constants.resource, Constants.href);
if (cObj != null) {
currentObject = extractor.getURI(element, cObj, context);
}
}
if (newSubject != null && element.getAttributeByName(Constants.typeof) != null) {
List<String> types = extractor.getURIs(element,
element.getAttributeByName(Constants.typeof), context);
for (String type : types) {
emitTriples(newSubject,
Constants.rdfType,
type);
}
}
// Dodgy extension
if (settings.contains(Setting.FormMode)) {
if (Constants.form.equals(element.getName())) {
emitTriples(newSubject, Constants.rdfType, "http://www.w3.org/1999/xhtml/vocab/#form"); // Signal entering form
}
if (Constants.input.equals(element.getName()) &&
element.getAttributeByName(Constants.name) != null) {
currentObject = "?" + element.getAttributeByName(Constants.name).getValue();
}
}
if (currentObject != null) {
if (element.getAttributeByName(Constants.rel) != null) {
emitTriples(newSubject,
extractor.getURIs(element,
element.getAttributeByName(Constants.rel), context),
currentObject);
}
if (element.getAttributeByName(Constants.rev) != null) {
emitTriples(currentObject,
extractor.getURIs(element, element.getAttributeByName(Constants.rev), context),
newSubject);
}
} else {
if (element.getAttributeByName(Constants.rel) != null) {
forwardProperties.addAll(extractor.getURIs(element,
element.getAttributeByName(Constants.rel), context));
}
if (element.getAttributeByName(Constants.rev) != null) {
backwardProperties.addAll(extractor.getURIs(element,
element.getAttributeByName(Constants.rev), context));
}
if (!forwardProperties.isEmpty() || !backwardProperties.isEmpty()) {
// if predicate present
currentObject = createBNode();
}
}
// Getting literal values. Complicated!
if (element.getAttributeByName(Constants.property) != null) {
List<String> props = extractor.getURIs(element,
element.getAttributeByName(Constants.property), context);
String dt = getDatatype(element);
if (element.getAttributeByName(Constants.content) != null) { // The easy bit
String lex = element.getAttributeByName(Constants.content).getValue();
if (dt == null || dt.length() == 0) {
emitTriplesPlainLiteral(newSubject, props, lex, currentLanguage);
} else {
emitTriplesDatatypeLiteral(newSubject, props, lex, dt);
}
} else {
literalCollector.collect(newSubject, props, dt, currentLanguage);
}
}
if (!skipElement && newSubject != null) {
emitTriples(context.parentSubject,
context.forwardProperties,
newSubject);
emitTriples(newSubject,
context.backwardProperties,
context.parentSubject);
}
EvalContext ec = new EvalContext(context);
if (skipElement) {
ec.language = currentLanguage;
} else {
if (newSubject != null) {
ec.parentSubject = newSubject;
} else {
ec.parentSubject = context.parentSubject;
}
if (currentObject != null) {
ec.parentObject = currentObject;
} else if (newSubject != null) {
ec.parentObject = newSubject;
} else {
ec.parentObject = context.parentSubject;
}
ec.language = currentLanguage;
ec.forwardProperties = forwardProperties;
ec.backwardProperties = backwardProperties;
}
return ec;
}
| EvalContext parse(EvalContext context, StartElement element)
throws XMLStreamException {
boolean skipElement = false;
String newSubject = null;
String currentObject = null;
List<String> forwardProperties = new LinkedList();
List<String> backwardProperties = new LinkedList();
String currentLanguage = context.language;
if (settings.contains(Setting.OnePointOne)) {
if (element.getAttributeByName(Constants.vocab) != null) {
context.vocab =
element.getAttributeByName(Constants.vocab).getValue().trim();
}
if (element.getAttributeByName(Constants.prefix) != null) {
parsePrefixes(element.getAttributeByName(Constants.prefix).getValue(), context);
}
if (element.getAttributeByName(Constants.profile) != null) {
String profileURI = extractor.resolveURI(
element.getAttributeByName(Constants.profile).getValue(),
context);
profileCollector.getProfile(
profileURI,
context);
}
}
// The xml / html namespace matching is a bit ropey. I wonder if the html 5
// parser has a setting for this?
if (settings.contains(Setting.ManualNamespaces)) {
if (element.getAttributeByName(Constants.xmllang) != null) {
currentLanguage = element.getAttributeByName(Constants.xmllang).getValue();
if (currentLanguage.length() == 0) currentLanguage = null;
} else if (element.getAttributeByName(Constants.lang) != null) {
currentLanguage = element.getAttributeByName(Constants.lang).getValue();
if (currentLanguage.length() == 0) currentLanguage = null;
}
} else if (element.getAttributeByName(Constants.xmllangNS) != null) {
currentLanguage = element.getAttributeByName(Constants.xmllangNS).getValue();
if (currentLanguage.length() == 0) currentLanguage = null;
}
if (Constants.base.equals(element.getName()) &&
element.getAttributeByName(Constants.href) != null) {
context.setBase(element.getAttributeByName(Constants.href).getValue());
}
if (element.getAttributeByName(Constants.rev) == null &&
element.getAttributeByName(Constants.rel) == null) {
Attribute nSubj = findAttribute(element, Constants.about, Constants.src,
Constants.resource, Constants.href);
if (nSubj != null) {
newSubject = extractor.getURI(element, nSubj, context);
}
if (newSubject == null) {
if (Constants.body.equals(element.getName()) ||
Constants.head.equals(element.getName())) {
newSubject = context.base;
}
else if (element.getAttributeByName(Constants.typeof) != null) {
newSubject = createBNode();
} else {
if (context.parentObject != null) {
newSubject = context.parentObject;
}
if (element.getAttributeByName(Constants.property) == null) {
skipElement = true;
}
}
}
} else {
Attribute nSubj = findAttribute(element, Constants.about, Constants.src);
if (nSubj != null) {
newSubject = extractor.getURI(element, nSubj, context);
}
if (newSubject == null) {
// if element is head or body assume about=""
if (Constants.head.equals(element.getName()) ||
Constants.body.equals(element.getName())) {
newSubject = context.base;
} else if (element.getAttributeByName(Constants.typeof) != null) {
newSubject = createBNode();
} else if (context.parentObject != null) {
newSubject = context.parentObject;
}
}
Attribute cObj = findAttribute(element, Constants.resource, Constants.href);
if (cObj != null) {
currentObject = extractor.getURI(element, cObj, context);
}
}
if (newSubject != null && element.getAttributeByName(Constants.typeof) != null) {
List<String> types = extractor.getURIs(element,
element.getAttributeByName(Constants.typeof), context);
for (String type : types) {
emitTriples(newSubject,
Constants.rdfType,
type);
}
}
// Dodgy extension
if (settings.contains(Setting.FormMode)) {
if (Constants.form.equals(element.getName())) {
emitTriples(newSubject, Constants.rdfType, "http://www.w3.org/1999/xhtml/vocab/#form"); // Signal entering form
}
if (Constants.input.equals(element.getName()) &&
element.getAttributeByName(Constants.name) != null) {
currentObject = "?" + element.getAttributeByName(Constants.name).getValue();
}
}
if (currentObject != null) {
if (element.getAttributeByName(Constants.rel) != null) {
emitTriples(newSubject,
extractor.getURIs(element,
element.getAttributeByName(Constants.rel), context),
currentObject);
}
if (element.getAttributeByName(Constants.rev) != null) {
emitTriples(currentObject,
extractor.getURIs(element, element.getAttributeByName(Constants.rev), context),
newSubject);
}
} else {
if (element.getAttributeByName(Constants.rel) != null) {
forwardProperties.addAll(extractor.getURIs(element,
element.getAttributeByName(Constants.rel), context));
}
if (element.getAttributeByName(Constants.rev) != null) {
backwardProperties.addAll(extractor.getURIs(element,
element.getAttributeByName(Constants.rev), context));
}
if (!forwardProperties.isEmpty() || !backwardProperties.isEmpty()) {
// if predicate present
currentObject = createBNode();
}
}
// Getting literal values. Complicated!
if (element.getAttributeByName(Constants.property) != null) {
List<String> props = extractor.getURIs(element,
element.getAttributeByName(Constants.property), context);
String dt = getDatatype(element);
if (element.getAttributeByName(Constants.content) != null) { // The easy bit
String lex = element.getAttributeByName(Constants.content).getValue();
if (dt == null || dt.length() == 0) {
emitTriplesPlainLiteral(newSubject, props, lex, currentLanguage);
} else {
emitTriplesDatatypeLiteral(newSubject, props, lex, dt);
}
} else {
literalCollector.collect(newSubject, props, dt, currentLanguage);
}
}
if (!skipElement && newSubject != null) {
emitTriples(context.parentSubject,
context.forwardProperties,
newSubject);
emitTriples(newSubject,
context.backwardProperties,
context.parentSubject);
}
EvalContext ec = new EvalContext(context);
if (skipElement) {
ec.language = currentLanguage;
} else {
if (newSubject != null) {
ec.parentSubject = newSubject;
} else {
ec.parentSubject = context.parentSubject;
}
if (currentObject != null) {
ec.parentObject = currentObject;
} else if (newSubject != null) {
ec.parentObject = newSubject;
} else {
ec.parentObject = context.parentSubject;
}
ec.language = currentLanguage;
ec.forwardProperties = forwardProperties;
ec.backwardProperties = backwardProperties;
}
return ec;
}
|
diff --git a/tests/src/test/java/li/klass/fhem/domain/CULWSDeviceTest.java b/tests/src/test/java/li/klass/fhem/domain/CULWSDeviceTest.java
index a6d779ae..e7882aed 100644
--- a/tests/src/test/java/li/klass/fhem/domain/CULWSDeviceTest.java
+++ b/tests/src/test/java/li/klass/fhem/domain/CULWSDeviceTest.java
@@ -1,57 +1,57 @@
/*
* AndFHEM - Open Source Android application to control a FHEM home automation
* server.
*
* Copyright (c) 2011, Matthias Klass or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU GENERAL PUBLIC LICENSE, as published by the Free Software Foundation.
*
* 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 distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package li.klass.fhem.domain;
import li.klass.fhem.domain.core.DeviceXMLParsingBase;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;
public class CULWSDeviceTest extends DeviceXMLParsingBase {
@Test
public void testForCorrectlySetAttributes() {
CULWSDevice device = getDefaultDevice();
assertThat(device.getName(), is(DEFAULT_TEST_DEVICE_NAME));
assertThat(device.getRoomConcatenated(), is(DEFAULT_TEST_ROOM_NAME));
assertThat(device.getHumidity(), is("45.8 (%)"));
assertThat(device.getTemperature(), is("13.6 (°C)"));
assertThat(device.getState(), is("T: 13.6 H: 45.8"));
assertThat(device.getAvailableTargetStates(), is(nullValue()));
assertThat(device.getFileLog(), is(notNullValue()));
- assertThat(device.getDeviceCharts().size(), is(2));
+ assertThat(device.getDeviceCharts().size(), is(1));
}
@Override
protected String getFileName() {
return "cul_ws.xml";
}
}
| true | true | public void testForCorrectlySetAttributes() {
CULWSDevice device = getDefaultDevice();
assertThat(device.getName(), is(DEFAULT_TEST_DEVICE_NAME));
assertThat(device.getRoomConcatenated(), is(DEFAULT_TEST_ROOM_NAME));
assertThat(device.getHumidity(), is("45.8 (%)"));
assertThat(device.getTemperature(), is("13.6 (°C)"));
assertThat(device.getState(), is("T: 13.6 H: 45.8"));
assertThat(device.getAvailableTargetStates(), is(nullValue()));
assertThat(device.getFileLog(), is(notNullValue()));
assertThat(device.getDeviceCharts().size(), is(2));
}
| public void testForCorrectlySetAttributes() {
CULWSDevice device = getDefaultDevice();
assertThat(device.getName(), is(DEFAULT_TEST_DEVICE_NAME));
assertThat(device.getRoomConcatenated(), is(DEFAULT_TEST_ROOM_NAME));
assertThat(device.getHumidity(), is("45.8 (%)"));
assertThat(device.getTemperature(), is("13.6 (°C)"));
assertThat(device.getState(), is("T: 13.6 H: 45.8"));
assertThat(device.getAvailableTargetStates(), is(nullValue()));
assertThat(device.getFileLog(), is(notNullValue()));
assertThat(device.getDeviceCharts().size(), is(1));
}
|
diff --git a/src/org/mozilla/javascript/NativeArray.java b/src/org/mozilla/javascript/NativeArray.java
index 87a2daa4..ecec663f 100644
--- a/src/org/mozilla/javascript/NativeArray.java
+++ b/src/org/mozilla/javascript/NativeArray.java
@@ -1,1204 +1,1204 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (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.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Mike McCabe
* Igor Bukanov
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
/**
* This class implements the Array native object.
* @author Norris Boyd
* @author Mike McCabe
*/
public class NativeArray extends IdScriptable {
/*
* Optimization possibilities and open issues:
* - Long vs. double schizophrenia. I suspect it might be better
* to use double throughout.
* - Most array operations go through getElem or setElem (defined
* in this file) to handle the full 2^32 range; it might be faster
* to have versions of most of the loops in this file for the
* (infinitely more common) case of indices < 2^31.
* - Functions that need a new Array call "new Array" in the
* current scope rather than using a hardwired constructor;
* "Array" could be redefined. It turns out that js calls the
* equivalent of "new Array" in the current scope, except that it
* always gets at least an object back, even when Array == null.
*/
static void init(Context cx, Scriptable scope, boolean sealed)
{
NativeArray obj = new NativeArray();
obj.prototypeFlag = true;
obj.addAsPrototype(MAX_PROTOTYPE_ID, cx, scope, sealed);
}
/**
* Zero-parameter constructor: just used to create Array.prototype
*/
private NativeArray()
{
dense = null;
this.length = 0;
}
public NativeArray(long length)
{
int intLength = (int) length;
if (intLength == length && intLength > 0) {
if (intLength > maximumDenseLength)
intLength = maximumDenseLength;
dense = new Object[intLength];
for (int i=0; i < intLength; i++)
dense[i] = NOT_FOUND;
}
this.length = length;
}
public NativeArray(Object[] array)
{
dense = array;
this.length = array.length;
}
public String getClassName()
{
return "Array";
}
protected int getIdAttributes(int id)
{
if (id == Id_length) {
return DONTENUM | PERMANENT;
}
return super.getIdAttributes(id);
}
protected Object getIdValue(int id)
{
if (id == Id_length) {
return wrap_double(length);
}
return super.getIdValue(id);
}
protected void setIdValue(int id, Object value)
{
if (id == Id_length) {
setLength(value); return;
}
super.setIdValue(id, value);
}
public int methodArity(int methodId)
{
if (prototypeFlag) {
switch (methodId) {
case Id_constructor: return 1;
case Id_toString: return 0;
case Id_toLocaleString: return 1;
case Id_join: return 1;
case Id_reverse: return 0;
case Id_sort: return 1;
case Id_push: return 1;
case Id_pop: return 1;
case Id_shift: return 1;
case Id_unshift: return 1;
case Id_splice: return 1;
case Id_concat: return 1;
case Id_slice: return 1;
}
}
return super.methodArity(methodId);
}
public Object execMethod
(int methodId, IdFunction f,
Context cx, Scriptable scope, Scriptable thisObj, Object[] args)
throws JavaScriptException
{
if (prototypeFlag) {
switch (methodId) {
case Id_constructor:
return jsConstructor(cx, scope, args, f, thisObj == null);
case Id_toString:
return js_toString(cx, thisObj, args);
case Id_toLocaleString:
return js_toLocaleString(cx, thisObj, args);
case Id_join:
return js_join(cx, thisObj, args);
case Id_reverse:
return js_reverse(cx, thisObj, args);
case Id_sort:
return js_sort(cx, scope, thisObj, args);
case Id_push:
return js_push(cx, thisObj, args);
case Id_pop:
return js_pop(cx, thisObj, args);
case Id_shift:
return js_shift(cx, thisObj, args);
case Id_unshift:
return js_unshift(cx, thisObj, args);
case Id_splice:
return js_splice(cx, scope, thisObj, args);
case Id_concat:
return js_concat(cx, scope, thisObj, args);
case Id_slice:
return js_slice(cx, thisObj, args);
}
}
return super.execMethod(methodId, f, cx, scope, thisObj, args);
}
public Object get(int index, Scriptable start)
{
if (dense != null && 0 <= index && index < dense.length)
return dense[index];
return super.get(index, start);
}
public boolean has(int index, Scriptable start)
{
if (dense != null && 0 <= index && index < dense.length)
return dense[index] != NOT_FOUND;
return super.has(index, start);
}
// if id is an array index (ECMA 15.4.0), return the number,
// otherwise return -1L
private static long toArrayIndex(String id)
{
double d = ScriptRuntime.toNumber(id);
if (d == d) {
long index = ScriptRuntime.toUint32(d);
if (index == d && index != 4294967295L) {
// Assume that ScriptRuntime.toString(index) is the same
// as java.lang.Long.toString(index) for long
if (Long.toString(index).equals(id)) {
return index;
}
}
}
return -1;
}
public void put(String id, Scriptable start, Object value)
{
super.put(id, start, value);
if (start == this) {
// If the object is sealed, super will throw exception
long index = toArrayIndex(id);
if (index >= length) {
length = index + 1;
}
}
}
public void put(int index, Scriptable start, Object value)
{
if (start == this && !isSealed()
&& dense != null && 0 <= index && index < dense.length)
{
// If start == this && sealed, super will throw exception
dense[index] = value;
} else {
super.put(index, start, value);
}
if (start == this) {
// only set the array length if given an array index (ECMA 15.4.0)
if (this.length <= index) {
// avoid overflowing index!
this.length = (long)index + 1;
}
}
}
public void delete(int index)
{
if (!isSealed()
&& dense != null && 0 <= index && index < dense.length)
{
dense[index] = NOT_FOUND;
} else {
super.delete(index);
}
}
public Object[] getIds()
{
Object[] superIds = super.getIds();
if (dense == null) { return superIds; }
int N = dense.length;
long currentLength = length;
if (N > currentLength) {
N = (int)currentLength;
}
if (N == 0) { return superIds; }
int shift = superIds.length;
Object[] ids = new Object[shift + N];
// Make a copy of dense to be immune to removing
// of array elems from other thread when calculating presentCount
System.arraycopy(dense, 0, ids, shift, N);
int presentCount = 0;
for (int i = 0; i != N; ++i) {
// Replace existing elements by their indexes
if (ids[shift + i] != NOT_FOUND) {
ids[shift + presentCount] = new Integer(i);
++presentCount;
}
}
if (presentCount != N) {
// dense contains deleted elems, need to shrink the result
Object[] tmp = new Object[shift + presentCount];
System.arraycopy(ids, shift, tmp, shift, presentCount);
ids = tmp;
}
System.arraycopy(superIds, 0, ids, 0, shift);
return ids;
}
public Object getDefaultValue(Class hint)
{
if (hint == ScriptRuntime.NumberClass) {
Context cx = Context.getContext();
if (cx.getLanguageVersion() == Context.VERSION_1_2)
return new Long(length);
}
return super.getDefaultValue(hint);
}
/**
* See ECMA 15.4.1,2
*/
private static Object jsConstructor(Context cx, Scriptable scope,
Object[] args, IdFunction ctorObj,
boolean inNewExpr)
throws JavaScriptException
{
if (!inNewExpr) {
// FunctionObject.construct will set up parent, proto
return ctorObj.construct(cx, scope, args);
}
if (args.length == 0)
return new NativeArray();
// Only use 1 arg as first element for version 1.2; for
// any other version (including 1.3) follow ECMA and use it as
// a length.
if (cx.getLanguageVersion() == cx.VERSION_1_2) {
return new NativeArray(args);
} else {
Object arg0 = args[0];
if (args.length > 1 || !(arg0 instanceof Number)) {
return new NativeArray(args);
} else {
long len = ScriptRuntime.toUint32(arg0);
if (len != ((Number)arg0).doubleValue())
throw Context.reportRuntimeError0("msg.arraylength.bad");
return new NativeArray(len);
}
}
}
public long getLength() {
return length;
}
/** @deprecated Use {@link #getLength()} instead. */
public long jsGet_length() {
return getLength();
}
private void setLength(Object val) {
/* XXX do we satisfy this?
* 15.4.5.1 [[Put]](P, V):
* 1. Call the [[CanPut]] method of A with name P.
* 2. If Result(1) is false, return.
* ?
*/
double d = ScriptRuntime.toNumber(val);
long longVal = ScriptRuntime.toUint32(d);
if (longVal != d)
throw Context.reportRuntimeError0("msg.arraylength.bad");
if (longVal < length) {
// remove all properties between longVal and length
if (length - longVal > 0x1000) {
// assume that the representation is sparse
Object[] e = getIds(); // will only find in object itself
for (int i=0; i < e.length; i++) {
Object id = e[i];
if (id instanceof String) {
// > MAXINT will appear as string
String strId = (String)id;
long index = toArrayIndex(strId);
if (index >= longVal)
delete(strId);
} else {
int index = ((Integer)id).intValue();
if (index >= longVal)
delete(index);
}
}
} else {
// assume a dense representation
for (long i = longVal; i < length; i++) {
deleteElem(this, i);
}
}
}
length = longVal;
}
/* Support for generic Array-ish objects. Most of the Array
* functions try to be generic; anything that has a length
* property is assumed to be an array.
* getLengthProperty returns 0 if obj does not have the length property
* or its value is not convertible to a number.
*/
static long getLengthProperty(Scriptable obj) {
// These will both give numeric lengths within Uint32 range.
if (obj instanceof NativeString) {
return ((NativeString)obj).getLength();
} else if (obj instanceof NativeArray) {
return ((NativeArray)obj).getLength();
} else if (!(obj instanceof Scriptable)) {
return 0;
}
return ScriptRuntime.toUint32(ScriptRuntime
.getProp(obj, "length", obj));
}
/* Utility functions to encapsulate index > Integer.MAX_VALUE
* handling. Also avoids unnecessary object creation that would
* be necessary to use the general ScriptRuntime.get/setElem
* functions... though this is probably premature optimization.
*/
private static void deleteElem(Scriptable target, long index) {
int i = (int)index;
if (i == index) { target.delete(i); }
else { target.delete(Long.toString(index)); }
}
private static Object getElem(Scriptable target, long index) {
if (index > Integer.MAX_VALUE) {
String id = Long.toString(index);
return ScriptRuntime.getStrIdElem(target, id);
} else {
return ScriptRuntime.getElem(target, (int)index);
}
}
private static void setElem(Scriptable target, long index, Object value) {
if (index > Integer.MAX_VALUE) {
String id = Long.toString(index);
ScriptRuntime.setStrIdElem(target, id, value, target);
} else {
ScriptRuntime.setElem(target, (int)index, value);
}
}
private static String js_toString(Context cx, Scriptable thisObj,
Object[] args)
throws JavaScriptException
{
return toStringHelper(cx, thisObj,
cx.hasFeature(Context.FEATURE_TO_STRING_AS_SOURCE),
false);
}
private static String js_toLocaleString(Context cx, Scriptable thisObj,
Object[] args)
throws JavaScriptException
{
return toStringHelper(cx, thisObj, false, true);
}
private static String toStringHelper(Context cx, Scriptable thisObj,
boolean toSource, boolean toLocale)
throws JavaScriptException
{
/* It's probably redundant to handle long lengths in this
* function; StringBuffers are limited to 2^31 in java.
*/
long length = getLengthProperty(thisObj);
StringBuffer result = new StringBuffer(256);
// whether to return '4,unquoted,5' or '[4, "quoted", 5]'
String separator;
if (toSource) {
result.append('[');
separator = ", ";
} else {
separator = ",";
}
boolean haslast = false;
long i = 0;
boolean toplevel, iterating;
if (cx.iterating == null) {
toplevel = true;
iterating = false;
cx.iterating = new ObjToIntMap(31);
} else {
toplevel = false;
iterating = cx.iterating.has(thisObj);
}
// Make sure cx.iterating is set to null when done
// so we don't leak memory
try {
if (!iterating) {
cx.iterating.put(thisObj, 0); // stop recursion.
for (i = 0; i < length; i++) {
if (i > 0) result.append(separator);
Object elem = getElem(thisObj, i);
if (elem == null || elem == Undefined.instance) {
haslast = false;
continue;
}
haslast = true;
if (elem instanceof String) {
String s = (String)elem;
if (toSource) {
result.append('\"');
result.append(ScriptRuntime.escapeString(s));
result.append('\"');
} else {
result.append(s);
}
} else {
if (toLocale && elem != Undefined.instance &&
elem != null)
{
Scriptable obj = ScriptRuntime.
toObject(cx, thisObj, elem);
Object tls = ScriptRuntime.
getProp(obj, "toLocaleString", thisObj);
elem = ScriptRuntime.call(cx, tls, elem,
ScriptRuntime.emptyArgs);
}
result.append(ScriptRuntime.toString(elem));
}
}
}
} finally {
if (toplevel) {
cx.iterating = null;
}
}
if (toSource) {
//for [,,].length behavior; we want toString to be symmetric.
if (!haslast && i > 0)
result.append(", ]");
else
result.append(']');
}
return result.toString();
}
/**
* See ECMA 15.4.4.3
*/
private static String js_join(Context cx, Scriptable thisObj,
Object[] args)
{
StringBuffer result = new StringBuffer();
String separator;
long length = getLengthProperty(thisObj);
// if no args, use "," as separator
if ((args.length < 1) || (args[0] == Undefined.instance)) {
separator = ",";
} else {
separator = ScriptRuntime.toString(args[0]);
}
for (long i=0; i < length; i++) {
if (i > 0)
result.append(separator);
Object temp = getElem(thisObj, i);
if (temp == null || temp == Undefined.instance)
continue;
result.append(ScriptRuntime.toString(temp));
}
return result.toString();
}
/**
* See ECMA 15.4.4.4
*/
private static Scriptable js_reverse(Context cx, Scriptable thisObj,
Object[] args)
{
long len = getLengthProperty(thisObj);
long half = len / 2;
for(long i=0; i < half; i++) {
long j = len - i - 1;
Object temp1 = getElem(thisObj, i);
Object temp2 = getElem(thisObj, j);
setElem(thisObj, i, temp2);
setElem(thisObj, j, temp1);
}
return thisObj;
}
/**
* See ECMA 15.4.4.5
*/
private static Scriptable js_sort(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
throws JavaScriptException
{
long length = getLengthProperty(thisObj);
if (length <= 1) { return thisObj; }
Object compare;
Object[] cmpBuf;
if (args.length > 0 && Undefined.instance != args[0]) {
// sort with given compare function
compare = args[0];
cmpBuf = new Object[2]; // Buffer for cmp arguments
} else {
// sort with default compare
compare = null;
cmpBuf = null;
}
// Should we use the extended sort function, or the faster one?
if (length >= Integer.MAX_VALUE) {
heapsort_extended(cx, scope, thisObj, length, compare, cmpBuf);
}
else {
int ilength = (int)length;
// copy the JS array into a working array, so it can be
// sorted cheaply.
Object[] working = new Object[ilength];
for (int i = 0; i != ilength; ++i) {
working[i] = getElem(thisObj, i);
}
heapsort(cx, scope, working, ilength, compare, cmpBuf);
// copy the working array back into thisObj
for (int i = 0; i != ilength; ++i) {
setElem(thisObj, i, working[i]);
}
}
return thisObj;
}
// Return true only if x > y
private static boolean isBigger(Context cx, Scriptable scope,
Object x, Object y,
Object cmp, Object[] cmpBuf)
throws JavaScriptException
{
if (check) {
if (cmp == null) {
if (cmpBuf != null) Context.codeBug();
} else {
if (cmpBuf == null || cmpBuf.length != 2) Context.codeBug();
}
}
Object undef = Undefined.instance;
// sort undefined to end
if (undef == y) {
return false; // x can not be bigger then undef
} else if (undef == x) {
return true; // y != undef here, so x > y
}
if (cmp == null) {
// if no cmp function supplied, sort lexicographically
String a = ScriptRuntime.toString(x);
String b = ScriptRuntime.toString(y);
return a.compareTo(b) > 0;
}
else {
// assemble args and call supplied JS cmp function
cmpBuf[0] = x;
cmpBuf[1] = y;
Object ret = ScriptRuntime.call(cx, cmp, null, cmpBuf, scope);
double d = ScriptRuntime.toNumber(ret);
// XXX what to do when cmp function returns NaN? ECMA states
// that it's then not a 'consistent compararison function'... but
// then what do we do? Back out and start over with the generic
// cmp function when we see a NaN? Throw an error?
// for now, just ignore it:
return d > 0;
}
}
/** Heapsort implementation.
* See "Introduction to Algorithms" by Cormen, Leiserson, Rivest for details.
* Adjusted for zero based indexes.
*/
private static void heapsort(Context cx, Scriptable scope,
Object[] array, int length,
Object cmp, Object[] cmpBuf)
throws JavaScriptException
{
if (check && length <= 1) Context.codeBug();
// Build heap
for (int i = length / 2; i != 0;) {
--i;
Object pivot = array[i];
heapify(cx, scope, pivot, array, i, length, cmp, cmpBuf);
}
// Sort heap
for (int i = length; i != 1;) {
--i;
Object pivot = array[i];
array[i] = array[0];
heapify(cx, scope, pivot, array, 0, i, cmp, cmpBuf);
}
}
/** pivot and child heaps of i should be made into heap starting at i,
* original array[i] is never used to have less array access during sorting.
*/
private static void heapify(Context cx, Scriptable scope,
Object pivot, Object[] array, int i, int end,
Object cmp, Object[] cmpBuf)
throws JavaScriptException
{
for (;;) {
int child = i * 2 + 1;
if (child >= end) {
break;
}
Object childVal = array[child];
if (child + 1 < end) {
Object nextVal = array[child + 1];
if (isBigger(cx, scope, nextVal, childVal, cmp, cmpBuf)) {
++child; childVal = nextVal;
}
}
if (!isBigger(cx, scope, childVal, pivot, cmp, cmpBuf)) {
break;
}
array[i] = childVal;
i = child;
}
array[i] = pivot;
}
/** Version of heapsort that call getElem/setElem on target to query/assign
* array elements instead of Java array access
*/
private static void heapsort_extended(Context cx, Scriptable scope,
Scriptable target, long length,
Object cmp, Object[] cmpBuf)
throws JavaScriptException
{
if (check && length <= 1) Context.codeBug();
// Build heap
for (long i = length / 2; i != 0;) {
--i;
Object pivot = getElem(target, i);
heapify_extended(cx, scope, pivot, target, i, length, cmp, cmpBuf);
}
// Sort heap
for (long i = length; i != 1;) {
--i;
Object pivot = getElem(target, i);
setElem(target, i, getElem(target, 0));
heapify_extended(cx, scope, pivot, target, 0, i, cmp, cmpBuf);
}
}
private static void heapify_extended(Context cx, Scriptable scope,
Object pivot, Scriptable target,
long i, long end,
Object cmp, Object[] cmpBuf)
throws JavaScriptException
{
for (;;) {
long child = i * 2 + 1;
if (child >= end) {
break;
}
Object childVal = getElem(target, child);
if (child + 1 < end) {
Object nextVal = getElem(target, child + 1);
if (isBigger(cx, scope, nextVal, childVal, cmp, cmpBuf)) {
++child; childVal = nextVal;
}
}
if (!isBigger(cx, scope, childVal, pivot, cmp, cmpBuf)) {
break;
}
setElem(target, i, childVal);
i = child;
}
setElem(target, i, pivot);
}
/**
* Non-ECMA methods.
*/
private static Object js_push(Context cx, Scriptable thisObj,
Object[] args)
{
long length = getLengthProperty(thisObj);
for (int i = 0; i < args.length; i++) {
setElem(thisObj, length + i, args[i]);
}
length += args.length;
Double lengthObj = new Double(length);
ScriptRuntime.setProp(thisObj, "length", lengthObj, thisObj);
/*
* If JS1.2, follow Perl4 by returning the last thing pushed.
* Otherwise, return the new array length.
*/
if (cx.getLanguageVersion() == Context.VERSION_1_2)
// if JS1.2 && no arguments, return undefined.
return args.length == 0
? Context.getUndefinedValue()
: args[args.length - 1];
else
return lengthObj;
}
private static Object js_pop(Context cx, Scriptable thisObj,
Object[] args)
{
Object result;
long length = getLengthProperty(thisObj);
if (length > 0) {
length--;
// Get the to-be-deleted property's value.
result = getElem(thisObj, length);
// We don't need to delete the last property, because
// setLength does that for us.
} else {
result = Context.getUndefinedValue();
}
// necessary to match js even when length < 0; js pop will give a
// length property to any target it is called on.
ScriptRuntime.setProp(thisObj, "length", new Double(length), thisObj);
return result;
}
private static Object js_shift(Context cx, Scriptable thisObj,
Object[] args)
{
Object result;
long length = getLengthProperty(thisObj);
if (length > 0) {
long i = 0;
length--;
// Get the to-be-deleted property's value.
result = getElem(thisObj, i);
/*
* Slide down the array above the first element. Leave i
* set to point to the last element.
*/
if (length > 0) {
for (i = 1; i <= length; i++) {
Object temp = getElem(thisObj, i);
setElem(thisObj, i - 1, temp);
}
}
// We don't need to delete the last property, because
// setLength does that for us.
} else {
result = Context.getUndefinedValue();
}
ScriptRuntime.setProp(thisObj, "length", new Double(length), thisObj);
return result;
}
private static Object js_unshift(Context cx, Scriptable thisObj,
Object[] args)
{
Object result;
double length = (double)getLengthProperty(thisObj);
int argc = args.length;
if (args.length > 0) {
/* Slide up the array to make room for args at the bottom */
if (length > 0) {
for (long last = (long)length - 1; last >= 0; last--) {
Object temp = getElem(thisObj, last);
setElem(thisObj, last + argc, temp);
}
}
/* Copy from argv to the bottom of the array. */
for (int i = 0; i < args.length; i++) {
setElem(thisObj, i, args[i]);
}
/* Follow Perl by returning the new array length. */
length += args.length;
ScriptRuntime.setProp(thisObj, "length",
new Double(length), thisObj);
}
return new Long((long)length);
}
private static Object js_splice(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
/* create an empty Array to return. */
scope = getTopLevelScope(scope);
Object result = ScriptRuntime.newObject(cx, scope, "Array", null);
int argc = args.length;
if (argc == 0)
return result;
long length = getLengthProperty(thisObj);
/* Convert the first argument into a starting index. */
- long begin = toSliceIndex(ScriptRuntime.toInteger(args[0]), length);
+ long begin = toSliceIndex(ScriptRuntime.toInteger(args[0]), length);
argc--;
/* Convert the second argument into count */
long count;
if (args.length == 1) {
count = length - begin;
} else {
double dcount = ScriptRuntime.toInteger(args[1]);
if (dcount < 0) {
count = 0;
} else if (dcount > (length - begin)) {
count = length - begin;
} else {
count = (long)dcount;
}
argc--;
}
long end = begin + count;
/* If there are elements to remove, put them into the return value. */
if (count != 0) {
if (count == 1
&& (cx.getLanguageVersion() == Context.VERSION_1_2))
{
/*
* JS lacks "list context", whereby in Perl one turns the
* single scalar that's spliced out into an array just by
* assigning it to @single instead of $single, or by using it
* as Perl push's first argument, for instance.
*
* JS1.2 emulated Perl too closely and returned a non-Array for
* the single-splice-out case, requiring callers to test and
* wrap in [] if necessary. So JS1.3, default, and other
* versions all return an array of length 1 for uniformity.
*/
result = getElem(thisObj, begin);
} else {
for (long last = begin; last != end; last++) {
Scriptable resultArray = (Scriptable)result;
Object temp = getElem(thisObj, last);
setElem(resultArray, last - begin, temp);
}
}
} else if (count == 0
&& cx.getLanguageVersion() == Context.VERSION_1_2)
{
/* Emulate C JS1.2; if no elements are removed, return undefined. */
result = Context.getUndefinedValue();
}
/* Find the direction (up or down) to copy and make way for argv. */
long delta = argc - count;
if (delta > 0) {
for (long last = length - 1; last >= end; last--) {
Object temp = getElem(thisObj, last);
setElem(thisObj, last + delta, temp);
}
} else if (delta < 0) {
for (long last = end; last < length; last++) {
Object temp = getElem(thisObj, last);
setElem(thisObj, last + delta, temp);
}
}
/* Copy from argv into the hole to complete the splice. */
int argoffset = args.length - argc;
for (int i = 0; i < argc; i++) {
setElem(thisObj, begin + i, args[i + argoffset]);
}
/* Update length in case we deleted elements from the end. */
ScriptRuntime.setProp(thisObj, "length",
new Double(length + delta), thisObj);
return result;
}
/*
* See Ecma 262v3 15.4.4.4
*/
private static Scriptable js_concat(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
throws JavaScriptException
{
// create an empty Array to return.
scope = getTopLevelScope(scope);
Function ctor = ScriptRuntime.getExistingCtor(cx, scope, "Array");
Scriptable result = ctor.construct(cx, scope, ScriptRuntime.emptyArgs);
long length;
long slot = 0;
/* Put the target in the result array; only add it as an array
* if it looks like one.
*/
if (ScriptRuntime.instanceOf(scope, thisObj, ctor)) {
length = getLengthProperty(thisObj);
// Copy from the target object into the result
for (slot = 0; slot < length; slot++) {
Object temp = getElem(thisObj, slot);
setElem(result, slot, temp);
}
} else {
setElem(result, slot++, thisObj);
}
/* Copy from the arguments into the result. If any argument
* has a numeric length property, treat it as an array and add
* elements separately; otherwise, just copy the argument.
*/
for (int i = 0; i < args.length; i++) {
if (ScriptRuntime.instanceOf(scope, args[i], ctor)) {
// ScriptRuntime.instanceOf => instanceof Scriptable
Scriptable arg = (Scriptable)args[i];
length = getLengthProperty(arg);
for (long j = 0; j < length; j++, slot++) {
Object temp = getElem(arg, j);
setElem(result, slot, temp);
}
} else {
setElem(result, slot++, args[i]);
}
}
return result;
}
private Scriptable js_slice(Context cx, Scriptable thisObj,
Object[] args)
{
Scriptable scope = getTopLevelScope(this);
Scriptable result = ScriptRuntime.newObject(cx, scope, "Array", null);
long length = getLengthProperty(thisObj);
long begin, end;
if (args.length == 0) {
begin = 0;
end = length;
} else {
begin = toSliceIndex(ScriptRuntime.toInteger(args[0]), length);
if (args.length == 1) {
end = length;
} else {
end = toSliceIndex(ScriptRuntime.toInteger(args[1]), length);
}
}
for (long slot = begin; slot < end; slot++) {
Object temp = getElem(thisObj, slot);
setElem(result, slot - begin, temp);
}
return result;
}
private static long toSliceIndex(double value, long length) {
long result;
if (value < 0.0) {
if (value + length < 0.0) {
result = 0;
} else {
result = (long)(value + length);
}
} else if (value > length) {
result = length;
} else {
result = (long)value;
}
return result;
}
protected String getIdName(int id)
{
if (id == Id_length) { return "length"; }
if (prototypeFlag) {
switch (id) {
case Id_constructor: return "constructor";
case Id_toString: return "toString";
case Id_toLocaleString: return "toLocaleString";
case Id_join: return "join";
case Id_reverse: return "reverse";
case Id_sort: return "sort";
case Id_push: return "push";
case Id_pop: return "pop";
case Id_shift: return "shift";
case Id_unshift: return "unshift";
case Id_splice: return "splice";
case Id_concat: return "concat";
case Id_slice: return "slice";
}
}
return null;
}
private static final int
Id_length = 1,
MAX_INSTANCE_ID = 1;
{ setMaxId(MAX_INSTANCE_ID); }
protected int mapNameToId(String s)
{
if (s.equals("length")) { return Id_length; }
else if (prototypeFlag) {
return toPrototypeId(s);
}
return 0;
}
// #string_id_map#
private static int toPrototypeId(String s)
{
int id;
// #generated# Last update: 2001-04-23 11:46:01 GMT+02:00
L0: { id = 0; String X = null; int c;
L: switch (s.length()) {
case 3: X="pop";id=Id_pop; break L;
case 4: c=s.charAt(0);
if (c=='j') { X="join";id=Id_join; }
else if (c=='p') { X="push";id=Id_push; }
else if (c=='s') { X="sort";id=Id_sort; }
break L;
case 5: c=s.charAt(1);
if (c=='h') { X="shift";id=Id_shift; }
else if (c=='l') { X="slice";id=Id_slice; }
break L;
case 6: c=s.charAt(0);
if (c=='c') { X="concat";id=Id_concat; }
else if (c=='l') { X="length";id=Id_length; }
else if (c=='s') { X="splice";id=Id_splice; }
break L;
case 7: c=s.charAt(0);
if (c=='r') { X="reverse";id=Id_reverse; }
else if (c=='u') { X="unshift";id=Id_unshift; }
break L;
case 8: X="toString";id=Id_toString; break L;
case 11: X="constructor";id=Id_constructor; break L;
case 14: X="toLocaleString";id=Id_toLocaleString; break L;
}
if (X!=null && X!=s && !X.equals(s)) id = 0;
}
// #/generated#
return id;
}
private static final int
Id_constructor = MAX_INSTANCE_ID + 1,
Id_toString = MAX_INSTANCE_ID + 2,
Id_toLocaleString = MAX_INSTANCE_ID + 3,
Id_join = MAX_INSTANCE_ID + 4,
Id_reverse = MAX_INSTANCE_ID + 5,
Id_sort = MAX_INSTANCE_ID + 6,
Id_push = MAX_INSTANCE_ID + 7,
Id_pop = MAX_INSTANCE_ID + 8,
Id_shift = MAX_INSTANCE_ID + 9,
Id_unshift = MAX_INSTANCE_ID + 10,
Id_splice = MAX_INSTANCE_ID + 11,
Id_concat = MAX_INSTANCE_ID + 12,
Id_slice = MAX_INSTANCE_ID + 13,
MAX_PROTOTYPE_ID = MAX_INSTANCE_ID + 13;
// #/string_id_map#
private long length;
private Object[] dense;
private static final int maximumDenseLength = 10000;
private boolean prototypeFlag;
private static final boolean check = true && Context.check;
}
| true | true | private static Object js_splice(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
/* create an empty Array to return. */
scope = getTopLevelScope(scope);
Object result = ScriptRuntime.newObject(cx, scope, "Array", null);
int argc = args.length;
if (argc == 0)
return result;
long length = getLengthProperty(thisObj);
/* Convert the first argument into a starting index. */
long begin = toSliceIndex(ScriptRuntime.toInteger(args[0]), length);
argc--;
/* Convert the second argument into count */
long count;
if (args.length == 1) {
count = length - begin;
} else {
double dcount = ScriptRuntime.toInteger(args[1]);
if (dcount < 0) {
count = 0;
} else if (dcount > (length - begin)) {
count = length - begin;
} else {
count = (long)dcount;
}
argc--;
}
long end = begin + count;
/* If there are elements to remove, put them into the return value. */
if (count != 0) {
if (count == 1
&& (cx.getLanguageVersion() == Context.VERSION_1_2))
{
/*
* JS lacks "list context", whereby in Perl one turns the
* single scalar that's spliced out into an array just by
* assigning it to @single instead of $single, or by using it
* as Perl push's first argument, for instance.
*
* JS1.2 emulated Perl too closely and returned a non-Array for
* the single-splice-out case, requiring callers to test and
* wrap in [] if necessary. So JS1.3, default, and other
* versions all return an array of length 1 for uniformity.
*/
result = getElem(thisObj, begin);
} else {
for (long last = begin; last != end; last++) {
Scriptable resultArray = (Scriptable)result;
Object temp = getElem(thisObj, last);
setElem(resultArray, last - begin, temp);
}
}
} else if (count == 0
&& cx.getLanguageVersion() == Context.VERSION_1_2)
{
/* Emulate C JS1.2; if no elements are removed, return undefined. */
result = Context.getUndefinedValue();
}
/* Find the direction (up or down) to copy and make way for argv. */
long delta = argc - count;
if (delta > 0) {
for (long last = length - 1; last >= end; last--) {
Object temp = getElem(thisObj, last);
setElem(thisObj, last + delta, temp);
}
} else if (delta < 0) {
for (long last = end; last < length; last++) {
Object temp = getElem(thisObj, last);
setElem(thisObj, last + delta, temp);
}
}
/* Copy from argv into the hole to complete the splice. */
int argoffset = args.length - argc;
for (int i = 0; i < argc; i++) {
setElem(thisObj, begin + i, args[i + argoffset]);
}
/* Update length in case we deleted elements from the end. */
ScriptRuntime.setProp(thisObj, "length",
new Double(length + delta), thisObj);
return result;
}
| private static Object js_splice(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
/* create an empty Array to return. */
scope = getTopLevelScope(scope);
Object result = ScriptRuntime.newObject(cx, scope, "Array", null);
int argc = args.length;
if (argc == 0)
return result;
long length = getLengthProperty(thisObj);
/* Convert the first argument into a starting index. */
long begin = toSliceIndex(ScriptRuntime.toInteger(args[0]), length);
argc--;
/* Convert the second argument into count */
long count;
if (args.length == 1) {
count = length - begin;
} else {
double dcount = ScriptRuntime.toInteger(args[1]);
if (dcount < 0) {
count = 0;
} else if (dcount > (length - begin)) {
count = length - begin;
} else {
count = (long)dcount;
}
argc--;
}
long end = begin + count;
/* If there are elements to remove, put them into the return value. */
if (count != 0) {
if (count == 1
&& (cx.getLanguageVersion() == Context.VERSION_1_2))
{
/*
* JS lacks "list context", whereby in Perl one turns the
* single scalar that's spliced out into an array just by
* assigning it to @single instead of $single, or by using it
* as Perl push's first argument, for instance.
*
* JS1.2 emulated Perl too closely and returned a non-Array for
* the single-splice-out case, requiring callers to test and
* wrap in [] if necessary. So JS1.3, default, and other
* versions all return an array of length 1 for uniformity.
*/
result = getElem(thisObj, begin);
} else {
for (long last = begin; last != end; last++) {
Scriptable resultArray = (Scriptable)result;
Object temp = getElem(thisObj, last);
setElem(resultArray, last - begin, temp);
}
}
} else if (count == 0
&& cx.getLanguageVersion() == Context.VERSION_1_2)
{
/* Emulate C JS1.2; if no elements are removed, return undefined. */
result = Context.getUndefinedValue();
}
/* Find the direction (up or down) to copy and make way for argv. */
long delta = argc - count;
if (delta > 0) {
for (long last = length - 1; last >= end; last--) {
Object temp = getElem(thisObj, last);
setElem(thisObj, last + delta, temp);
}
} else if (delta < 0) {
for (long last = end; last < length; last++) {
Object temp = getElem(thisObj, last);
setElem(thisObj, last + delta, temp);
}
}
/* Copy from argv into the hole to complete the splice. */
int argoffset = args.length - argc;
for (int i = 0; i < argc; i++) {
setElem(thisObj, begin + i, args[i + argoffset]);
}
/* Update length in case we deleted elements from the end. */
ScriptRuntime.setProp(thisObj, "length",
new Double(length + delta), thisObj);
return result;
}
|
diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/UpdateListener.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/UpdateListener.java
index e70a71d8a..993e4e7a5 100644
--- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/UpdateListener.java
+++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/UpdateListener.java
@@ -1,175 +1,181 @@
/*******************************************************************************
* Copyright (c) 2000, 2002 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM - Initial API and implementation
******************************************************************************/
package org.eclipse.team.internal.ccvs.core.client.listeners;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.team.internal.ccvs.core.CVSStatus;
import org.eclipse.team.internal.ccvs.core.ICVSFolder;
import org.eclipse.team.internal.ccvs.core.client.Update;
public class UpdateListener implements ICommandOutputListener {
static final String SERVER_PREFIX = "cvs server: "; //$NON-NLS-1$
static final String SERVER_ABORTED_PREFIX = "cvs [server aborted]: "; //$NON-NLS-1$
IUpdateMessageListener updateMessageListener;
boolean merging = false;
public UpdateListener(IUpdateMessageListener updateMessageListener) {
this.updateMessageListener = updateMessageListener;
}
public IStatus messageLine(String line, ICVSFolder commandRoot,
IProgressMonitor monitor) {
if (updateMessageListener == null) return OK;
if(line.startsWith("Merging differences")) { //$NON-NLS-1$
merging = true;
} else if(line.indexOf(' ')==1) {
// We have a message that indicates the type of update. The possible messages are
// defined by the prefix constants MLP_*.
String path = line.substring(2);
char changeType = line.charAt(0);
// calculate change type
int type = 0;
switch(changeType) {
case 'A': type = Update.STATE_ADDED_LOCAL; break; // new file locally that was added but not comitted to server yet
case '?': type = Update.STATE_UNKOWN; break; // new file locally but not added to server
case 'U': type = Update.STATE_REMOTE_CHANGES; break; // remote changes to an unmodified local file
case 'R': type = Update.STATE_DELETED; break; // removed locally but still exists on the server
case 'M': type = Update.STATE_MODIFIED; break; // modified locally
case 'C': type = Update.STATE_CONFLICT; break; // modified locally and on the server but cannot be auto-merged
case 'D': type = Update.STATE_DELETED; break; // deleted locally but still exists on server
default: type = Update.STATE_NONE;
}
if (merging) {
// If we are merging the modified prefix is used both to show merges and
// local changes. We have to detect this case and use a more specific change
// type.
if (type == Update.STATE_MODIFIED)
type = Update.STATE_MERGEABLE_CONFLICT;
merging = false;
}
updateMessageListener.fileInformation(type, commandRoot, path);
}
return OK;
}
/**
* This handler is used by the RemoteResource hierarchy to retrieve E messages
* from the CVS server in order to determine the folders contained in a parent folder.
*
* WARNING: This class parses the message output to determine the state of files in the
* repository. Unfortunately, these messages seem to be customizable on a server by server basis.
*
* Here's a list of responses we expect in various situations:
*
* Directory exists remotely:
* cvs server: Updating folder1/folder2
* Directory doesn't exist remotely:
* cvs server: skipping directory folder1/folder2
* New (or unknown) remote directory
* cvs server: New Directory folder1/folder2
* File removed remotely
* cvs server: folder1/file.ext is no longer in the repository
* cvs server: warning: folder1/file.ext is not (any longer) pertinent
* Locally added file was added remotely as well
* cvs server: conflict: folder/file.ext created independently by second party
* File removed locally and modified remotely
* cvs server: conflict: removed file.txt was modified by second party
* File modified locally but removed remotely
* cvs server: conflict: file.txt is modified but no longer in the repository
* Ignored Messages
* cvs server: cannot open directory ...
* cvs server: nothing known about ...
* Tag error that really means there are no files in a directory
* cvs [server aborted]: no such tag
*/
public IStatus errorLine(String line, ICVSFolder commandRoot,
IProgressMonitor monitor) {
if (line.startsWith(SERVER_PREFIX)) {
// Strip the prefix from the line
String message = line.substring(SERVER_PREFIX.length());
if (message.startsWith("Updating")) { //$NON-NLS-1$
if (updateMessageListener != null) {
IPath path = new Path(message.substring(9));
updateMessageListener.directoryInformation(commandRoot, path, false);
+ return OK;
}
} else if (message.startsWith("skipping directory")) { //$NON-NLS-1$
if (updateMessageListener != null) {
IPath path = new Path(message.substring(18).trim());
updateMessageListener.directoryDoesNotExist(commandRoot, path);
+ return OK;
}
} else if (message.startsWith("New directory")) { //$NON-NLS-1$
if (updateMessageListener != null) {
IPath path = new Path(message.substring(15, message.indexOf('\'', 15)));
updateMessageListener.directoryInformation(commandRoot, path, true);
+ return OK;
}
} else if (message.endsWith("is no longer in the repository")) { //$NON-NLS-1$
if (updateMessageListener != null) {
String filename = message.substring(0, message.length() - 31);
updateMessageListener.fileDoesNotExist(commandRoot, filename);
+ return OK;
}
} else if (message.startsWith("conflict:")) { //$NON-NLS-1$
/*
* We can get the following conflict warnings
* cvs server: conflict: folder/file.ext created independently by second party
* cvs server: conflict: removed file.txt was modified by second party
* cvs server: conflict: file.txt is modified but no longer in the repository
* If we get the above line, we have conflicting additions or deletions and we can expect a server error.
* We still get "C foler/file.ext" so we don't need to do anything else (except in the remotely deleted case)
*/
if (updateMessageListener != null) {
if (message.endsWith("is modified but no longer in the repository")) { //$NON-NLS-1$
// The "C foler/file.ext" will come after this so if whould be ignored!
String filename = message.substring(10, message.length() - 44);
updateMessageListener.fileDoesNotExist(commandRoot, filename);
+ return OK;
}
}
return new CVSStatus(CVSStatus.WARNING, CVSStatus.CONFLICT, line);
} else if (message.startsWith("warning:")) { //$NON-NLS-1$
/*
* We can get the following conflict warnings
* cvs server: warning: folder1/file.ext is not (any longer) pertinent
* If we get the above line, we have local changes to a remotely deleted file.
*/
if (updateMessageListener != null) {
if (message.endsWith("is not (any longer) pertinent")) { //$NON-NLS-1$
String filename = message.substring(9, message.length() - 30);
updateMessageListener.fileDoesNotExist(commandRoot, filename);
+ return OK;
}
}
return new CVSStatus(CVSStatus.WARNING, CVSStatus.CONFLICT, line);
} else if (message.startsWith("conflicts")) { //$NON-NLS-1$
// This line is info only. The server doesn't report an error.
return new CVSStatus(IStatus.INFO, CVSStatus.CONFLICT, line);
} else if (!message.startsWith("cannot open directory") //$NON-NLS-1$
&& !message.startsWith("nothing known about")) { //$NON-NLS-1$
return new CVSStatus(CVSStatus.ERROR, CVSStatus.ERROR_LINE, line);
}
} else if (line.startsWith(SERVER_ABORTED_PREFIX)) {
// Strip the prefix from the line
String message = line.substring(SERVER_ABORTED_PREFIX.length());
if (message.startsWith("no such tag")) { //$NON-NLS-1$
// This is reported from CVS when a tag is used on the update there are no files in the directory
// To get the folders, the update request should be re-issued for HEAD
return new CVSStatus(CVSStatus.WARNING, CVSStatus.NO_SUCH_TAG, line);
} else {
return new CVSStatus(CVSStatus.ERROR, CVSStatus.ERROR_LINE, line);
}
}
- return OK;
+ return new CVSStatus(CVSStatus.ERROR, CVSStatus.ERROR_LINE, line);
}
}
| false | true | public IStatus errorLine(String line, ICVSFolder commandRoot,
IProgressMonitor monitor) {
if (line.startsWith(SERVER_PREFIX)) {
// Strip the prefix from the line
String message = line.substring(SERVER_PREFIX.length());
if (message.startsWith("Updating")) { //$NON-NLS-1$
if (updateMessageListener != null) {
IPath path = new Path(message.substring(9));
updateMessageListener.directoryInformation(commandRoot, path, false);
}
} else if (message.startsWith("skipping directory")) { //$NON-NLS-1$
if (updateMessageListener != null) {
IPath path = new Path(message.substring(18).trim());
updateMessageListener.directoryDoesNotExist(commandRoot, path);
}
} else if (message.startsWith("New directory")) { //$NON-NLS-1$
if (updateMessageListener != null) {
IPath path = new Path(message.substring(15, message.indexOf('\'', 15)));
updateMessageListener.directoryInformation(commandRoot, path, true);
}
} else if (message.endsWith("is no longer in the repository")) { //$NON-NLS-1$
if (updateMessageListener != null) {
String filename = message.substring(0, message.length() - 31);
updateMessageListener.fileDoesNotExist(commandRoot, filename);
}
} else if (message.startsWith("conflict:")) { //$NON-NLS-1$
/*
* We can get the following conflict warnings
* cvs server: conflict: folder/file.ext created independently by second party
* cvs server: conflict: removed file.txt was modified by second party
* cvs server: conflict: file.txt is modified but no longer in the repository
* If we get the above line, we have conflicting additions or deletions and we can expect a server error.
* We still get "C foler/file.ext" so we don't need to do anything else (except in the remotely deleted case)
*/
if (updateMessageListener != null) {
if (message.endsWith("is modified but no longer in the repository")) { //$NON-NLS-1$
// The "C foler/file.ext" will come after this so if whould be ignored!
String filename = message.substring(10, message.length() - 44);
updateMessageListener.fileDoesNotExist(commandRoot, filename);
}
}
return new CVSStatus(CVSStatus.WARNING, CVSStatus.CONFLICT, line);
} else if (message.startsWith("warning:")) { //$NON-NLS-1$
/*
* We can get the following conflict warnings
* cvs server: warning: folder1/file.ext is not (any longer) pertinent
* If we get the above line, we have local changes to a remotely deleted file.
*/
if (updateMessageListener != null) {
if (message.endsWith("is not (any longer) pertinent")) { //$NON-NLS-1$
String filename = message.substring(9, message.length() - 30);
updateMessageListener.fileDoesNotExist(commandRoot, filename);
}
}
return new CVSStatus(CVSStatus.WARNING, CVSStatus.CONFLICT, line);
} else if (message.startsWith("conflicts")) { //$NON-NLS-1$
// This line is info only. The server doesn't report an error.
return new CVSStatus(IStatus.INFO, CVSStatus.CONFLICT, line);
} else if (!message.startsWith("cannot open directory") //$NON-NLS-1$
&& !message.startsWith("nothing known about")) { //$NON-NLS-1$
return new CVSStatus(CVSStatus.ERROR, CVSStatus.ERROR_LINE, line);
}
} else if (line.startsWith(SERVER_ABORTED_PREFIX)) {
// Strip the prefix from the line
String message = line.substring(SERVER_ABORTED_PREFIX.length());
if (message.startsWith("no such tag")) { //$NON-NLS-1$
// This is reported from CVS when a tag is used on the update there are no files in the directory
// To get the folders, the update request should be re-issued for HEAD
return new CVSStatus(CVSStatus.WARNING, CVSStatus.NO_SUCH_TAG, line);
} else {
return new CVSStatus(CVSStatus.ERROR, CVSStatus.ERROR_LINE, line);
}
}
return OK;
}
| public IStatus errorLine(String line, ICVSFolder commandRoot,
IProgressMonitor monitor) {
if (line.startsWith(SERVER_PREFIX)) {
// Strip the prefix from the line
String message = line.substring(SERVER_PREFIX.length());
if (message.startsWith("Updating")) { //$NON-NLS-1$
if (updateMessageListener != null) {
IPath path = new Path(message.substring(9));
updateMessageListener.directoryInformation(commandRoot, path, false);
return OK;
}
} else if (message.startsWith("skipping directory")) { //$NON-NLS-1$
if (updateMessageListener != null) {
IPath path = new Path(message.substring(18).trim());
updateMessageListener.directoryDoesNotExist(commandRoot, path);
return OK;
}
} else if (message.startsWith("New directory")) { //$NON-NLS-1$
if (updateMessageListener != null) {
IPath path = new Path(message.substring(15, message.indexOf('\'', 15)));
updateMessageListener.directoryInformation(commandRoot, path, true);
return OK;
}
} else if (message.endsWith("is no longer in the repository")) { //$NON-NLS-1$
if (updateMessageListener != null) {
String filename = message.substring(0, message.length() - 31);
updateMessageListener.fileDoesNotExist(commandRoot, filename);
return OK;
}
} else if (message.startsWith("conflict:")) { //$NON-NLS-1$
/*
* We can get the following conflict warnings
* cvs server: conflict: folder/file.ext created independently by second party
* cvs server: conflict: removed file.txt was modified by second party
* cvs server: conflict: file.txt is modified but no longer in the repository
* If we get the above line, we have conflicting additions or deletions and we can expect a server error.
* We still get "C foler/file.ext" so we don't need to do anything else (except in the remotely deleted case)
*/
if (updateMessageListener != null) {
if (message.endsWith("is modified but no longer in the repository")) { //$NON-NLS-1$
// The "C foler/file.ext" will come after this so if whould be ignored!
String filename = message.substring(10, message.length() - 44);
updateMessageListener.fileDoesNotExist(commandRoot, filename);
return OK;
}
}
return new CVSStatus(CVSStatus.WARNING, CVSStatus.CONFLICT, line);
} else if (message.startsWith("warning:")) { //$NON-NLS-1$
/*
* We can get the following conflict warnings
* cvs server: warning: folder1/file.ext is not (any longer) pertinent
* If we get the above line, we have local changes to a remotely deleted file.
*/
if (updateMessageListener != null) {
if (message.endsWith("is not (any longer) pertinent")) { //$NON-NLS-1$
String filename = message.substring(9, message.length() - 30);
updateMessageListener.fileDoesNotExist(commandRoot, filename);
return OK;
}
}
return new CVSStatus(CVSStatus.WARNING, CVSStatus.CONFLICT, line);
} else if (message.startsWith("conflicts")) { //$NON-NLS-1$
// This line is info only. The server doesn't report an error.
return new CVSStatus(IStatus.INFO, CVSStatus.CONFLICT, line);
} else if (!message.startsWith("cannot open directory") //$NON-NLS-1$
&& !message.startsWith("nothing known about")) { //$NON-NLS-1$
return new CVSStatus(CVSStatus.ERROR, CVSStatus.ERROR_LINE, line);
}
} else if (line.startsWith(SERVER_ABORTED_PREFIX)) {
// Strip the prefix from the line
String message = line.substring(SERVER_ABORTED_PREFIX.length());
if (message.startsWith("no such tag")) { //$NON-NLS-1$
// This is reported from CVS when a tag is used on the update there are no files in the directory
// To get the folders, the update request should be re-issued for HEAD
return new CVSStatus(CVSStatus.WARNING, CVSStatus.NO_SUCH_TAG, line);
} else {
return new CVSStatus(CVSStatus.ERROR, CVSStatus.ERROR_LINE, line);
}
}
return new CVSStatus(CVSStatus.ERROR, CVSStatus.ERROR_LINE, line);
}
|
diff --git a/goci-diagram/goci-pussycat/src/main/java/uk/ac/ebi/fgpt/goci/pussycat/session/OntologyReasonerSession.java b/goci-diagram/goci-pussycat/src/main/java/uk/ac/ebi/fgpt/goci/pussycat/session/OntologyReasonerSession.java
index 98654524a..b7436f5f2 100644
--- a/goci-diagram/goci-pussycat/src/main/java/uk/ac/ebi/fgpt/goci/pussycat/session/OntologyReasonerSession.java
+++ b/goci-diagram/goci-pussycat/src/main/java/uk/ac/ebi/fgpt/goci/pussycat/session/OntologyReasonerSession.java
@@ -1,103 +1,103 @@
package uk.ac.ebi.fgpt.goci.pussycat.session;
import org.semanticweb.HermiT.Reasoner;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyDocumentAlreadyExistsException;
import org.semanticweb.owlapi.reasoner.*;
import uk.ac.ebi.fgpt.goci.exception.OWLConversionException;
import uk.ac.ebi.fgpt.goci.lang.Initializable;
import uk.ac.ebi.fgpt.goci.lang.OntologyConfiguration;
import uk.ac.ebi.fgpt.goci.lang.OntologyConstants;
import uk.ac.ebi.fgpt.goci.utils.OntologyUtils;
/**
* A simple reasoner session that returns a reasoner over EFO.
*
* @author Tony Burdett
* @date 03/08/12
*/
public class OntologyReasonerSession extends Initializable implements ReasonerSession {
private OntologyConfiguration ontologyConfiguration;
private OWLReasoner reasoner;
public OntologyConfiguration getConfiguration() {
return ontologyConfiguration;
}
public void setConfiguration(OntologyConfiguration ontologyConfiguration) {
this.ontologyConfiguration = ontologyConfiguration;
}
@Override protected void doInitialization() throws Exception {
IRI efoLocationIRI = IRI.create(getConfiguration().getEfoResource().getURI());
- IRI efoLogicalIRI = IRI.create(OntologyConstants.EFO_ONTOLOGY_SCHEMA_IRI + "/");
+ IRI efoLogicalIRI = IRI.create(OntologyConstants.EFO_ONTOLOGY_SCHEMA_IRI);
OWLOntology ontology;
getLog().debug("Trying to create a reasoner over ontology from '" + efoLocationIRI + "'");
try {
ontology = getConfiguration().getOWLOntologyManager().loadOntology(efoLocationIRI);
OntologyUtils.loadImports(getConfiguration().getOWLOntologyManager(), ontology);
StringBuilder loadedOntologies = new StringBuilder();
int n = 1;
for (OWLOntology o : ontology.getOWLOntologyManager().getOntologies()) {
loadedOntologies.append("\t")
.append(n++)
.append(") ")
.append(o.getOntologyID().getOntologyIRI())
.append("\n");
}
getLog().debug("Imports collected: the following ontologies have been loaded in this session:\n" +
loadedOntologies.toString());
}
catch (OWLOntologyDocumentAlreadyExistsException e) {
getLog().debug("Ontology already exists: attempting to retrieve '" + efoLogicalIRI + "'");
if (getConfiguration().getOWLOntologyManager().contains(efoLogicalIRI)) {
ontology = getConfiguration().getOWLOntologyManager().getOntology(efoLogicalIRI);
}
else {
String msg = "Ontology from '" + efoLocationIRI + "' has already been loaded, " +
"but EFO ('" + efoLogicalIRI + "') was not found";
getLog().error(msg);
throw new NullPointerException(msg);
}
}
getLog().info("Classifying ontology from " + efoLogicalIRI);
getLog().debug("Creating reasoner... ");
OWLReasonerFactory factory = new Reasoner.ReasonerFactory();
ConsoleProgressMonitor progressMonitor = new ConsoleProgressMonitor();
OWLReasonerConfiguration config = new SimpleConfiguration(progressMonitor);
reasoner = factory.createReasoner(ontology, config);
getLog().debug("Precomputing inferences...");
reasoner.precomputeInferences();
getLog().debug("Checking ontology consistency...");
reasoner.isConsistent();
getLog().debug("Checking for unsatisfiable classes...");
if (reasoner.getUnsatisfiableClasses().getEntitiesMinusBottom().size() > 0) {
throw new OWLConversionException("Once classified, unsatisfiable classes were detected");
}
else {
getLog().info("Reasoning complete! ");
}
}
@Override public boolean isReasonerInitialized() {
return isReady();
}
@Override public OWLReasoner getReasoner() throws OWLConversionException {
try {
waitUntilReady();
return reasoner;
}
catch (InterruptedException e) {
throw new RuntimeException("Reasoning was interrupted", e);
}
}
}
| true | true | @Override protected void doInitialization() throws Exception {
IRI efoLocationIRI = IRI.create(getConfiguration().getEfoResource().getURI());
IRI efoLogicalIRI = IRI.create(OntologyConstants.EFO_ONTOLOGY_SCHEMA_IRI + "/");
OWLOntology ontology;
getLog().debug("Trying to create a reasoner over ontology from '" + efoLocationIRI + "'");
try {
ontology = getConfiguration().getOWLOntologyManager().loadOntology(efoLocationIRI);
OntologyUtils.loadImports(getConfiguration().getOWLOntologyManager(), ontology);
StringBuilder loadedOntologies = new StringBuilder();
int n = 1;
for (OWLOntology o : ontology.getOWLOntologyManager().getOntologies()) {
loadedOntologies.append("\t")
.append(n++)
.append(") ")
.append(o.getOntologyID().getOntologyIRI())
.append("\n");
}
getLog().debug("Imports collected: the following ontologies have been loaded in this session:\n" +
loadedOntologies.toString());
}
catch (OWLOntologyDocumentAlreadyExistsException e) {
getLog().debug("Ontology already exists: attempting to retrieve '" + efoLogicalIRI + "'");
if (getConfiguration().getOWLOntologyManager().contains(efoLogicalIRI)) {
ontology = getConfiguration().getOWLOntologyManager().getOntology(efoLogicalIRI);
}
else {
String msg = "Ontology from '" + efoLocationIRI + "' has already been loaded, " +
"but EFO ('" + efoLogicalIRI + "') was not found";
getLog().error(msg);
throw new NullPointerException(msg);
}
}
getLog().info("Classifying ontology from " + efoLogicalIRI);
getLog().debug("Creating reasoner... ");
OWLReasonerFactory factory = new Reasoner.ReasonerFactory();
ConsoleProgressMonitor progressMonitor = new ConsoleProgressMonitor();
OWLReasonerConfiguration config = new SimpleConfiguration(progressMonitor);
reasoner = factory.createReasoner(ontology, config);
getLog().debug("Precomputing inferences...");
reasoner.precomputeInferences();
getLog().debug("Checking ontology consistency...");
reasoner.isConsistent();
getLog().debug("Checking for unsatisfiable classes...");
if (reasoner.getUnsatisfiableClasses().getEntitiesMinusBottom().size() > 0) {
throw new OWLConversionException("Once classified, unsatisfiable classes were detected");
}
else {
getLog().info("Reasoning complete! ");
}
}
| @Override protected void doInitialization() throws Exception {
IRI efoLocationIRI = IRI.create(getConfiguration().getEfoResource().getURI());
IRI efoLogicalIRI = IRI.create(OntologyConstants.EFO_ONTOLOGY_SCHEMA_IRI);
OWLOntology ontology;
getLog().debug("Trying to create a reasoner over ontology from '" + efoLocationIRI + "'");
try {
ontology = getConfiguration().getOWLOntologyManager().loadOntology(efoLocationIRI);
OntologyUtils.loadImports(getConfiguration().getOWLOntologyManager(), ontology);
StringBuilder loadedOntologies = new StringBuilder();
int n = 1;
for (OWLOntology o : ontology.getOWLOntologyManager().getOntologies()) {
loadedOntologies.append("\t")
.append(n++)
.append(") ")
.append(o.getOntologyID().getOntologyIRI())
.append("\n");
}
getLog().debug("Imports collected: the following ontologies have been loaded in this session:\n" +
loadedOntologies.toString());
}
catch (OWLOntologyDocumentAlreadyExistsException e) {
getLog().debug("Ontology already exists: attempting to retrieve '" + efoLogicalIRI + "'");
if (getConfiguration().getOWLOntologyManager().contains(efoLogicalIRI)) {
ontology = getConfiguration().getOWLOntologyManager().getOntology(efoLogicalIRI);
}
else {
String msg = "Ontology from '" + efoLocationIRI + "' has already been loaded, " +
"but EFO ('" + efoLogicalIRI + "') was not found";
getLog().error(msg);
throw new NullPointerException(msg);
}
}
getLog().info("Classifying ontology from " + efoLogicalIRI);
getLog().debug("Creating reasoner... ");
OWLReasonerFactory factory = new Reasoner.ReasonerFactory();
ConsoleProgressMonitor progressMonitor = new ConsoleProgressMonitor();
OWLReasonerConfiguration config = new SimpleConfiguration(progressMonitor);
reasoner = factory.createReasoner(ontology, config);
getLog().debug("Precomputing inferences...");
reasoner.precomputeInferences();
getLog().debug("Checking ontology consistency...");
reasoner.isConsistent();
getLog().debug("Checking for unsatisfiable classes...");
if (reasoner.getUnsatisfiableClasses().getEntitiesMinusBottom().size() > 0) {
throw new OWLConversionException("Once classified, unsatisfiable classes were detected");
}
else {
getLog().info("Reasoning complete! ");
}
}
|
diff --git a/bundles/org.eclipse.wst.xsd.ui/src-common/org/eclipse/wst/xsd/ui/internal/common/commands/DeleteCommand.java b/bundles/org.eclipse.wst.xsd.ui/src-common/org/eclipse/wst/xsd/ui/internal/common/commands/DeleteCommand.java
index 500110456..d47f31751 100644
--- a/bundles/org.eclipse.wst.xsd.ui/src-common/org/eclipse/wst/xsd/ui/internal/common/commands/DeleteCommand.java
+++ b/bundles/org.eclipse.wst.xsd.ui/src-common/org/eclipse/wst/xsd/ui/internal/common/commands/DeleteCommand.java
@@ -1,125 +1,131 @@
/*******************************************************************************
* Copyright (c) 2001, 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.wst.xsd.ui.internal.common.commands;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.wst.xsd.ui.internal.adapters.XSDVisitor;
import org.eclipse.xsd.XSDAttributeDeclaration;
import org.eclipse.xsd.XSDAttributeGroupDefinition;
import org.eclipse.xsd.XSDAttributeUse;
import org.eclipse.xsd.XSDComplexTypeDefinition;
import org.eclipse.xsd.XSDConcreteComponent;
import org.eclipse.xsd.XSDElementDeclaration;
import org.eclipse.xsd.XSDEnumerationFacet;
import org.eclipse.xsd.XSDModelGroup;
import org.eclipse.xsd.XSDModelGroupDefinition;
import org.eclipse.xsd.XSDParticle;
import org.eclipse.xsd.XSDSchema;
import org.eclipse.xsd.XSDSimpleTypeDefinition;
public class DeleteCommand extends BaseCommand
{
XSDConcreteComponent target;
public DeleteCommand(String label, XSDConcreteComponent target)
{
super(label);
this.target = target;
}
public void execute()
{
XSDVisitor visitor = new XSDVisitor()
{
public void visitElementDeclaration(org.eclipse.xsd.XSDElementDeclaration element)
{
if (element.getTypeDefinition() == target)
{
XSDSimpleTypeDefinition type = target.getSchema().getSchemaForSchema().resolveSimpleTypeDefinition("string"); //$NON-NLS-1$
element.setTypeDefinition(type);
}
super.visitElementDeclaration(element);
}
};
XSDConcreteComponent parent = target.getContainer();
if (target instanceof XSDModelGroup || target instanceof XSDElementDeclaration || target instanceof XSDModelGroupDefinition)
{
if (parent instanceof XSDParticle)
{
if (parent.getContainer() instanceof XSDModelGroup)
{
XSDModelGroup modelGroup = (XSDModelGroup) ((XSDParticle) parent).getContainer();
modelGroup.getContents().remove(parent);
}
+ else if (parent.getContainer() instanceof XSDComplexTypeDefinition)
+ {
+ XSDComplexTypeDefinition complexType = (XSDComplexTypeDefinition) parent.getContainer();
+ if (complexType.getComplexType() != null)
+ complexType.getComplexType().setContent(null);
+ }
}
else if (parent instanceof XSDSchema)
{
visitor.visitSchema(target.getSchema());
((XSDSchema) parent).getContents().remove(target);
}
}
else if (target instanceof XSDAttributeDeclaration)
{
if (parent instanceof XSDAttributeUse)
{
EObject obj = parent.eContainer();
XSDComplexTypeDefinition complexType = null;
while (obj != null)
{
if (obj instanceof XSDComplexTypeDefinition)
{
complexType = (XSDComplexTypeDefinition) obj;
break;
}
obj = obj.eContainer();
}
if (complexType != null)
{
complexType.getAttributeContents().remove(parent);
}
if (parent.getContainer() instanceof XSDAttributeGroupDefinition)
{
XSDAttributeGroupDefinition attrGroup = (XSDAttributeGroupDefinition) parent.getContainer();
attrGroup.getContents().remove(parent);
}
}
else if (parent instanceof XSDSchema)
{
visitor.visitSchema(target.getSchema());
((XSDSchema) parent).getContents().remove(target);
}
}
else if (target instanceof XSDAttributeGroupDefinition &&
parent instanceof XSDComplexTypeDefinition)
{
((XSDComplexTypeDefinition)parent).getAttributeContents().remove(target);
}
else if (target instanceof XSDEnumerationFacet)
{
XSDEnumerationFacet enumerationFacet = (XSDEnumerationFacet)target;
enumerationFacet.getSimpleTypeDefinition().getFacetContents().remove(enumerationFacet);
}
else
{
if (parent instanceof XSDSchema)
{
visitor.visitSchema(target.getSchema());
((XSDSchema) parent).getContents().remove(target);
}
}
}
}
| true | true | public void execute()
{
XSDVisitor visitor = new XSDVisitor()
{
public void visitElementDeclaration(org.eclipse.xsd.XSDElementDeclaration element)
{
if (element.getTypeDefinition() == target)
{
XSDSimpleTypeDefinition type = target.getSchema().getSchemaForSchema().resolveSimpleTypeDefinition("string"); //$NON-NLS-1$
element.setTypeDefinition(type);
}
super.visitElementDeclaration(element);
}
};
XSDConcreteComponent parent = target.getContainer();
if (target instanceof XSDModelGroup || target instanceof XSDElementDeclaration || target instanceof XSDModelGroupDefinition)
{
if (parent instanceof XSDParticle)
{
if (parent.getContainer() instanceof XSDModelGroup)
{
XSDModelGroup modelGroup = (XSDModelGroup) ((XSDParticle) parent).getContainer();
modelGroup.getContents().remove(parent);
}
}
else if (parent instanceof XSDSchema)
{
visitor.visitSchema(target.getSchema());
((XSDSchema) parent).getContents().remove(target);
}
}
else if (target instanceof XSDAttributeDeclaration)
{
if (parent instanceof XSDAttributeUse)
{
EObject obj = parent.eContainer();
XSDComplexTypeDefinition complexType = null;
while (obj != null)
{
if (obj instanceof XSDComplexTypeDefinition)
{
complexType = (XSDComplexTypeDefinition) obj;
break;
}
obj = obj.eContainer();
}
if (complexType != null)
{
complexType.getAttributeContents().remove(parent);
}
if (parent.getContainer() instanceof XSDAttributeGroupDefinition)
{
XSDAttributeGroupDefinition attrGroup = (XSDAttributeGroupDefinition) parent.getContainer();
attrGroup.getContents().remove(parent);
}
}
else if (parent instanceof XSDSchema)
{
visitor.visitSchema(target.getSchema());
((XSDSchema) parent).getContents().remove(target);
}
}
else if (target instanceof XSDAttributeGroupDefinition &&
parent instanceof XSDComplexTypeDefinition)
{
((XSDComplexTypeDefinition)parent).getAttributeContents().remove(target);
}
else if (target instanceof XSDEnumerationFacet)
{
XSDEnumerationFacet enumerationFacet = (XSDEnumerationFacet)target;
enumerationFacet.getSimpleTypeDefinition().getFacetContents().remove(enumerationFacet);
}
else
{
if (parent instanceof XSDSchema)
{
visitor.visitSchema(target.getSchema());
((XSDSchema) parent).getContents().remove(target);
}
}
}
| public void execute()
{
XSDVisitor visitor = new XSDVisitor()
{
public void visitElementDeclaration(org.eclipse.xsd.XSDElementDeclaration element)
{
if (element.getTypeDefinition() == target)
{
XSDSimpleTypeDefinition type = target.getSchema().getSchemaForSchema().resolveSimpleTypeDefinition("string"); //$NON-NLS-1$
element.setTypeDefinition(type);
}
super.visitElementDeclaration(element);
}
};
XSDConcreteComponent parent = target.getContainer();
if (target instanceof XSDModelGroup || target instanceof XSDElementDeclaration || target instanceof XSDModelGroupDefinition)
{
if (parent instanceof XSDParticle)
{
if (parent.getContainer() instanceof XSDModelGroup)
{
XSDModelGroup modelGroup = (XSDModelGroup) ((XSDParticle) parent).getContainer();
modelGroup.getContents().remove(parent);
}
else if (parent.getContainer() instanceof XSDComplexTypeDefinition)
{
XSDComplexTypeDefinition complexType = (XSDComplexTypeDefinition) parent.getContainer();
if (complexType.getComplexType() != null)
complexType.getComplexType().setContent(null);
}
}
else if (parent instanceof XSDSchema)
{
visitor.visitSchema(target.getSchema());
((XSDSchema) parent).getContents().remove(target);
}
}
else if (target instanceof XSDAttributeDeclaration)
{
if (parent instanceof XSDAttributeUse)
{
EObject obj = parent.eContainer();
XSDComplexTypeDefinition complexType = null;
while (obj != null)
{
if (obj instanceof XSDComplexTypeDefinition)
{
complexType = (XSDComplexTypeDefinition) obj;
break;
}
obj = obj.eContainer();
}
if (complexType != null)
{
complexType.getAttributeContents().remove(parent);
}
if (parent.getContainer() instanceof XSDAttributeGroupDefinition)
{
XSDAttributeGroupDefinition attrGroup = (XSDAttributeGroupDefinition) parent.getContainer();
attrGroup.getContents().remove(parent);
}
}
else if (parent instanceof XSDSchema)
{
visitor.visitSchema(target.getSchema());
((XSDSchema) parent).getContents().remove(target);
}
}
else if (target instanceof XSDAttributeGroupDefinition &&
parent instanceof XSDComplexTypeDefinition)
{
((XSDComplexTypeDefinition)parent).getAttributeContents().remove(target);
}
else if (target instanceof XSDEnumerationFacet)
{
XSDEnumerationFacet enumerationFacet = (XSDEnumerationFacet)target;
enumerationFacet.getSimpleTypeDefinition().getFacetContents().remove(enumerationFacet);
}
else
{
if (parent instanceof XSDSchema)
{
visitor.visitSchema(target.getSchema());
((XSDSchema) parent).getContents().remove(target);
}
}
}
|
diff --git a/src/main/java/net/sf/beezle/sushi/fs/zip/ZipRoot.java b/src/main/java/net/sf/beezle/sushi/fs/zip/ZipRoot.java
index cd5ee189..2d19b16a 100644
--- a/src/main/java/net/sf/beezle/sushi/fs/zip/ZipRoot.java
+++ b/src/main/java/net/sf/beezle/sushi/fs/zip/ZipRoot.java
@@ -1,120 +1,120 @@
/*
* Copyright 1&1 Internet AG, http://www.1and1.org
*
* 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 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.beezle.sushi.fs.zip;
import net.sf.beezle.sushi.archive.Archive;
import net.sf.beezle.sushi.fs.Root;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ZipRoot implements Root<ZipNode> {
private final ZipFilesystem filesystem;
private final ZipFile zip;
public ZipRoot(ZipFilesystem filesystem, ZipFile zip) {
this.filesystem = filesystem;
this.zip = zip;
}
@Override
public boolean equals(Object obj) {
ZipRoot root;
if (obj instanceof ZipRoot) {
root = (ZipRoot) obj;
return filesystem == root.filesystem && zip.equals(root.zip);
}
return false;
}
@Override
public int hashCode() {
return zip.hashCode();
}
public ZipFile getZip() {
return zip;
}
public ZipFilesystem getFilesystem() {
return filesystem;
}
public long getLastModified() {
return new File(zip.getName()).lastModified();
}
public String getId() {
return new File(zip.getName()).toURI() + "!/";
}
public ZipNode node(String path, String encodedQuery) {
if (encodedQuery != null) {
throw new IllegalArgumentException(encodedQuery);
}
return new ZipNode(this, path);
}
// TODO: cache?
public List<String> list(String path) {
ZipEntry entry;
Enumeration<? extends ZipEntry> e;
String name;
String separator;
String prefix;
int length;
List<String> result;
int idx;
e = zip.entries();
separator = getFilesystem().getSeparator();
prefix = path.length() == 0 ? "" : path + separator;
length = prefix.length();
result = new ArrayList<String>();
while (e.hasMoreElements()) {
entry = e.nextElement();
name = entry.getName();
if (name.length() > length && name.startsWith(prefix)) {
idx = name.indexOf(separator, length);
name = (idx == -1 ? name : name.substring(0, idx));
- if (!result.contains(name)) {
+ if (!result.contains(name) && name.length() > 0 /* happens for "/" entries ... */) {
result.add(name);
}
}
}
return result;
}
public Manifest readManifest() throws IOException {
InputStream src;
Manifest result;
src = node(Archive.MANIFEST, null).createInputStream();
result = new Manifest(src);
src.close();
return result;
}
}
| true | true | public List<String> list(String path) {
ZipEntry entry;
Enumeration<? extends ZipEntry> e;
String name;
String separator;
String prefix;
int length;
List<String> result;
int idx;
e = zip.entries();
separator = getFilesystem().getSeparator();
prefix = path.length() == 0 ? "" : path + separator;
length = prefix.length();
result = new ArrayList<String>();
while (e.hasMoreElements()) {
entry = e.nextElement();
name = entry.getName();
if (name.length() > length && name.startsWith(prefix)) {
idx = name.indexOf(separator, length);
name = (idx == -1 ? name : name.substring(0, idx));
if (!result.contains(name)) {
result.add(name);
}
}
}
return result;
}
| public List<String> list(String path) {
ZipEntry entry;
Enumeration<? extends ZipEntry> e;
String name;
String separator;
String prefix;
int length;
List<String> result;
int idx;
e = zip.entries();
separator = getFilesystem().getSeparator();
prefix = path.length() == 0 ? "" : path + separator;
length = prefix.length();
result = new ArrayList<String>();
while (e.hasMoreElements()) {
entry = e.nextElement();
name = entry.getName();
if (name.length() > length && name.startsWith(prefix)) {
idx = name.indexOf(separator, length);
name = (idx == -1 ? name : name.substring(0, idx));
if (!result.contains(name) && name.length() > 0 /* happens for "/" entries ... */) {
result.add(name);
}
}
}
return result;
}
|
diff --git a/src/main/java/org/osiam/resources/helper/UserDeserializer.java b/src/main/java/org/osiam/resources/helper/UserDeserializer.java
index 3c6a2b7..da082c4 100644
--- a/src/main/java/org/osiam/resources/helper/UserDeserializer.java
+++ b/src/main/java/org/osiam/resources/helper/UserDeserializer.java
@@ -1,68 +1,68 @@
package org.osiam.resources.helper;
import java.io.IOException;
import org.osiam.resources.scim.Constants;
import org.osiam.resources.scim.Extension;
import org.osiam.resources.scim.User;
import com.fasterxml.jackson.core.JsonLocation;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class UserDeserializer extends StdDeserializer<User> {
private static final long serialVersionUID = 1L;
public UserDeserializer(Class<?> valueClass) {
super(valueClass);
}
@Override
public User deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
JsonNode rootNode = jp.readValueAsTree();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ExtensionDeserializer deserializer = new ExtensionDeserializer(Extension.class);
- SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null))
+ SimpleModule testModule = new SimpleModule("ExtensionDeserializerModule", Version.unknownVersion())
.addDeserializer(Extension.class, deserializer);
mapper.registerModule(testModule);
User user = mapper.readValue(rootNode.toString(), User.class);
if (user.getSchemas() == null) {
throw new JsonMappingException("Required field Schema is missing");
}
if (user.getSchemas().size() == 1) {
return user;
}
User.Builder builder = new User.Builder(user);
for (String urn : user.getSchemas()) {
if (urn.equals(Constants.CORE_SCHEMA)) {
continue;
}
JsonNode extensionNode = rootNode.get(urn);
if (extensionNode == null) {
throw new JsonParseException("Registered extension not present.", JsonLocation.NA);
}
deserializer.setUrn(urn);
Extension extension = mapper.readValue(extensionNode.toString(), Extension.class);
builder.addExtension(urn, extension);
}
return builder.build();
}
}
| true | true | public User deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
JsonNode rootNode = jp.readValueAsTree();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ExtensionDeserializer deserializer = new ExtensionDeserializer(Extension.class);
SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null))
.addDeserializer(Extension.class, deserializer);
mapper.registerModule(testModule);
User user = mapper.readValue(rootNode.toString(), User.class);
if (user.getSchemas() == null) {
throw new JsonMappingException("Required field Schema is missing");
}
if (user.getSchemas().size() == 1) {
return user;
}
User.Builder builder = new User.Builder(user);
for (String urn : user.getSchemas()) {
if (urn.equals(Constants.CORE_SCHEMA)) {
continue;
}
JsonNode extensionNode = rootNode.get(urn);
if (extensionNode == null) {
throw new JsonParseException("Registered extension not present.", JsonLocation.NA);
}
deserializer.setUrn(urn);
Extension extension = mapper.readValue(extensionNode.toString(), Extension.class);
builder.addExtension(urn, extension);
}
return builder.build();
}
| public User deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
JsonNode rootNode = jp.readValueAsTree();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ExtensionDeserializer deserializer = new ExtensionDeserializer(Extension.class);
SimpleModule testModule = new SimpleModule("ExtensionDeserializerModule", Version.unknownVersion())
.addDeserializer(Extension.class, deserializer);
mapper.registerModule(testModule);
User user = mapper.readValue(rootNode.toString(), User.class);
if (user.getSchemas() == null) {
throw new JsonMappingException("Required field Schema is missing");
}
if (user.getSchemas().size() == 1) {
return user;
}
User.Builder builder = new User.Builder(user);
for (String urn : user.getSchemas()) {
if (urn.equals(Constants.CORE_SCHEMA)) {
continue;
}
JsonNode extensionNode = rootNode.get(urn);
if (extensionNode == null) {
throw new JsonParseException("Registered extension not present.", JsonLocation.NA);
}
deserializer.setUrn(urn);
Extension extension = mapper.readValue(extensionNode.toString(), Extension.class);
builder.addExtension(urn, extension);
}
return builder.build();
}
|
diff --git a/src/Player.java b/src/Player.java
index 649928b..4b7187b 100644
--- a/src/Player.java
+++ b/src/Player.java
@@ -1,97 +1,101 @@
/**
* Player Class.
* This class is in charge of the Player.
* This class has a reference to the current room that the player is in.
* As well, there is a playerHistory variable, in order to undo and redo certain moves.
* This class implements a doCommand method which will take the input command words and correlate them to actual actions.
*
*/
public class Player extends Humanoid {
private PlayerHistory playerHistory;
private Room currentRoom;
public Player(int health, Room r, String name){
super(health, name);
currentRoom = r;
playerHistory = new PlayerHistory();
}
public Player(Room r){
super();
currentRoom = r;
playerHistory = new PlayerHistory();
}
public void doCommand(Command c){
boolean b = false;
if (c.getCommandWord().equals(CommandWords.UNDO)){
c = playerHistory.undo();
b = true;
} else if (c.getCommandWord().equals(CommandWords.REDO)){
c = playerHistory.redo();
b = true;
}
if(c==null){
return; //TODO tell view about it
}
if (c.getCommandWord().equals(CommandWords.GO)){
Direction d = (Direction) c.getSecondWord();
Room r = currentRoom.getExit(d);
if(r!=null){
currentRoom = r;
} // else error TODO
if(b == false){
playerHistory.addStep(c);
}
} else if (c.getCommandWord().equals(CommandWords.FIGHT)){
Monster m = currentRoom.getMonster();
if(m==null){
System.out.println("Nothing to Fight!");
//should probably call the view here..shouldn't be a system.out in this class
} else {
//if(this.getBestItem().compareTo(m.getBestItem()) == 1){
m.updateHealth(this.getBestItem().getValue());
this.updateHealth(m.getBestItem().getValue());
if(m.getHealth()<=0){
currentRoom.removeMonster(m);
}
}
} else if (c.getCommandWord().equals(CommandWords.HELP)){
System.out.println("You are lost. You are alone. You wander around in a cave.\n");
System.out.println("Your command words are:");
System.out.println("GO, PICKUP, DROP, UNDO, REDO, FIGHT, HELP, QUIT");
//HELP may be implemented in another class.
} else if (c.getCommandWord().equals(CommandWords.PICKUP)){
Item i = (Item) c.getSecondWord();
- addItem(i);
+ if(currentRoom.hasItem(i)){
+ addItem(i);
+ }
if(b == false){
playerHistory.addStep(c);
}
} else if (c.getCommandWord().equals(CommandWords.DROP)){
Item i = (Item) c.getSecondWord();
- removeItem(i);
+ if(currentRoom.hasItem(i)){
+ removeItem(i);
+ }
if(b == false){
playerHistory.addStep(c);
}
} else {
//TODO some sort of extraneous error checking
}//QUIT command does not get passed to the player
}
public Room getCurrentRoom(){
return currentRoom;
}
}
| false | true | public void doCommand(Command c){
boolean b = false;
if (c.getCommandWord().equals(CommandWords.UNDO)){
c = playerHistory.undo();
b = true;
} else if (c.getCommandWord().equals(CommandWords.REDO)){
c = playerHistory.redo();
b = true;
}
if(c==null){
return; //TODO tell view about it
}
if (c.getCommandWord().equals(CommandWords.GO)){
Direction d = (Direction) c.getSecondWord();
Room r = currentRoom.getExit(d);
if(r!=null){
currentRoom = r;
} // else error TODO
if(b == false){
playerHistory.addStep(c);
}
} else if (c.getCommandWord().equals(CommandWords.FIGHT)){
Monster m = currentRoom.getMonster();
if(m==null){
System.out.println("Nothing to Fight!");
//should probably call the view here..shouldn't be a system.out in this class
} else {
//if(this.getBestItem().compareTo(m.getBestItem()) == 1){
m.updateHealth(this.getBestItem().getValue());
this.updateHealth(m.getBestItem().getValue());
if(m.getHealth()<=0){
currentRoom.removeMonster(m);
}
}
} else if (c.getCommandWord().equals(CommandWords.HELP)){
System.out.println("You are lost. You are alone. You wander around in a cave.\n");
System.out.println("Your command words are:");
System.out.println("GO, PICKUP, DROP, UNDO, REDO, FIGHT, HELP, QUIT");
//HELP may be implemented in another class.
} else if (c.getCommandWord().equals(CommandWords.PICKUP)){
Item i = (Item) c.getSecondWord();
addItem(i);
if(b == false){
playerHistory.addStep(c);
}
} else if (c.getCommandWord().equals(CommandWords.DROP)){
Item i = (Item) c.getSecondWord();
removeItem(i);
if(b == false){
playerHistory.addStep(c);
}
} else {
//TODO some sort of extraneous error checking
}//QUIT command does not get passed to the player
}
| public void doCommand(Command c){
boolean b = false;
if (c.getCommandWord().equals(CommandWords.UNDO)){
c = playerHistory.undo();
b = true;
} else if (c.getCommandWord().equals(CommandWords.REDO)){
c = playerHistory.redo();
b = true;
}
if(c==null){
return; //TODO tell view about it
}
if (c.getCommandWord().equals(CommandWords.GO)){
Direction d = (Direction) c.getSecondWord();
Room r = currentRoom.getExit(d);
if(r!=null){
currentRoom = r;
} // else error TODO
if(b == false){
playerHistory.addStep(c);
}
} else if (c.getCommandWord().equals(CommandWords.FIGHT)){
Monster m = currentRoom.getMonster();
if(m==null){
System.out.println("Nothing to Fight!");
//should probably call the view here..shouldn't be a system.out in this class
} else {
//if(this.getBestItem().compareTo(m.getBestItem()) == 1){
m.updateHealth(this.getBestItem().getValue());
this.updateHealth(m.getBestItem().getValue());
if(m.getHealth()<=0){
currentRoom.removeMonster(m);
}
}
} else if (c.getCommandWord().equals(CommandWords.HELP)){
System.out.println("You are lost. You are alone. You wander around in a cave.\n");
System.out.println("Your command words are:");
System.out.println("GO, PICKUP, DROP, UNDO, REDO, FIGHT, HELP, QUIT");
//HELP may be implemented in another class.
} else if (c.getCommandWord().equals(CommandWords.PICKUP)){
Item i = (Item) c.getSecondWord();
if(currentRoom.hasItem(i)){
addItem(i);
}
if(b == false){
playerHistory.addStep(c);
}
} else if (c.getCommandWord().equals(CommandWords.DROP)){
Item i = (Item) c.getSecondWord();
if(currentRoom.hasItem(i)){
removeItem(i);
}
if(b == false){
playerHistory.addStep(c);
}
} else {
//TODO some sort of extraneous error checking
}//QUIT command does not get passed to the player
}
|
diff --git a/src/eclipse/plugins/com.ibm.sbt.core/src/com/ibm/sbt/services/client/connections/files/model/FileCreationParameters.java b/src/eclipse/plugins/com.ibm.sbt.core/src/com/ibm/sbt/services/client/connections/files/model/FileCreationParameters.java
index 1e0ee1f49..335902cf5 100644
--- a/src/eclipse/plugins/com.ibm.sbt.core/src/com/ibm/sbt/services/client/connections/files/model/FileCreationParameters.java
+++ b/src/eclipse/plugins/com.ibm.sbt.core/src/com/ibm/sbt/services/client/connections/files/model/FileCreationParameters.java
@@ -1,132 +1,132 @@
package com.ibm.sbt.services.client.connections.files.model;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
/**
* @author Lorenzo Boccaccia
* @date May 28, 2013
*/
public class FileCreationParameters {
/**
* Specifies whether you want to get a notification when someone adds or updates a comment on a file. Options are on or off. The default value is on.
*/
public NotificationFlag commentNotification;
/**
* Date to use as the creation date of the file. This value can be set by the user, and defaults to the current system time on the server.
* Sent as the time in the number of milliseconds since January 1, 1970, 00:00:00 GMT time.
*/
public Date created;
/**
* Specifies whether you want to show the file path to the file. if true,
* adds an entry extension <td:path> element that specifies the file path to the object.
*/
public Boolean includePath;
/**
* Specifies whether the person updating the file wants to get a notification when someone subsequently updates the file.
* Options are on or off. The default value is off.
*/
public NotificationFlag mediaNotification;
public enum NotificationFlag {
ON, OFF
}
/**
* Date to use as the last modified date of the file. This value can be set by the user, and defaults to the current system time on the server.
* Sent as the time in the number of milliseconds since January 1, 1970, 00:00:00 GMT time.
*/
public Date modified;
/**
* Indicates if users that are shared with can share this document. The default value is false.
*/
public Boolean propagate;
/**
* Defines the level of permission that the people listed in the sharedWith parameter have to the file. Only applicable if the sharedWith parameter is passed.
* Permission level options are Edit or View.
* The default value is View.
*/
public Permission sharePermission;
public enum Permission {
EDIT, VIEW
}
/**
* Text. Explanation of the share.
*/
public String shareSummary;
/**
* User ID of the user to share the content with. This parameter can be applied multiple times.
*/
public Collection<String> shareWith = new LinkedList<String>();
/**
* String. Keyword that helps to classify the file. This parameter can be applied multiple times if multiple tags are passed.
*/
public Collection<String> tags = new LinkedList<String>();
/**
* Specifies who can see the file. Options are private or public. A public file is visible to all users and can be shared by all users.
* The default value is private.
*/
public Visibility visibility;
public enum Visibility {
PUBLIC, PRIVATE
}
public Map<String, String> buildParameters() {
Map<String, String> ret = new HashMap<String, String>();
if (commentNotification!=null) {
ret.put("commentNotification", commentNotification.toString().toLowerCase());
}
if (mediaNotification!=null) {
ret.put("mediaNotification", mediaNotification.toString().toLowerCase());
}
if (created!=null) {
ret.put("created", Long.toString(created.getTime()));
}
if (includePath!=null) {
ret.put("includePath", includePath.toString());
}
if (modified!=null) {
ret.put("modified", Long.toString(modified.getTime()));
}
if (propagate!=null) {
ret.put("propagate", propagate.toString());
}
if (sharePermission!=null) {
ret.put("sharePermission", sharePermission.toString().toLowerCase());
}
if (shareSummary!=null) {
ret.put("shareSummary", shareSummary.toString());
}
if (shareWith!=null && shareWith.size()>0) {
if ( shareWith.size()>1)
throw new UnsupportedOperationException("multivalue shareWith args not yet supported");
ret.put("shareWith", shareWith.iterator().next());
}
if (tags!=null && tags.size()>0) {
if ( tags.size()>1)
throw new UnsupportedOperationException("multivalue tags args not yet supported");
- ret.put("tags", tags.iterator().next());
+ ret.put("tag", tags.iterator().next());
}
if (visibility!=null) {
ret.put("visibility", visibility.toString().toLowerCase());
}
return ret;
}
}
| true | true | public Map<String, String> buildParameters() {
Map<String, String> ret = new HashMap<String, String>();
if (commentNotification!=null) {
ret.put("commentNotification", commentNotification.toString().toLowerCase());
}
if (mediaNotification!=null) {
ret.put("mediaNotification", mediaNotification.toString().toLowerCase());
}
if (created!=null) {
ret.put("created", Long.toString(created.getTime()));
}
if (includePath!=null) {
ret.put("includePath", includePath.toString());
}
if (modified!=null) {
ret.put("modified", Long.toString(modified.getTime()));
}
if (propagate!=null) {
ret.put("propagate", propagate.toString());
}
if (sharePermission!=null) {
ret.put("sharePermission", sharePermission.toString().toLowerCase());
}
if (shareSummary!=null) {
ret.put("shareSummary", shareSummary.toString());
}
if (shareWith!=null && shareWith.size()>0) {
if ( shareWith.size()>1)
throw new UnsupportedOperationException("multivalue shareWith args not yet supported");
ret.put("shareWith", shareWith.iterator().next());
}
if (tags!=null && tags.size()>0) {
if ( tags.size()>1)
throw new UnsupportedOperationException("multivalue tags args not yet supported");
ret.put("tags", tags.iterator().next());
}
if (visibility!=null) {
ret.put("visibility", visibility.toString().toLowerCase());
}
return ret;
}
| public Map<String, String> buildParameters() {
Map<String, String> ret = new HashMap<String, String>();
if (commentNotification!=null) {
ret.put("commentNotification", commentNotification.toString().toLowerCase());
}
if (mediaNotification!=null) {
ret.put("mediaNotification", mediaNotification.toString().toLowerCase());
}
if (created!=null) {
ret.put("created", Long.toString(created.getTime()));
}
if (includePath!=null) {
ret.put("includePath", includePath.toString());
}
if (modified!=null) {
ret.put("modified", Long.toString(modified.getTime()));
}
if (propagate!=null) {
ret.put("propagate", propagate.toString());
}
if (sharePermission!=null) {
ret.put("sharePermission", sharePermission.toString().toLowerCase());
}
if (shareSummary!=null) {
ret.put("shareSummary", shareSummary.toString());
}
if (shareWith!=null && shareWith.size()>0) {
if ( shareWith.size()>1)
throw new UnsupportedOperationException("multivalue shareWith args not yet supported");
ret.put("shareWith", shareWith.iterator().next());
}
if (tags!=null && tags.size()>0) {
if ( tags.size()>1)
throw new UnsupportedOperationException("multivalue tags args not yet supported");
ret.put("tag", tags.iterator().next());
}
if (visibility!=null) {
ret.put("visibility", visibility.toString().toLowerCase());
}
return ret;
}
|
diff --git a/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/record/RecordCreateUpdate.java b/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/record/RecordCreateUpdate.java
index 0bdef637..831faf2a 100644
--- a/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/record/RecordCreateUpdate.java
+++ b/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/record/RecordCreateUpdate.java
@@ -1,437 +1,437 @@
/* Copyright 2010 University of Cambridge
* Licensed under the Educational Community License (ECL), Version 2.0. You may not use this file except in
* compliance with this License.
*
* You may obtain a copy of the ECL 2.0 License at https://source.collectionspace.org/collection-space/LICENSE.txt
*/
package org.collectionspace.chain.csp.webui.record;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.collectionspace.chain.csp.config.ConfigException;
import org.collectionspace.chain.csp.schema.Instance;
import org.collectionspace.chain.csp.schema.Record;
import org.collectionspace.chain.csp.schema.Spec;
import org.collectionspace.chain.csp.webui.authorities.AuthoritiesVocabulariesInitialize;
import org.collectionspace.chain.csp.webui.main.Request;
import org.collectionspace.chain.csp.webui.main.WebMethod;
import org.collectionspace.chain.csp.webui.main.WebUI;
import org.collectionspace.chain.csp.webui.misc.Generic;
import org.collectionspace.chain.csp.webui.nuispec.CacheTermList;
import org.collectionspace.csp.api.persistence.ExistException;
import org.collectionspace.csp.api.persistence.Storage;
import org.collectionspace.csp.api.persistence.UnderlyingStorageException;
import org.collectionspace.csp.api.persistence.UnimplementedException;
import org.collectionspace.csp.api.ui.Operation;
import org.collectionspace.csp.api.ui.UIException;
import org.collectionspace.csp.api.ui.UIRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RecordCreateUpdate implements WebMethod {
private static final Logger log=LoggerFactory.getLogger(RecordCreateUpdate.class);
protected String url_base,base;
protected boolean create;
protected Record record;
protected AuthoritiesVocabulariesInitialize avi;
protected Spec spec;
protected RecordRead reader;
protected RecordSearchList searcher;
protected CacheTermList ctl;
public RecordCreateUpdate(Record r,boolean create) {
this.spec=r.getSpec();
this.record = r;
this.url_base=r.getWebURL();
this.base=r.getID();
this.create=create;
this.reader=new RecordRead(r);
this.avi = new AuthoritiesVocabulariesInitialize(r,false);
this.reader.configure(spec);
this.searcher = new RecordSearchList(r,false);
}
private void deleteAllRelations(Storage storage,String csid) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException {
JSONObject r=new JSONObject();
r.put("src",base+"/"+csid);
// XXX needs pagination support CSPACE-1819
JSONObject data = storage.getPathsJSON("relations/main",r);
String[] paths = (String[]) data.get("listItems");
for(String relation : paths) {
storage.deleteJSON("relations/main/"+relation);
}
}
private void setRelations(Storage storage,String csid,JSONArray relations) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException {
deleteAllRelations(storage,csid);
for(int i=0;i<relations.length();i++) {
// Extract data from miniobject
JSONObject in=relations.getJSONObject(i);
String dst_type=spec.getRecordByWebUrl(in.getString("recordtype")).getID();
String dst_id=in.getString("csid");
String type=in.getString("relationshiptype");
// Create relation
JSONObject r=new JSONObject();
r.put("src",base+"/"+csid);
r.put("dst",dst_type+"/"+dst_id);
r.put("type",type);
storage.autocreateJSON("relations/main",r);
}
}
public String sendJSON(Storage storage,String path,JSONObject data) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException {
JSONObject fields=data.optJSONObject("fields");
JSONArray relations=data.optJSONArray("relations");
if(path!=null) {
// Update
if(fields!=null)
storage.updateJSON(base+"/"+path,fields);
} else {
// Create
if(fields!=null)
path=storage.autocreateJSON(base,fields);
}
if(relations!=null)
setRelations(storage,path,relations);
return path;
}
private JSONObject permJSON(String permValue) throws JSONException{
JSONObject perm = new JSONObject();
perm.put("name", permValue);
return perm;
}
private JSONObject getPerm(Storage storage, String resourceName, String permlevel, Boolean isWorkflow) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException{
Record r = Generic.RecordNameServices(spec,resourceName);
JSONObject permitem = new JSONObject();
JSONArray actions = new JSONArray();
JSONArray wf_actions = new JSONArray();
JSONObject permR = permJSON("READ");
JSONObject permC = permJSON("CREATE");
JSONObject permU = permJSON("UPDATE");
JSONObject permD = permJSON("DELETE");
JSONObject permL = permJSON("SEARCH");
///cspace-services/authorization/permissions?res=acquisition&actGrp=CRUDL
String queryString = "CRUDL";
String wf_querystring = "";
if(permlevel.equals("none")){
queryString = "";
actions = new JSONArray();
return permitem;
}
if(permlevel.equals("read")){
queryString = "RL";
actions.put(permR);
actions.put(permL);
}
if(permlevel.equals("write")){
queryString = "CRUL";
actions.put(permC);
actions.put(permR);
actions.put(permU);
actions.put(permL);
}
if(permlevel.equals("delete")){
if(r!=null && r.hasSoftDeleteMethod()){
queryString = "CRUL";
actions.put(permC);
actions.put(permR);
actions.put(permU);
actions.put(permL);
wf_querystring = "CRUDL";
wf_actions.put(permC);
wf_actions.put(permR);
wf_actions.put(permU);
wf_actions.put(permD);
wf_actions.put(permL);
}
else{
queryString = "CRUDL";
actions.put(permC);
actions.put(permR);
actions.put(permU);
actions.put(permD);
actions.put(permL);
}
}
String permbase = spec.getRecordByWebUrl("permission").getID();
if(isWorkflow){
if(r!=null && r.hasSoftDeleteMethod()){
if(wf_querystring.equals("")){
wf_querystring = "RL";
wf_actions.put(permR);
wf_actions.put(permL);
}
permitem = getPermID(storage, Generic.ResourceNameServices(spec, resourceName)+"/*/workflow/", wf_querystring, permbase, wf_actions);
}
}
else{
permitem = getPermID(storage, Generic.ResourceNameServices(spec, resourceName), queryString, permbase, actions);
}
return permitem;
}
private JSONObject getPermID(Storage storage, String name, String queryString, String permbase, JSONArray actions) throws JSONException, UIException, ExistException, UnimplementedException, UnderlyingStorageException{
JSONObject permitem = new JSONObject();
JSONObject wf_permrestrictions = new JSONObject();
wf_permrestrictions.put("keywords", name);
wf_permrestrictions.put("queryTerm", "actGrp");
wf_permrestrictions.put("queryString", queryString);
JSONObject data = searcher.getJSON(storage,wf_permrestrictions,"items",permbase);
String permid = "";
JSONArray items = data.getJSONArray("items");
for(int i=0;i<items.length();i++){
JSONObject item = items.getJSONObject(i);
String resourcename = item.getString("summary");
String actionGroup = item.getString("number");
//need to do a double check as the query is an inexact match
if(resourcename.equals(name) && actionGroup.equals(queryString)){
permid = item.getString("csid");
}
}
if(permid.equals("")){
//create the permission
/**
* {
"effect": "PERMIT",
"resourceName": "testthing2",
"action":[{"name":"CREATE"},{"name":"READ"},{"name":"UPDATE"},{"name":"DELETE"},{"name":"SEARCH"}]
}
*/
JSONObject permission_add = new JSONObject();
permission_add.put("effect", "PERMIT");
permission_add.put("description", "created because we couldn't find a match");
permission_add.put("resourceName", name);
permission_add.put("actionGroup", queryString);
permission_add.put("action", actions);
permid=storage.autocreateJSON(spec.getRecordByWebUrl("permission").getID(),permission_add);
}
if(!permid.equals("")){
permitem.put("resourceName", name);
permitem.put("permissionId", permid);
permitem.put("actionGroup", queryString);
}
return permitem;
}
private void assignTerms(Storage storage, String path, JSONObject data) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException{
JSONObject fields=data.optJSONObject("fields");
String insId = "";
if(fields.has("terms")){
Record vr = this.spec.getRecord("vocab");
Record thisr = spec.getRecord("vocab");
String sid = fields.getString("shortIdentifier");
String name = fields.getString("displayName");
insId = "vocab-"+sid;
if(create){
Map<String,String> options=new HashMap<String,String>();
options.put("id", insId);
options.put("title", name);
options.put("web-url", sid);
options.put("title-ref", sid);
Instance ins=new Instance(thisr, options);
vr.addInstance(ins);
}
ctl.get(storage, sid,vr,0);
}
}
private void assignPermissions(Storage storage, String path, JSONObject data) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException{
JSONObject fields=data.optJSONObject("fields");
JSONArray permdata = new JSONArray();
JSONObject permcheck = new JSONObject();
if(fields.has("permissions")){
JSONArray permissions = fields.getJSONArray("permissions");
for(int i=0;i<permissions.length();i++){
JSONObject perm = permissions.getJSONObject(i);
Record r = Generic.RecordNameServices(spec,perm.getString("resourceName"));
//if(r!=null){
if(r!=null && r.hasSoftDeleteMethod()){
JSONObject permitem = getPerm(storage,perm.getString("resourceName"),perm.getString("permission"),true);
if(permitem.has("permissionId")){
if(permcheck.has(permitem.getString("resourceName"))){
//ignore as we have duplicate name - eek
}else{
permcheck.put(permitem.getString("resourceName"), permitem);
permdata.put(permitem);
}
}
}
JSONObject permitem = getPerm(storage,perm.getString("resourceName"),perm.getString("permission"),false);
if(permitem.has("permissionId")){
if(permcheck.has(permitem.getString("resourceName"))){
//ignore as we have duplicate name - eek
}else{
permcheck.put(permitem.getString("resourceName"), permitem);
permdata.put(permitem);
}
}
//}
}
}
//log.info("permdata"+permdata.toString());
JSONObject roledata = new JSONObject();
roledata.put("roleName", fields.getString("roleName"));
String[] ids=path.split("/");
roledata.put("roleId", ids[ids.length - 1]);
JSONObject accountrole = new JSONObject();
JSONObject arfields = new JSONObject();
arfields.put("role", roledata);
arfields.put("permission", permdata);
accountrole.put("fields", arfields);
//log.info("WAAA"+arfields.toString());
if(fields!=null)
path=storage.autocreateJSON(spec.getRecordByWebUrl("permrole").getID(),arfields);
}
private void store_set(Storage storage,UIRequest request,String path) throws UIException {
try {
JSONObject data=request.getJSONBody();
if(this.base.equals("role")){
JSONObject fields=data.optJSONObject("fields");
if((fields.optString("roleName") == null || fields.optString("roleName").equals("")) && fields.optString("displayName") !=null){
String test = fields.optString("displayName");
test = test.toUpperCase();
test.replaceAll("\\W", "_");
fields.put("roleName", "ROLE_"+test);
data.put("fields", fields);
}
}
if(this.record.getID().equals("media")){
JSONObject fields=data.optJSONObject("fields");
if(fields.has("srcUri")){
//is this internal or external?
//XXX HACK as ervice layer having issues with external urls
String uri = fields.getString("srcUri");
/*
String baseurl = "http://nightly.collectionspace.org:8180/cspace-services/blobs/";
if(uri.startsWith(baseurl)){
uri = uri.replace(baseurl, "");
String[] parts = uri.split("/");
fields.put("blobCsid",parts[0]);
fields.remove("srcUri");
}
*/
String[] parts = uri.split("/blobs/");
String[] bits = parts[1].split("/");
fields.put("blobCsid",bits[0]);
fields.remove("srcUri");
data.put("fields", fields);
}
}
if(this.record.getID().equals("output")){
//do a read instead of a create as reports are special and evil
JSONObject fields=data.optJSONObject("fields");
JSONObject payload = new JSONObject();
payload.put("mode", "single");
if(fields.has("mode")){
payload.put("mode", fields.getString("mode"));
}
if(fields.has("docType")){
String type = spec.getRecordByWebUrl(fields.getString("docType")).getServicesTenantSg();
payload.put("docType", type);
}
if(fields.has("singleCSID")){
payload.put("singleCSID", fields.getString("singleCSID"));
}
else if(fields.has("groupCSID")){
payload.put("singleCSID", fields.getString("csid"));
}
JSONObject out=storage.retrieveJSON(base+"/"+path,payload);
byte[] data_array = (byte[])out.get("getByteBody");
request.sendUnknown(data_array,out.getString("contenttype"));
//request.sendJSONResponse(out);
request.setOperationPerformed(create?Operation.CREATE:Operation.UPDATE);
}
else{
if(create) {
path=sendJSON(storage,null,data);
data.put("csid",path);
data.getJSONObject("fields").put("csid",path);
} else
path=sendJSON(storage,path,data);
if(path==null)
throw new UIException("Insufficient data for create (no fields?)");
if(this.base.equals("role")){
assignPermissions(storage,path,data);
}
if(this.base.equals("termlist")){
assignTerms(storage,path,data);
}
data=reader.getJSON(storage,path);
request.sendJSONResponse(data);
request.setOperationPerformed(create?Operation.CREATE:Operation.UPDATE);
if(create)
request.setSecondaryRedirectPath(new String[]{url_base,path});
}
} catch (JSONException x) {
throw new UIException("Failed to parse json: "+x,x);
} catch (ExistException x) {
- UIException uiexception = new UIException(x.getMessage(),400,"",x);
+ UIException uiexception = new UIException(x.getMessage(),0,"",x);
request.sendJSONResponse(uiexception.getJSON());
} catch (UnimplementedException x) {
throw new UIException("Unimplemented exception: "+x,x);
} catch (UnderlyingStorageException x) {
UIException uiexception = new UIException(x.getMessage(),x.getStatus(),x.getUrl(),x);
request.sendJSONResponse(uiexception.getJSON());
}catch (Exception x) {
throw new UIException(x);
}
}
public void run(Object in, String[] tail) throws UIException {
Request q=(Request)in;
ctl = new CacheTermList(q.getCache());
store_set(q.getStorage(),q.getUIRequest(),StringUtils.join(tail,"/"));
}
public void configure() throws ConfigException {}
public void configure(WebUI ui,Spec spec) {}
}
| true | true | private void store_set(Storage storage,UIRequest request,String path) throws UIException {
try {
JSONObject data=request.getJSONBody();
if(this.base.equals("role")){
JSONObject fields=data.optJSONObject("fields");
if((fields.optString("roleName") == null || fields.optString("roleName").equals("")) && fields.optString("displayName") !=null){
String test = fields.optString("displayName");
test = test.toUpperCase();
test.replaceAll("\\W", "_");
fields.put("roleName", "ROLE_"+test);
data.put("fields", fields);
}
}
if(this.record.getID().equals("media")){
JSONObject fields=data.optJSONObject("fields");
if(fields.has("srcUri")){
//is this internal or external?
//XXX HACK as ervice layer having issues with external urls
String uri = fields.getString("srcUri");
/*
String baseurl = "http://nightly.collectionspace.org:8180/cspace-services/blobs/";
if(uri.startsWith(baseurl)){
uri = uri.replace(baseurl, "");
String[] parts = uri.split("/");
fields.put("blobCsid",parts[0]);
fields.remove("srcUri");
}
*/
String[] parts = uri.split("/blobs/");
String[] bits = parts[1].split("/");
fields.put("blobCsid",bits[0]);
fields.remove("srcUri");
data.put("fields", fields);
}
}
if(this.record.getID().equals("output")){
//do a read instead of a create as reports are special and evil
JSONObject fields=data.optJSONObject("fields");
JSONObject payload = new JSONObject();
payload.put("mode", "single");
if(fields.has("mode")){
payload.put("mode", fields.getString("mode"));
}
if(fields.has("docType")){
String type = spec.getRecordByWebUrl(fields.getString("docType")).getServicesTenantSg();
payload.put("docType", type);
}
if(fields.has("singleCSID")){
payload.put("singleCSID", fields.getString("singleCSID"));
}
else if(fields.has("groupCSID")){
payload.put("singleCSID", fields.getString("csid"));
}
JSONObject out=storage.retrieveJSON(base+"/"+path,payload);
byte[] data_array = (byte[])out.get("getByteBody");
request.sendUnknown(data_array,out.getString("contenttype"));
//request.sendJSONResponse(out);
request.setOperationPerformed(create?Operation.CREATE:Operation.UPDATE);
}
else{
if(create) {
path=sendJSON(storage,null,data);
data.put("csid",path);
data.getJSONObject("fields").put("csid",path);
} else
path=sendJSON(storage,path,data);
if(path==null)
throw new UIException("Insufficient data for create (no fields?)");
if(this.base.equals("role")){
assignPermissions(storage,path,data);
}
if(this.base.equals("termlist")){
assignTerms(storage,path,data);
}
data=reader.getJSON(storage,path);
request.sendJSONResponse(data);
request.setOperationPerformed(create?Operation.CREATE:Operation.UPDATE);
if(create)
request.setSecondaryRedirectPath(new String[]{url_base,path});
}
} catch (JSONException x) {
throw new UIException("Failed to parse json: "+x,x);
} catch (ExistException x) {
UIException uiexception = new UIException(x.getMessage(),400,"",x);
request.sendJSONResponse(uiexception.getJSON());
} catch (UnimplementedException x) {
throw new UIException("Unimplemented exception: "+x,x);
} catch (UnderlyingStorageException x) {
UIException uiexception = new UIException(x.getMessage(),x.getStatus(),x.getUrl(),x);
request.sendJSONResponse(uiexception.getJSON());
}catch (Exception x) {
throw new UIException(x);
}
}
| private void store_set(Storage storage,UIRequest request,String path) throws UIException {
try {
JSONObject data=request.getJSONBody();
if(this.base.equals("role")){
JSONObject fields=data.optJSONObject("fields");
if((fields.optString("roleName") == null || fields.optString("roleName").equals("")) && fields.optString("displayName") !=null){
String test = fields.optString("displayName");
test = test.toUpperCase();
test.replaceAll("\\W", "_");
fields.put("roleName", "ROLE_"+test);
data.put("fields", fields);
}
}
if(this.record.getID().equals("media")){
JSONObject fields=data.optJSONObject("fields");
if(fields.has("srcUri")){
//is this internal or external?
//XXX HACK as ervice layer having issues with external urls
String uri = fields.getString("srcUri");
/*
String baseurl = "http://nightly.collectionspace.org:8180/cspace-services/blobs/";
if(uri.startsWith(baseurl)){
uri = uri.replace(baseurl, "");
String[] parts = uri.split("/");
fields.put("blobCsid",parts[0]);
fields.remove("srcUri");
}
*/
String[] parts = uri.split("/blobs/");
String[] bits = parts[1].split("/");
fields.put("blobCsid",bits[0]);
fields.remove("srcUri");
data.put("fields", fields);
}
}
if(this.record.getID().equals("output")){
//do a read instead of a create as reports are special and evil
JSONObject fields=data.optJSONObject("fields");
JSONObject payload = new JSONObject();
payload.put("mode", "single");
if(fields.has("mode")){
payload.put("mode", fields.getString("mode"));
}
if(fields.has("docType")){
String type = spec.getRecordByWebUrl(fields.getString("docType")).getServicesTenantSg();
payload.put("docType", type);
}
if(fields.has("singleCSID")){
payload.put("singleCSID", fields.getString("singleCSID"));
}
else if(fields.has("groupCSID")){
payload.put("singleCSID", fields.getString("csid"));
}
JSONObject out=storage.retrieveJSON(base+"/"+path,payload);
byte[] data_array = (byte[])out.get("getByteBody");
request.sendUnknown(data_array,out.getString("contenttype"));
//request.sendJSONResponse(out);
request.setOperationPerformed(create?Operation.CREATE:Operation.UPDATE);
}
else{
if(create) {
path=sendJSON(storage,null,data);
data.put("csid",path);
data.getJSONObject("fields").put("csid",path);
} else
path=sendJSON(storage,path,data);
if(path==null)
throw new UIException("Insufficient data for create (no fields?)");
if(this.base.equals("role")){
assignPermissions(storage,path,data);
}
if(this.base.equals("termlist")){
assignTerms(storage,path,data);
}
data=reader.getJSON(storage,path);
request.sendJSONResponse(data);
request.setOperationPerformed(create?Operation.CREATE:Operation.UPDATE);
if(create)
request.setSecondaryRedirectPath(new String[]{url_base,path});
}
} catch (JSONException x) {
throw new UIException("Failed to parse json: "+x,x);
} catch (ExistException x) {
UIException uiexception = new UIException(x.getMessage(),0,"",x);
request.sendJSONResponse(uiexception.getJSON());
} catch (UnimplementedException x) {
throw new UIException("Unimplemented exception: "+x,x);
} catch (UnderlyingStorageException x) {
UIException uiexception = new UIException(x.getMessage(),x.getStatus(),x.getUrl(),x);
request.sendJSONResponse(uiexception.getJSON());
}catch (Exception x) {
throw new UIException(x);
}
}
|
diff --git a/branches/4.0.0/Crux/src/br/com/sysmap/crux/core/rebind/widget/creator/align/HorizontalAlignmentAttributeParser.java b/branches/4.0.0/Crux/src/br/com/sysmap/crux/core/rebind/widget/creator/align/HorizontalAlignmentAttributeParser.java
index aef214ad3..448d74e60 100644
--- a/branches/4.0.0/Crux/src/br/com/sysmap/crux/core/rebind/widget/creator/align/HorizontalAlignmentAttributeParser.java
+++ b/branches/4.0.0/Crux/src/br/com/sysmap/crux/core/rebind/widget/creator/align/HorizontalAlignmentAttributeParser.java
@@ -1,37 +1,37 @@
/*
* Copyright 2009 Sysmap Solutions Software e Consultoria Ltda.
*
* 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 br.com.sysmap.crux.core.rebind.widget.creator.align;
import br.com.sysmap.crux.core.rebind.widget.AttributeProcessor;
import br.com.sysmap.crux.core.rebind.widget.ViewFactoryCreator.SourcePrinter;
import br.com.sysmap.crux.core.rebind.widget.WidgetCreatorContext;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
/**
*
* @author Thiago da Rosa de Bustamante
*
*/
public class HorizontalAlignmentAttributeParser<C extends WidgetCreatorContext> extends AttributeProcessor<C>
{
@Override
public void processAttribute(SourcePrinter out, C context, String attributeValue)
{
out.println(context.getWidget()+".setHorizontalAlignment("+
- AlignmentAttributeParser.getHorizontalAlignment(attributeValue, HasHorizontalAlignment.class.getCanonicalName()+".ALIGN_DEFAULT"));
+ AlignmentAttributeParser.getHorizontalAlignment(attributeValue, HasHorizontalAlignment.class.getCanonicalName()+".ALIGN_DEFAULT")+");");
}
}
| true | true | public void processAttribute(SourcePrinter out, C context, String attributeValue)
{
out.println(context.getWidget()+".setHorizontalAlignment("+
AlignmentAttributeParser.getHorizontalAlignment(attributeValue, HasHorizontalAlignment.class.getCanonicalName()+".ALIGN_DEFAULT"));
}
| public void processAttribute(SourcePrinter out, C context, String attributeValue)
{
out.println(context.getWidget()+".setHorizontalAlignment("+
AlignmentAttributeParser.getHorizontalAlignment(attributeValue, HasHorizontalAlignment.class.getCanonicalName()+".ALIGN_DEFAULT")+");");
}
|
diff --git a/src/de/escidoc/sb/srw/EscidocSRWDatabaseImpl.java b/src/de/escidoc/sb/srw/EscidocSRWDatabaseImpl.java
index 86c4419..2f6d67e 100644
--- a/src/de/escidoc/sb/srw/EscidocSRWDatabaseImpl.java
+++ b/src/de/escidoc/sb/srw/EscidocSRWDatabaseImpl.java
@@ -1,565 +1,568 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at license/ESCIDOC.LICENSE
* or http://www.escidoc.de/license.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at license/ESCIDOC.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2006-2007 Fachinformationszentrum Karlsruhe Gesellschaft
* für wissenschaftlich-technische Information mbH and Max-Planck-
* Gesellschaft zur Förderung der Wissenschaft e.V.
* All rights reserved. Use is subject to license terms.
*/
package de.escidoc.sb.srw;
import gov.loc.www.zing.srw.ExtraDataType;
import gov.loc.www.zing.srw.RecordType;
import gov.loc.www.zing.srw.RecordsType;
import gov.loc.www.zing.srw.SearchRetrieveRequestType;
import gov.loc.www.zing.srw.SearchRetrieveResponseType;
import gov.loc.www.zing.srw.StringOrXmlFragment;
import java.io.StringReader;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import javax.servlet.ServletException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.axis.MessageContext;
import org.apache.axis.message.MessageElement;
import org.apache.axis.message.Text;
import org.apache.axis.types.NonNegativeInteger;
import org.apache.axis.types.PositiveInteger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osuosl.srw.ResolvingQueryResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.z3950.zing.cql.CQLNode;
import org.z3950.zing.cql.CQLParseException;
import ORG.oclc.os.SRW.Record;
import ORG.oclc.os.SRW.RecordIterator;
import ORG.oclc.os.SRW.SRWDiagnostic;
import de.escidoc.sb.srw.lucene.EscidocLuceneTranslator;
/**
* Class overwrites org.osuosl.srw.SRWDatabaseImpl. This is done because: -we
* dont retrieve and store all search-hits but only the ones requested -we dont
* use result-sets -we do sorting while querying lucene and not afterwards -get
* dynamic index-info from available lucene-fields
*
* @author MIH
* @sb
*/
public class EscidocSRWDatabaseImpl extends org.osuosl.srw.SRWDatabaseImpl {
private static Log log = LogFactory.getLog(EscidocSRWDatabaseImpl.class);
private static final int DIAGNOSTIC_CODE_EIGHT = 8;
private static final int DIAGNOSTIC_CODE_SEVENTY_ONE = 71;
private static final int TEN = 10;
private static final int ELEVEN = 11;
private static final int MILLISECONDS_PER_SECOND = 1000;
/**
* execute search -> get results. getRecordIterator from results. iterate
* over results, get records, put records into response.
*
* @param request
* SearchRetrieveRequestType
* @return SearchRetrieveResponseType response
* @throws ServletException
* e
* @sb
*/
public SearchRetrieveResponseType doRequest(
final SearchRetrieveRequestType request) throws ServletException {
SearchRetrieveResponseType response = null; // search response
int resultSetTTL; // time result set should expire
String recordPacking; // how record is packed (xml|string)
String query; // Search String
String sortKeysString; // keys to sort on
PositiveInteger startRec; // record number to start with
ExtraDataType extraData = null; // extra params sent with request
ResolvingQueryResult results; // results of search, array of
// Ids/handles
try {
MessageContext msgContext = MessageContext.getCurrentContext();
response = new SearchRetrieveResponseType();
response.setNumberOfRecords(new NonNegativeInteger("0"));
startRec = request.getStartRecord();
extraData = request.getExtraRequestData();
/**
* Get schema name and verify its supported.
*/
String schemaName = request.getRecordSchema();
if (schemaName == null) {
schemaName = "default";
}
log.info("recordSchema=" + schemaName);
if (schemaName != null && !schemaName.equals(DEFAULT_SCHEMA)) {
if (!getResolver().containsSchema(schemaName)) {
log.error("no handler for schema " + schemaName);
return diagnostic(SRWDiagnostic.UnknownSchemaForRetrieval,
schemaName, response);
}
}
/**
* RecordXPath - UNSUPPORTED
*/
if (request.getRecordXPath() != null
&& request.getRecordXPath().trim().length() != 0) {
return diagnostic(
DIAGNOSTIC_CODE_EIGHT, request.getRecordXPath(), response);
}
/**
* set result set TTL
*/
if (request.getResultSetTTL() != null) {
resultSetTTL = request.getResultSetTTL().intValue();
}
else {
resultSetTTL = defaultResultSetTTL;
}
/**
* Set Record Packing
*/
recordPacking = request.getRecordPacking();
if (recordPacking == null) {
if (msgContext != null && msgContext.getProperty("sru") != null) {
recordPacking = "xml"; // default for sru
}
else {
recordPacking = "string"; // default for srw
}
}
/**
* get sort keys
*/
sortKeysString = request.getSortKeys();
if (sortKeysString != null && sortKeysString.length() == 0) {
sortKeysString = null;
}
/**
* Parse and Execute Query
*/
query = request.getQuery();
try {
log.info("search:\n"
+ ORG.oclc.util.Util.byteArrayToString(query
.getBytes("UTF-8")));
}
catch (Exception e) {
log.info(e);
}
CQLNode queryRoot = null;
+ if (query.matches(".*[^\\\\]\".*")) {
+ query = escapeBackslash(query);
+ }
try {
- queryRoot = parser.parse(escapeBackslash(query));
+ queryRoot = parser.parse(query);
}
catch (CQLParseException e) {
return diagnostic(SRWDiagnostic.QuerySyntaxError, e
.getMessage(), response);
}
String resultSetID = queryRoot.getResultSetName();
int numRecs = defaultNumRecs;
NonNegativeInteger maxRecs = request.getMaximumRecords();
if (maxRecs != null) {
numRecs =
(int) java.lang.Math.min(maxRecs.longValue(),
maximumRecords);
}
// MIH: set maxRecs in request, because request
// gets passed to EscidocLuceneTranslator
// EscidocLuceneTranslator performs search and fills identifers
request.setMaximumRecords(new NonNegativeInteger(Integer
.toString(numRecs)));
int startPoint = 1;
if (startRec != null) {
startPoint = (int) startRec.longValue();
}
if (resultSetID != null) {
// look for existing result set
log.info("resultSetID=" + resultSetID);
results = (ResolvingQueryResult) oldResultSets.get(resultSetID);
if (results == null) {
return diagnostic(SRWDiagnostic.ResultSetDoesNotExist,
resultSetID, response);
}
}
else {
// MIH: call overwritten method that is only available in
// EscidocLuceneTranslator:
// 3rd parameter: request (to get sortKeys,
// startRecord, maxRecords..)!
results =
(ResolvingQueryResult) (
(EscidocLuceneTranslator) getCQLTranslator())
.search(queryRoot, extraData, request);
results.setResolver(getResolver());
results.setExtraDataType(extraData);
/**
* if results were found save the result set and setup the timer
* for when it expires
*
*/
if (results.getNumberOfRecords() > 0 && resultSetTTL > 0) {
resultSetID = makeResultSetID();
oldResultSets.put(resultSetID, results);
log.info("keeping resultSet '" + resultSetID + "' for "
+ resultSetTTL + " seconds");
timers.put(resultSetID, new Long(System.currentTimeMillis()
+ (resultSetTTL * MILLISECONDS_PER_SECOND)));
response.setResultSetId(resultSetID);
response.setResultSetIdleTime(new PositiveInteger(Integer
.toString(resultSetTTL)));
}
}
int postings = (int) results.getNumberOfRecords();
response.setNumberOfRecords(new NonNegativeInteger(Long
.toString(postings)));
log.info("'" + query + "'==> " + postings);
if (postings > 0 && startPoint > postings) {
diagnostic(SRWDiagnostic.FirstRecordPositionOutOfRange, null,
response);
}
if ((startPoint - 1 + numRecs) > postings) {
numRecs = postings - (startPoint - 1);
}
if (postings > 0 && numRecs == 0) {
response.setNextRecordPosition(new PositiveInteger("1"));
}
if (postings > 0 && numRecs > 0) { // render some records into SGML
RecordsType records = new RecordsType();
log.info("trying to get " + numRecs
+ " records starting with record " + startPoint
+ " from a set of " + postings + " records");
if (!recordPacking.equals("xml")
&& !recordPacking.equals("string")) {
return diagnostic(
DIAGNOSTIC_CODE_SEVENTY_ONE, recordPacking, response);
}
records.setRecord(new RecordType[numRecs]);
Document domDoc;
DocumentBuilder db = null;
DocumentBuilderFactory dbf = null;
int i = -1;
MessageElement[] elems;
RecordType record;
StringOrXmlFragment frag;
if (recordPacking.equals("xml")) {
dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
db = dbf.newDocumentBuilder();
}
/**
* One at a time, retrieve and display the requested documents.
*/
RecordIterator list = null;
try {
log.info("making RecordIterator, startPoint=" + startPoint
+ ", schemaID=" + schemaName);
list =
results.recordIterator(startPoint - 1, numRecs,
schemaName);
}
catch (InstantiationException e) {
diagnostic(SRWDiagnostic.GeneralSystemError,
e.getMessage(), response);
}
for (i = 0; list.hasNext(); i++) {
try {
Record rec = list.nextRecord();
/**
* create record container
*/
record = new RecordType();
record.setRecordPacking(recordPacking);
frag = new StringOrXmlFragment();
elems = new MessageElement[1];
frag.set_any(elems);
record.setRecordSchema(rec.getRecordSchemaID());
if (recordPacking.equals("xml")) {
domDoc =
db.parse(new InputSource(new StringReader(rec
.getRecord())));
Element el = domDoc.getDocumentElement();
log.debug("got the DocumentElement");
elems[0] = new MessageElement(el);
log.debug("put the domDoc into elems[0]");
}
else { // string
Text t = new Text(rec.getRecord());
elems[0] = new MessageElement(t);
}
record.setRecordData(frag);
log.debug("setRecordData");
record.setRecordPosition(new PositiveInteger(Integer
.toString(startPoint + i)));
records.setRecord(i, record);
}
catch (NoSuchElementException e) {
log.error("Read beyond the end of list!!");
log.error(e);
break;
}
response.setRecords(records);
}
if (startPoint + i <= postings) {
response.setNextRecordPosition(new PositiveInteger(Long
.toString(startPoint + i)));
}
}
log.debug("exit doRequest");
return response;
}
catch (Exception e) {
return diagnostic(SRWDiagnostic.GeneralSystemError, e.getMessage(),
response);
}
}
/**
* returns info about databases for explainPlan.
* Overwritten because schema 2.0 doesnt allow
* attribute indentifier in element implementation
*
* @return String databaseInfo xml for explainPlan
* @sb
*/
public String getDatabaseInfo() {
StringBuffer sb=new StringBuffer();
sb.append(" <databaseInfo>\n");
if(dbProperties!=null) {
String t=dbProperties.getProperty("databaseInfo.title");
if(t!=null)
sb.append(" <title>").append(t).append("</title>\n");
t=dbProperties.getProperty("databaseInfo.description");
if(t!=null)
sb.append(" <description>").append(t).append("</description>\n");
t=dbProperties.getProperty("databaseInfo.author");
if(t!=null)
sb.append(" <author>").append(t).append("</author>\n");
t=dbProperties.getProperty("databaseInfo.contact");
if(t!=null)
sb.append(" <contact>").append(t).append("</contact>\n");
t=dbProperties.getProperty("databaseInfo.restrictions");
if(t!=null)
sb.append(" <restrictions>").append(t).append("</restrictions>\n");
}
sb.append(" <implementation version='1.1'>\n");
sb.append(" <title>OCLC Research SRW Server version 1.1</title>\n");
sb.append(" </implementation>\n");
sb.append(" </databaseInfo>\n");
return sb.toString();
}
/**
* returns info about metaInfo for explainPlan.
* Overwritten because schema 2.0 needs attribute dateModified
* if element metaInfo is set.
*
* @return String databaseInfo xml for explainPlan
* @sb
*/
public String getMetaInfo() {
StringBuffer sb=new StringBuffer();
boolean writeElement = false;
sb.append(" <metaInfo>\n");
if(dbProperties!=null) {
String t=dbProperties.getProperty("metaInfo.dateModified");
if(t!=null) {
sb.append(" <dateModified>").append(t).append("</dateModified>\n");
writeElement = true;
}
t=dbProperties.getProperty("metaInfo.aggregatedFrom");
if(t!=null) {
sb.append(" <aggregatedFrom>").append(t).append("</aggregatedFrom>\n");
}
t=dbProperties.getProperty("metaInfo.dateAggregated");
if(t!=null) {
sb.append(" <dateAggregated>").append(t).append("</dateAggregated>\n");
}
}
sb.append(" </metaInfo>\n");
if (writeElement) {
return sb.toString();
} else {
return "";
}
}
/**
* returns info about indices in this database for explainPlan. Dynamically
* reads all fields from lucene-index and appends them to the explainPlan if
* prefix of fieldName (string that ends with a dot) is defined as
* contextSet in properties (contextSet...). Dynamically adds sortKeywords
* by selecting all fields that start with a prefix as given in property
* sortSet.
*
* @return String indexInfo xml for explainPlan
* @sb
*/
public String getIndexInfo() {
Enumeration enumer = dbProperties.propertyNames();
Hashtable sets = new Hashtable();
String index, indexSet, prop;
StringBuffer sb = new StringBuffer("");
StringTokenizer st;
HashMap contextSets = new HashMap();
String sortSet = dbProperties.getProperty("sortSet");
while (enumer.hasMoreElements()) {
prop = (String) enumer.nextElement();
// MIH: extract contextSetName
// compare with fieldNames in LuceneIndex
// if fieldName starts with <name>. that is contained in contextSets
// then this field belongs to a contextSet
if (prop.startsWith("contextSet.")) {
contextSets.put(prop.substring(ELEVEN), "");
}
if (prop.startsWith("qualifier.")) {
st = new StringTokenizer(prop.substring(TEN));
index = st.nextToken();
st = new StringTokenizer(index, ".");
if (st.countTokens() == 1) {
indexSet = "local";
}
else {
indexSet = st.nextToken();
}
index = st.nextToken();
if (sets.get(indexSet) == null) { // new set
sets.put(indexSet, indexSet);
}
sb
.append(" <index>\n")
.append(" <title>").append(indexSet).append('.')
.append(index).append("</title>\n").append(
" <map>\n").append(
" <name set=\"").append(indexSet).append(
"\">").append(index).append("</name>\n").append(
" </map>\n").append(
" </index>\n");
}
}
Collection fieldList =
((EscidocLuceneTranslator) getCQLTranslator()).getFieldList();
indexSet = null;
index = null;
if (fieldList != null) {
StringBuffer sortKeywords = new StringBuffer("");
for (Iterator iter = fieldList.iterator(); iter.hasNext();) {
String fieldName = (String) iter.next();
String[] parts = fieldName.split("\\.");
if (parts != null && parts.length > 1) {
String indexName =
fieldName.replaceFirst(parts[0] + "\\.", "");
if (contextSets.get(parts[0]) != null) {
if (sets.get(parts[0]) == null) {
sets.put(parts[0], parts[0]);
}
// get title from properties
String title =
dbProperties
.getProperty("description." + fieldName);
if (title == null || title.equals("")) {
title = fieldName;
}
sb
.append(" <index>\n").append(
" <title>").append(title).append(
"</title>\n").append(" <map>\n")
.append(" <name set=\"").append(
parts[0]).append("\">").append(indexName)
.append("</name>\n").append(
" </map>\n").append(
" </index>\n");
}
if (sortSet != null && !sortSet.equals("")
&& sortSet.equals(parts[0])) {
sortKeywords.append(" <sortKeyword>").append(
fieldName).append("</sortKeyword>\n");
}
}
}
if (sortKeywords.length() > 0) {
sb.append(sortKeywords);
}
}
if (sets != null && !sets.isEmpty()) {
StringBuffer setsBuf = new StringBuffer("");
for (Iterator iter = sets.keySet().iterator(); iter.hasNext();) {
String setName = (String) iter.next();
setsBuf.append(" <set identifier=\"").append(
dbProperties.getProperty("contextSet." + setName)).append(
"\" name=\"").append(setName).append("\"/>\n");
}
sb.insert(0, setsBuf);
}
sb.insert(0, " <indexInfo>\n");
sb.append(" </indexInfo>\n");
return sb.toString();
}
}
| false | true | public SearchRetrieveResponseType doRequest(
final SearchRetrieveRequestType request) throws ServletException {
SearchRetrieveResponseType response = null; // search response
int resultSetTTL; // time result set should expire
String recordPacking; // how record is packed (xml|string)
String query; // Search String
String sortKeysString; // keys to sort on
PositiveInteger startRec; // record number to start with
ExtraDataType extraData = null; // extra params sent with request
ResolvingQueryResult results; // results of search, array of
// Ids/handles
try {
MessageContext msgContext = MessageContext.getCurrentContext();
response = new SearchRetrieveResponseType();
response.setNumberOfRecords(new NonNegativeInteger("0"));
startRec = request.getStartRecord();
extraData = request.getExtraRequestData();
/**
* Get schema name and verify its supported.
*/
String schemaName = request.getRecordSchema();
if (schemaName == null) {
schemaName = "default";
}
log.info("recordSchema=" + schemaName);
if (schemaName != null && !schemaName.equals(DEFAULT_SCHEMA)) {
if (!getResolver().containsSchema(schemaName)) {
log.error("no handler for schema " + schemaName);
return diagnostic(SRWDiagnostic.UnknownSchemaForRetrieval,
schemaName, response);
}
}
/**
* RecordXPath - UNSUPPORTED
*/
if (request.getRecordXPath() != null
&& request.getRecordXPath().trim().length() != 0) {
return diagnostic(
DIAGNOSTIC_CODE_EIGHT, request.getRecordXPath(), response);
}
/**
* set result set TTL
*/
if (request.getResultSetTTL() != null) {
resultSetTTL = request.getResultSetTTL().intValue();
}
else {
resultSetTTL = defaultResultSetTTL;
}
/**
* Set Record Packing
*/
recordPacking = request.getRecordPacking();
if (recordPacking == null) {
if (msgContext != null && msgContext.getProperty("sru") != null) {
recordPacking = "xml"; // default for sru
}
else {
recordPacking = "string"; // default for srw
}
}
/**
* get sort keys
*/
sortKeysString = request.getSortKeys();
if (sortKeysString != null && sortKeysString.length() == 0) {
sortKeysString = null;
}
/**
* Parse and Execute Query
*/
query = request.getQuery();
try {
log.info("search:\n"
+ ORG.oclc.util.Util.byteArrayToString(query
.getBytes("UTF-8")));
}
catch (Exception e) {
log.info(e);
}
CQLNode queryRoot = null;
try {
queryRoot = parser.parse(escapeBackslash(query));
}
catch (CQLParseException e) {
return diagnostic(SRWDiagnostic.QuerySyntaxError, e
.getMessage(), response);
}
String resultSetID = queryRoot.getResultSetName();
int numRecs = defaultNumRecs;
NonNegativeInteger maxRecs = request.getMaximumRecords();
if (maxRecs != null) {
numRecs =
(int) java.lang.Math.min(maxRecs.longValue(),
maximumRecords);
}
// MIH: set maxRecs in request, because request
// gets passed to EscidocLuceneTranslator
// EscidocLuceneTranslator performs search and fills identifers
request.setMaximumRecords(new NonNegativeInteger(Integer
.toString(numRecs)));
int startPoint = 1;
if (startRec != null) {
startPoint = (int) startRec.longValue();
}
if (resultSetID != null) {
// look for existing result set
log.info("resultSetID=" + resultSetID);
results = (ResolvingQueryResult) oldResultSets.get(resultSetID);
if (results == null) {
return diagnostic(SRWDiagnostic.ResultSetDoesNotExist,
resultSetID, response);
}
}
else {
// MIH: call overwritten method that is only available in
// EscidocLuceneTranslator:
// 3rd parameter: request (to get sortKeys,
// startRecord, maxRecords..)!
results =
(ResolvingQueryResult) (
(EscidocLuceneTranslator) getCQLTranslator())
.search(queryRoot, extraData, request);
results.setResolver(getResolver());
results.setExtraDataType(extraData);
/**
* if results were found save the result set and setup the timer
* for when it expires
*
*/
if (results.getNumberOfRecords() > 0 && resultSetTTL > 0) {
resultSetID = makeResultSetID();
oldResultSets.put(resultSetID, results);
log.info("keeping resultSet '" + resultSetID + "' for "
+ resultSetTTL + " seconds");
timers.put(resultSetID, new Long(System.currentTimeMillis()
+ (resultSetTTL * MILLISECONDS_PER_SECOND)));
response.setResultSetId(resultSetID);
response.setResultSetIdleTime(new PositiveInteger(Integer
.toString(resultSetTTL)));
}
}
int postings = (int) results.getNumberOfRecords();
response.setNumberOfRecords(new NonNegativeInteger(Long
.toString(postings)));
log.info("'" + query + "'==> " + postings);
if (postings > 0 && startPoint > postings) {
diagnostic(SRWDiagnostic.FirstRecordPositionOutOfRange, null,
response);
}
if ((startPoint - 1 + numRecs) > postings) {
numRecs = postings - (startPoint - 1);
}
if (postings > 0 && numRecs == 0) {
response.setNextRecordPosition(new PositiveInteger("1"));
}
if (postings > 0 && numRecs > 0) { // render some records into SGML
RecordsType records = new RecordsType();
log.info("trying to get " + numRecs
+ " records starting with record " + startPoint
+ " from a set of " + postings + " records");
if (!recordPacking.equals("xml")
&& !recordPacking.equals("string")) {
return diagnostic(
DIAGNOSTIC_CODE_SEVENTY_ONE, recordPacking, response);
}
records.setRecord(new RecordType[numRecs]);
Document domDoc;
DocumentBuilder db = null;
DocumentBuilderFactory dbf = null;
int i = -1;
MessageElement[] elems;
RecordType record;
StringOrXmlFragment frag;
if (recordPacking.equals("xml")) {
dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
db = dbf.newDocumentBuilder();
}
/**
* One at a time, retrieve and display the requested documents.
*/
RecordIterator list = null;
try {
log.info("making RecordIterator, startPoint=" + startPoint
+ ", schemaID=" + schemaName);
list =
results.recordIterator(startPoint - 1, numRecs,
schemaName);
}
catch (InstantiationException e) {
diagnostic(SRWDiagnostic.GeneralSystemError,
e.getMessage(), response);
}
for (i = 0; list.hasNext(); i++) {
try {
Record rec = list.nextRecord();
/**
* create record container
*/
record = new RecordType();
record.setRecordPacking(recordPacking);
frag = new StringOrXmlFragment();
elems = new MessageElement[1];
frag.set_any(elems);
record.setRecordSchema(rec.getRecordSchemaID());
if (recordPacking.equals("xml")) {
domDoc =
db.parse(new InputSource(new StringReader(rec
.getRecord())));
Element el = domDoc.getDocumentElement();
log.debug("got the DocumentElement");
elems[0] = new MessageElement(el);
log.debug("put the domDoc into elems[0]");
}
else { // string
Text t = new Text(rec.getRecord());
elems[0] = new MessageElement(t);
}
record.setRecordData(frag);
log.debug("setRecordData");
record.setRecordPosition(new PositiveInteger(Integer
.toString(startPoint + i)));
records.setRecord(i, record);
}
catch (NoSuchElementException e) {
log.error("Read beyond the end of list!!");
log.error(e);
break;
}
response.setRecords(records);
}
if (startPoint + i <= postings) {
response.setNextRecordPosition(new PositiveInteger(Long
.toString(startPoint + i)));
}
}
log.debug("exit doRequest");
return response;
}
catch (Exception e) {
return diagnostic(SRWDiagnostic.GeneralSystemError, e.getMessage(),
response);
}
}
| public SearchRetrieveResponseType doRequest(
final SearchRetrieveRequestType request) throws ServletException {
SearchRetrieveResponseType response = null; // search response
int resultSetTTL; // time result set should expire
String recordPacking; // how record is packed (xml|string)
String query; // Search String
String sortKeysString; // keys to sort on
PositiveInteger startRec; // record number to start with
ExtraDataType extraData = null; // extra params sent with request
ResolvingQueryResult results; // results of search, array of
// Ids/handles
try {
MessageContext msgContext = MessageContext.getCurrentContext();
response = new SearchRetrieveResponseType();
response.setNumberOfRecords(new NonNegativeInteger("0"));
startRec = request.getStartRecord();
extraData = request.getExtraRequestData();
/**
* Get schema name and verify its supported.
*/
String schemaName = request.getRecordSchema();
if (schemaName == null) {
schemaName = "default";
}
log.info("recordSchema=" + schemaName);
if (schemaName != null && !schemaName.equals(DEFAULT_SCHEMA)) {
if (!getResolver().containsSchema(schemaName)) {
log.error("no handler for schema " + schemaName);
return diagnostic(SRWDiagnostic.UnknownSchemaForRetrieval,
schemaName, response);
}
}
/**
* RecordXPath - UNSUPPORTED
*/
if (request.getRecordXPath() != null
&& request.getRecordXPath().trim().length() != 0) {
return diagnostic(
DIAGNOSTIC_CODE_EIGHT, request.getRecordXPath(), response);
}
/**
* set result set TTL
*/
if (request.getResultSetTTL() != null) {
resultSetTTL = request.getResultSetTTL().intValue();
}
else {
resultSetTTL = defaultResultSetTTL;
}
/**
* Set Record Packing
*/
recordPacking = request.getRecordPacking();
if (recordPacking == null) {
if (msgContext != null && msgContext.getProperty("sru") != null) {
recordPacking = "xml"; // default for sru
}
else {
recordPacking = "string"; // default for srw
}
}
/**
* get sort keys
*/
sortKeysString = request.getSortKeys();
if (sortKeysString != null && sortKeysString.length() == 0) {
sortKeysString = null;
}
/**
* Parse and Execute Query
*/
query = request.getQuery();
try {
log.info("search:\n"
+ ORG.oclc.util.Util.byteArrayToString(query
.getBytes("UTF-8")));
}
catch (Exception e) {
log.info(e);
}
CQLNode queryRoot = null;
if (query.matches(".*[^\\\\]\".*")) {
query = escapeBackslash(query);
}
try {
queryRoot = parser.parse(query);
}
catch (CQLParseException e) {
return diagnostic(SRWDiagnostic.QuerySyntaxError, e
.getMessage(), response);
}
String resultSetID = queryRoot.getResultSetName();
int numRecs = defaultNumRecs;
NonNegativeInteger maxRecs = request.getMaximumRecords();
if (maxRecs != null) {
numRecs =
(int) java.lang.Math.min(maxRecs.longValue(),
maximumRecords);
}
// MIH: set maxRecs in request, because request
// gets passed to EscidocLuceneTranslator
// EscidocLuceneTranslator performs search and fills identifers
request.setMaximumRecords(new NonNegativeInteger(Integer
.toString(numRecs)));
int startPoint = 1;
if (startRec != null) {
startPoint = (int) startRec.longValue();
}
if (resultSetID != null) {
// look for existing result set
log.info("resultSetID=" + resultSetID);
results = (ResolvingQueryResult) oldResultSets.get(resultSetID);
if (results == null) {
return diagnostic(SRWDiagnostic.ResultSetDoesNotExist,
resultSetID, response);
}
}
else {
// MIH: call overwritten method that is only available in
// EscidocLuceneTranslator:
// 3rd parameter: request (to get sortKeys,
// startRecord, maxRecords..)!
results =
(ResolvingQueryResult) (
(EscidocLuceneTranslator) getCQLTranslator())
.search(queryRoot, extraData, request);
results.setResolver(getResolver());
results.setExtraDataType(extraData);
/**
* if results were found save the result set and setup the timer
* for when it expires
*
*/
if (results.getNumberOfRecords() > 0 && resultSetTTL > 0) {
resultSetID = makeResultSetID();
oldResultSets.put(resultSetID, results);
log.info("keeping resultSet '" + resultSetID + "' for "
+ resultSetTTL + " seconds");
timers.put(resultSetID, new Long(System.currentTimeMillis()
+ (resultSetTTL * MILLISECONDS_PER_SECOND)));
response.setResultSetId(resultSetID);
response.setResultSetIdleTime(new PositiveInteger(Integer
.toString(resultSetTTL)));
}
}
int postings = (int) results.getNumberOfRecords();
response.setNumberOfRecords(new NonNegativeInteger(Long
.toString(postings)));
log.info("'" + query + "'==> " + postings);
if (postings > 0 && startPoint > postings) {
diagnostic(SRWDiagnostic.FirstRecordPositionOutOfRange, null,
response);
}
if ((startPoint - 1 + numRecs) > postings) {
numRecs = postings - (startPoint - 1);
}
if (postings > 0 && numRecs == 0) {
response.setNextRecordPosition(new PositiveInteger("1"));
}
if (postings > 0 && numRecs > 0) { // render some records into SGML
RecordsType records = new RecordsType();
log.info("trying to get " + numRecs
+ " records starting with record " + startPoint
+ " from a set of " + postings + " records");
if (!recordPacking.equals("xml")
&& !recordPacking.equals("string")) {
return diagnostic(
DIAGNOSTIC_CODE_SEVENTY_ONE, recordPacking, response);
}
records.setRecord(new RecordType[numRecs]);
Document domDoc;
DocumentBuilder db = null;
DocumentBuilderFactory dbf = null;
int i = -1;
MessageElement[] elems;
RecordType record;
StringOrXmlFragment frag;
if (recordPacking.equals("xml")) {
dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
db = dbf.newDocumentBuilder();
}
/**
* One at a time, retrieve and display the requested documents.
*/
RecordIterator list = null;
try {
log.info("making RecordIterator, startPoint=" + startPoint
+ ", schemaID=" + schemaName);
list =
results.recordIterator(startPoint - 1, numRecs,
schemaName);
}
catch (InstantiationException e) {
diagnostic(SRWDiagnostic.GeneralSystemError,
e.getMessage(), response);
}
for (i = 0; list.hasNext(); i++) {
try {
Record rec = list.nextRecord();
/**
* create record container
*/
record = new RecordType();
record.setRecordPacking(recordPacking);
frag = new StringOrXmlFragment();
elems = new MessageElement[1];
frag.set_any(elems);
record.setRecordSchema(rec.getRecordSchemaID());
if (recordPacking.equals("xml")) {
domDoc =
db.parse(new InputSource(new StringReader(rec
.getRecord())));
Element el = domDoc.getDocumentElement();
log.debug("got the DocumentElement");
elems[0] = new MessageElement(el);
log.debug("put the domDoc into elems[0]");
}
else { // string
Text t = new Text(rec.getRecord());
elems[0] = new MessageElement(t);
}
record.setRecordData(frag);
log.debug("setRecordData");
record.setRecordPosition(new PositiveInteger(Integer
.toString(startPoint + i)));
records.setRecord(i, record);
}
catch (NoSuchElementException e) {
log.error("Read beyond the end of list!!");
log.error(e);
break;
}
response.setRecords(records);
}
if (startPoint + i <= postings) {
response.setNextRecordPosition(new PositiveInteger(Long
.toString(startPoint + i)));
}
}
log.debug("exit doRequest");
return response;
}
catch (Exception e) {
return diagnostic(SRWDiagnostic.GeneralSystemError, e.getMessage(),
response);
}
}
|
diff --git a/src/main/java/Rule.java b/src/main/java/Rule.java
index 532683b..e255620 100644
--- a/src/main/java/Rule.java
+++ b/src/main/java/Rule.java
@@ -1,74 +1,74 @@
import osm.primitive.Tag;
public class Rule {
private String type;
private String srcKey;
private String srcValue;
private boolean useOriginalValue = false;
private String targetKey;
private String targetValue;
/**
*
*/
public Rule(String type, String srcKey, String srcValue, String targetKey, String targetValue) {
this.type = type;
this.srcKey = srcKey;
this.srcValue = srcValue;
this.targetKey = targetKey;
this.targetValue = targetValue;
}
/**
* Constructor that uses the original shapefile's value as the value of the
* tag.
*
*/
public Rule(String type, String srcKey, String srcValue, String targetKey) {
this(type, srcKey, srcValue, targetKey, null);
this.useOriginalValue = true;
}
public String toString() {
return type + ": " + srcKey + "=" + srcValue + " => " + targetKey + "=" + targetValue;
}
public Tag createTag(String srcKey, String originalValue) {
String key;
String value;
// Only create the tag if their key matches ours
if (srcKey.equals(this.srcKey)) {
// If they list a source key value, then only create the tag if their key
// value matches ours
if (srcValue != null) {
- if (originalValue.contains(this.srcValue)) {
+ if (originalValue.equals(this.srcValue)) {
key = targetKey;
if (useOriginalValue) {
value = originalValue;
} else {
value = targetValue;
}
return new Tag(key, value);
}
} else {
// If they didn't specify a value for the source key, then we
// always apply the tag
if (useOriginalValue) {
value = originalValue;
} else {
value = targetValue;
}
return new Tag(targetKey, value);
}
}
return null;
}
}
| true | true | public Tag createTag(String srcKey, String originalValue) {
String key;
String value;
// Only create the tag if their key matches ours
if (srcKey.equals(this.srcKey)) {
// If they list a source key value, then only create the tag if their key
// value matches ours
if (srcValue != null) {
if (originalValue.contains(this.srcValue)) {
key = targetKey;
if (useOriginalValue) {
value = originalValue;
} else {
value = targetValue;
}
return new Tag(key, value);
}
} else {
// If they didn't specify a value for the source key, then we
// always apply the tag
if (useOriginalValue) {
value = originalValue;
} else {
value = targetValue;
}
return new Tag(targetKey, value);
}
}
return null;
}
| public Tag createTag(String srcKey, String originalValue) {
String key;
String value;
// Only create the tag if their key matches ours
if (srcKey.equals(this.srcKey)) {
// If they list a source key value, then only create the tag if their key
// value matches ours
if (srcValue != null) {
if (originalValue.equals(this.srcValue)) {
key = targetKey;
if (useOriginalValue) {
value = originalValue;
} else {
value = targetValue;
}
return new Tag(key, value);
}
} else {
// If they didn't specify a value for the source key, then we
// always apply the tag
if (useOriginalValue) {
value = originalValue;
} else {
value = targetValue;
}
return new Tag(targetKey, value);
}
}
return null;
}
|
diff --git a/src/ru/uiiiii/ssearchm/searching/GitHelper.java b/src/ru/uiiiii/ssearchm/searching/GitHelper.java
index 5bd65d9..eb7ccdd 100644
--- a/src/ru/uiiiii/ssearchm/searching/GitHelper.java
+++ b/src/ru/uiiiii/ssearchm/searching/GitHelper.java
@@ -1,54 +1,54 @@
package ru.uiiiii.ssearchm.searching;
import java.io.File;
import java.io.IOException;
import java.util.Set;
import java.util.TreeSet;
import org.eclipse.jgit.api.BlameCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.NoHeadException;
import org.eclipse.jgit.blame.BlameResult;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.revwalk.RevCommit;
import ru.uiiiii.ssearchm.indexing.Indexer;
public class GitHelper {
private Git git;
private ObjectId headId;
public GitHelper(String docsPath) throws IOException, NoHeadException, GitAPIException {
git = Git.open(new File(docsPath));
headId = git.log().call().iterator().next().getId();
}
private BlameResult getBlameResult(String filePath) throws IOException, GitAPIException {
String docsPath = Indexer.DOCS_PATH;
- String filePathInsideRepo = filePath.replace(docsPath, "").substring(1); // remove \\
+ String filePathInsideRepo = filePath.replace(docsPath, "").substring(1).replace('\\', '/'); // substring(1) = remove '\'
BlameCommand blame = git.blame();
blame.setFilePath(filePathInsideRepo);
blame.setStartCommit(headId);
blame.setFollowFileRenames(true);
BlameResult result = blame.call();
return result;
}
public Set<RevCommit> getCommitsFromFile(String filePath) throws IOException, GitAPIException {
BlameResult blameResult = getBlameResult(filePath);
int linesCount = blameResult.getResultContents().size();
TreeSet<RevCommit> commits = new TreeSet<RevCommit>();
for (int i = 0; i < linesCount; i++) {
commits.add(blameResult.getSourceCommit(i));
}
return commits;
}
}
| true | true | private BlameResult getBlameResult(String filePath) throws IOException, GitAPIException {
String docsPath = Indexer.DOCS_PATH;
String filePathInsideRepo = filePath.replace(docsPath, "").substring(1); // remove \\
BlameCommand blame = git.blame();
blame.setFilePath(filePathInsideRepo);
blame.setStartCommit(headId);
blame.setFollowFileRenames(true);
BlameResult result = blame.call();
return result;
}
| private BlameResult getBlameResult(String filePath) throws IOException, GitAPIException {
String docsPath = Indexer.DOCS_PATH;
String filePathInsideRepo = filePath.replace(docsPath, "").substring(1).replace('\\', '/'); // substring(1) = remove '\'
BlameCommand blame = git.blame();
blame.setFilePath(filePathInsideRepo);
blame.setStartCommit(headId);
blame.setFollowFileRenames(true);
BlameResult result = blame.call();
return result;
}
|
diff --git a/ludum-dare-26/src/eu32k/ludumdare/ld26/effects/TileMove.java b/ludum-dare-26/src/eu32k/ludumdare/ld26/effects/TileMove.java
index 4a53546..0ddcc5a 100644
--- a/ludum-dare-26/src/eu32k/ludumdare/ld26/effects/TileMove.java
+++ b/ludum-dare-26/src/eu32k/ludumdare/ld26/effects/TileMove.java
@@ -1,116 +1,118 @@
package eu32k.ludumdare.ld26.effects;
import com.badlogic.gdx.math.Vector2;
import eu32k.ludumdare.ld26.level.MoveComplete;
import eu32k.ludumdare.ld26.level.Tile;
import eu32k.ludumdare.ld26.objects.Goal;
import eu32k.ludumdare.ld26.objects.Player;
import eu32k.ludumdare.ld26.state.LevelState;
import eu32k.ludumdare.ld26.state.PlayerState;
import eu32k.ludumdare.ld26.state.StateMachine;
public class TileMove implements IRunningEffect {
private boolean complete;
private Tile tile;
private float targetX;
private float targetY;
private float speedX;
private float speedY;
private LevelState levelState;
private Player player;
public boolean complete() {
return complete;
}
public TileMove()
{
this.levelState = StateMachine.instance().getState(LevelState.class);
PlayerState playerState = StateMachine.instance().getState(PlayerState.class);
if(playerState != null)
{
this.player = playerState.getPlayer();
}
}
public void initMove(Tile tile, float targetX, float targetY, float speed)
{
this.tile = tile;
this.targetX = targetX;
this.targetY = targetY;
complete = false;
Vector2 t1 = Vector2.tmp;
Vector2 t2 = Vector2.tmp2;
t1.set(tile.getX(), tile.getY());
t2.set(targetX, targetY);
t2.sub(t1).nor().mul(speed);
speedX = t2.x;
speedY = t2.y;
}
public void update(float delta) {
float x = tile.getX();
float y = tile.getY();
//Player offset to tile... used in case player is moved with a tile to put him in the exact same position
float poX = 0;
float poY = 0;
float goX = 0;
float goY = 0;
Goal goal = levelState.getGoal();
boolean movesPlayer = player != null && levelState.playerTile != null && levelState.playerTile.equals(tile);
boolean movesGoal = goal != null && levelState.goalTile != null && levelState.goalTile.equals(tile);
+ if(goal.isFreeMovement())
+ movesGoal = false;
if(movesPlayer)
{
poX = player.getX() - x;
poY = player.getY() - y;
}
if(movesGoal)
{
goX = goal.getX() - x;
goY = goal.getY() - y;
}
x += speedX * delta;
y += speedY * delta;
if ((speedX > 0 && x >= targetX) || (speedX < 0 && x <= targetX) || (speedY > 0 && y >= targetY) || (speedY < 0 && y <= targetY)) {
levelState.getEvents().enqueue(new MoveComplete(this));
tile.setX(targetX);
tile.setY(targetY);
if(movesPlayer)
{
player.setMovingWithTile(true);
player.setPosition(tile.getX() + poX, tile.getY() + poY);
}
if(movesGoal)
{
goal.setPosition(tile.getX() + goX, tile.getY() + goY);
}
complete = true;
return;
}
tile.setX(x);
tile.setY(y);
if(movesPlayer)
{
player.setMovingWithTile(false);
player.setPosition(tile.getX() + poX, tile.getY() + poY);
}
if(movesGoal)
{
goal.setPosition(tile.getX() + goX, tile.getY() + goY);
}
}
public Tile getTile() {
return tile;
}
public void setTile(Tile tile) {
this.tile = tile;
}
}
| true | true | public void update(float delta) {
float x = tile.getX();
float y = tile.getY();
//Player offset to tile... used in case player is moved with a tile to put him in the exact same position
float poX = 0;
float poY = 0;
float goX = 0;
float goY = 0;
Goal goal = levelState.getGoal();
boolean movesPlayer = player != null && levelState.playerTile != null && levelState.playerTile.equals(tile);
boolean movesGoal = goal != null && levelState.goalTile != null && levelState.goalTile.equals(tile);
if(movesPlayer)
{
poX = player.getX() - x;
poY = player.getY() - y;
}
if(movesGoal)
{
goX = goal.getX() - x;
goY = goal.getY() - y;
}
x += speedX * delta;
y += speedY * delta;
if ((speedX > 0 && x >= targetX) || (speedX < 0 && x <= targetX) || (speedY > 0 && y >= targetY) || (speedY < 0 && y <= targetY)) {
levelState.getEvents().enqueue(new MoveComplete(this));
tile.setX(targetX);
tile.setY(targetY);
if(movesPlayer)
{
player.setMovingWithTile(true);
player.setPosition(tile.getX() + poX, tile.getY() + poY);
}
if(movesGoal)
{
goal.setPosition(tile.getX() + goX, tile.getY() + goY);
}
complete = true;
return;
}
tile.setX(x);
tile.setY(y);
if(movesPlayer)
{
player.setMovingWithTile(false);
player.setPosition(tile.getX() + poX, tile.getY() + poY);
}
if(movesGoal)
{
goal.setPosition(tile.getX() + goX, tile.getY() + goY);
}
}
| public void update(float delta) {
float x = tile.getX();
float y = tile.getY();
//Player offset to tile... used in case player is moved with a tile to put him in the exact same position
float poX = 0;
float poY = 0;
float goX = 0;
float goY = 0;
Goal goal = levelState.getGoal();
boolean movesPlayer = player != null && levelState.playerTile != null && levelState.playerTile.equals(tile);
boolean movesGoal = goal != null && levelState.goalTile != null && levelState.goalTile.equals(tile);
if(goal.isFreeMovement())
movesGoal = false;
if(movesPlayer)
{
poX = player.getX() - x;
poY = player.getY() - y;
}
if(movesGoal)
{
goX = goal.getX() - x;
goY = goal.getY() - y;
}
x += speedX * delta;
y += speedY * delta;
if ((speedX > 0 && x >= targetX) || (speedX < 0 && x <= targetX) || (speedY > 0 && y >= targetY) || (speedY < 0 && y <= targetY)) {
levelState.getEvents().enqueue(new MoveComplete(this));
tile.setX(targetX);
tile.setY(targetY);
if(movesPlayer)
{
player.setMovingWithTile(true);
player.setPosition(tile.getX() + poX, tile.getY() + poY);
}
if(movesGoal)
{
goal.setPosition(tile.getX() + goX, tile.getY() + goY);
}
complete = true;
return;
}
tile.setX(x);
tile.setY(y);
if(movesPlayer)
{
player.setMovingWithTile(false);
player.setPosition(tile.getX() + poX, tile.getY() + poY);
}
if(movesGoal)
{
goal.setPosition(tile.getX() + goX, tile.getY() + goY);
}
}
|
diff --git a/app/controllers/Dummy.java b/app/controllers/Dummy.java
index 13df70f..0812019 100644
--- a/app/controllers/Dummy.java
+++ b/app/controllers/Dummy.java
@@ -1,32 +1,32 @@
package controllers;
import play.mvc.Controller;
import play.data.validation.Required;
public class Dummy extends Controller {
public static void index(){
if(!Security.isConnected())
render();
else
PageController.welcome();
}
public static void createAccount(){
render();
}
public static void newAccount(@Required String email, @Required String password,
@Required String firstName, @Required String lastName,
@Required String address, @Required String phoneNumber,
@Required String sex, String code){
if (validation.hasErrors()) {
- createAccount();
+ render("createAccount.html");
}
//TODO: Create the user, then log them in automagically
}
}
| true | true | public static void newAccount(@Required String email, @Required String password,
@Required String firstName, @Required String lastName,
@Required String address, @Required String phoneNumber,
@Required String sex, String code){
if (validation.hasErrors()) {
createAccount();
}
//TODO: Create the user, then log them in automagically
}
| public static void newAccount(@Required String email, @Required String password,
@Required String firstName, @Required String lastName,
@Required String address, @Required String phoneNumber,
@Required String sex, String code){
if (validation.hasErrors()) {
render("createAccount.html");
}
//TODO: Create the user, then log them in automagically
}
|
diff --git a/crypto/src/org/bouncycastle/asn1/x509/KeyUsage.java b/crypto/src/org/bouncycastle/asn1/x509/KeyUsage.java
index 918173b7..3ffd94b4 100644
--- a/crypto/src/org/bouncycastle/asn1/x509/KeyUsage.java
+++ b/crypto/src/org/bouncycastle/asn1/x509/KeyUsage.java
@@ -1,77 +1,77 @@
package org.bouncycastle.asn1.x509;
import org.bouncycastle.asn1.DERBitString;
/**
* The KeyUsage object.
* <pre>
* id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }
*
* KeyUsage ::= BIT STRING {
* digitalSignature (0),
* nonRepudiation (1),
* keyEncipherment (2),
* dataEncipherment (3),
* keyAgreement (4),
* keyCertSign (5),
* cRLSign (6),
* encipherOnly (7),
* decipherOnly (8) }
* </pre>
*/
public class KeyUsage
extends DERBitString
{
public static final int digitalSignature = (1 << 7);
public static final int nonRepudiation = (1 << 6);
public static final int keyEncipherment = (1 << 5);
public static final int dataEncipherment = (1 << 4);
public static final int keyAgreement = (1 << 3);
public static final int keyCertSign = (1 << 2);
public static final int cRLSign = (1 << 1);
public static final int encipherOnly = (1 << 0);
public static final int decipherOnly = (1 << 15);
- public static KeyUsage getInstance(Object obj)
+ public static DERBitString getInstance(Object obj) // needs to be DERBitString for other VMs
{
if (obj instanceof KeyUsage)
{
return (KeyUsage)obj;
}
if (obj instanceof X509Extension)
{
return new KeyUsage(DERBitString.getInstance(X509Extension.convertValueToObject((X509Extension)obj)));
}
return new KeyUsage(DERBitString.getInstance(obj));
}
/**
* Basic constructor.
*
* @param usage - the bitwise OR of the Key Usage flags giving the
* allowed uses for the key.
* e.g. (KeyUsage.keyEncipherment | KeyUsage.dataEncipherment)
*/
public KeyUsage(
int usage)
{
super(getBytes(usage), getPadBits(usage));
}
public KeyUsage(
DERBitString usage)
{
super(usage.getBytes(), usage.getPadBits());
}
public String toString()
{
if (data.length == 1)
{
return "KeyUsage: 0x" + Integer.toHexString(data[0] & 0xff);
}
return "KeyUsage: 0x" + Integer.toHexString((data[1] & 0xff) << 8 | (data[0] & 0xff));
}
}
| true | true | public static KeyUsage getInstance(Object obj)
{
if (obj instanceof KeyUsage)
{
return (KeyUsage)obj;
}
if (obj instanceof X509Extension)
{
return new KeyUsage(DERBitString.getInstance(X509Extension.convertValueToObject((X509Extension)obj)));
}
return new KeyUsage(DERBitString.getInstance(obj));
}
| public static DERBitString getInstance(Object obj) // needs to be DERBitString for other VMs
{
if (obj instanceof KeyUsage)
{
return (KeyUsage)obj;
}
if (obj instanceof X509Extension)
{
return new KeyUsage(DERBitString.getInstance(X509Extension.convertValueToObject((X509Extension)obj)));
}
return new KeyUsage(DERBitString.getInstance(obj));
}
|
diff --git a/src/freemail/ui/web/MessageToadlet.java b/src/freemail/ui/web/MessageToadlet.java
index c7e65e9..e37b237 100644
--- a/src/freemail/ui/web/MessageToadlet.java
+++ b/src/freemail/ui/web/MessageToadlet.java
@@ -1,244 +1,238 @@
/*
* MessageToadlet.java
* This file is part of Freemail
* Copyright (C) 2011 Martin Nyhus
*
* 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 freemail.ui.web;
import java.io.IOException;
import java.net.URI;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import freemail.AccountManager;
import freemail.FreemailAccount;
import freemail.MailMessage;
import freemail.MessageBank;
import freemail.support.MessageBankTools;
import freemail.l10n.FreemailL10n;
import freemail.utils.Logger;
import freenet.clients.http.PageNode;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.HTMLNode;
import freenet.support.api.HTTPRequest;
public class MessageToadlet extends WebPage {
private static final String PATH = WebInterface.PATH + "/Message";
private final AccountManager accountManager;
MessageToadlet(AccountManager accountManager, PluginRespirator pluginRespirator) {
super(pluginRespirator);
this.accountManager = accountManager;
}
@Override
void makeWebPageGet(URI uri, HTTPRequest req, ToadletContext ctx, PageNode page) throws ToadletContextClosedException, IOException {
HTMLNode pageNode = page.outer;
HTMLNode contentNode = page.content;
HTMLNode container = contentNode.addChild("div", "class", "container");
//Add the list of folders
HTMLNode folderList = container.addChild("div", "class", "folderlist");
String identity = sessionManager.useSession(ctx).getUserID();
FreemailAccount account = accountManager.getAccount(identity);
MessageBank topLevelMessageBank = account.getMessageBank();
addMessageBank(folderList, topLevelMessageBank, "inbox");
//Add the message
String folderName = req.getParam("folder", "inbox");
- MessageBank messageBank;
- if(folderName.equals("inbox")) {
- messageBank = account.getMessageBank();
- } else {
- folderName = folderName.substring("index.".length());
- messageBank = MessageBankTools.getMessageBank(account.getMessageBank(), folderName);
- }
+ MessageBank messageBank = MessageBankTools.getMessageBank(account, folderName);
int messageUid;
try {
messageUid = Integer.parseInt(req.getParam("uid"));
} catch(NumberFormatException e) {
Logger.error(this, "Got invalid uid: " + req.getParam("uid"));
messageUid = 0;
}
MailMessage msg = MessageBankTools.getMessage(messageBank, messageUid);
if(msg == null) {
/* FIXME: L10n */
HTMLNode infobox = addErrorbox(container, "Message doesn't exist");
infobox.addChild("p", "The message you requested doesn't exist");
writeHTMLReply(ctx, 200, "OK", pageNode.generate());
return;
}
HTMLNode messageNode = container.addChild("div", "class", "message");
addMessageButtons(ctx, messageNode, folderName, messageUid);
addMessageHeaders(messageNode, msg);
addMessageContents(messageNode, msg);
//Mark message as read
if(!msg.flags.get("\\seen")) {
msg.flags.set("\\seen", true);
msg.storeFlags();
}
writeHTMLReply(ctx, 200, "OK", pageNode.generate());
}
@Override
void makeWebPagePost(URI uri, HTTPRequest req, ToadletContext ctx, PageNode page) throws ToadletContextClosedException, IOException {
makeWebPageGet(uri, req, ctx, page);
}
private void addMessageButtons(ToadletContext ctx, HTMLNode parent, String folderName, int uid) {
HTMLNode buttonBox = parent.addChild("div", "class", "message-buttons");
//Add reply button
HTMLNode replyForm = ctx.addFormChild(buttonBox, NewMessageToadlet.getPath(), "reply");
replyForm.addChild("input", new String[] {"type", "name", "value"},
new String[] {"hidden", "action", "reply"});
replyForm.addChild("input", new String[] {"type", "name", "value"},
new String[] {"hidden", "folder", folderName});
replyForm.addChild("input", new String[] {"type", "name", "value"},
new String[] {"hidden", "message", "" + uid});
replyForm.addChild("input", new String[] {"type", "value"},
new String[] {"submit", FreemailL10n.getString("Freemail.MessageToadlet.reply")});
}
private void addMessageHeaders(HTMLNode messageNode, MailMessage message) {
HTMLNode headerBox = messageNode.addChild("div", "class", "message-headers");
try {
message.readHeaders();
} catch(IOException e) {
/* FIXME: L10n */
Logger.error(this, "Caugth IOException reading headers for " + message);
headerBox.addChild("p", "There was a problem reading the message headers");
return;
}
HTMLNode toPara = headerBox.addChild("p");
toPara.addChild("strong", "To:");
toPara.addChild("#", " " + message.getFirstHeader("to"));
HTMLNode fromPara = headerBox.addChild("p");
fromPara.addChild("strong", "From:");
fromPara.addChild("#", " " + message.getFirstHeader("from"));
if(message.getFirstHeader("cc") != null) {
HTMLNode ccPara = headerBox.addChild("p");
ccPara.addChild("strong", "CC:");
ccPara.addChild("#", " " + message.getFirstHeader("cc"));
}
if(message.getFirstHeader("bcc") != null) {
HTMLNode bccPara = headerBox.addChild("p");
bccPara.addChild("strong", "BCC:");
bccPara.addChild("#", " " + message.getFirstHeader("bcc"));
}
HTMLNode subjectPara = headerBox.addChild("p");
subjectPara.addChild("strong", "Subject:");
String subject = message.getFirstHeader("Subject");
if((subject == null) || (subject.equals(""))) {
subject = FreemailL10n.getString("Freemail.Web.Common.defaultSubject");
}
subjectPara.addChild("#", " " + subject);
}
private void addMessageContents(HTMLNode messageNode, MailMessage message) {
HTMLNode messageContents = messageNode.addChild("div", "class", "message-content").addChild("p");
List<String> lines = new LinkedList<String>();
try {
boolean inHeader = true;
while(true) {
String line = message.readLine();
if(line == null) break;
if((line.equals("")) && inHeader) {
inHeader = false;
continue;
}
if(inHeader) {
continue;
}
lines.add(line);
}
} catch(IOException e) {
//TODO: Better error message
HTMLNode errorBox = addErrorbox(messageContents, "Couldn't read message");
errorBox.addChild("p", "Couldn't read the message: " + e);
return;
}
Iterator<String> lineIterator = lines.iterator();
while(lineIterator.hasNext()) {
messageContents.addChild("#", lineIterator.next());
if(lineIterator.hasNext()) {
messageContents.addChild("br");
}
}
}
private HTMLNode addMessageBank(HTMLNode parent, MessageBank messageBank, String folderName) {
//First add this message bank
HTMLNode folderDiv = parent.addChild("div", "class", "folder");
HTMLNode folderPara = folderDiv.addChild("p");
folderPara.addChild("a", "href", InboxToadlet.getFolderPath(folderName), messageBank.getName());
//Then add all the children recursively
for(MessageBank child : messageBank.listSubFolders()) {
addMessageBank(folderDiv, child, folderName + "." + child.getName());
}
return folderDiv;
}
@Override
public boolean isEnabled(ToadletContext ctx) {
return sessionManager.sessionExists(ctx);
}
@Override
public String path() {
return PATH;
}
static String getPath() {
return PATH;
}
static String getMessagePath(String folderName, int messageNum) {
return getPath() + "?folder=" + folderName + "&uid=" + messageNum;
}
@Override
boolean requiresValidSession() {
return true;
}
}
| true | true | void makeWebPageGet(URI uri, HTTPRequest req, ToadletContext ctx, PageNode page) throws ToadletContextClosedException, IOException {
HTMLNode pageNode = page.outer;
HTMLNode contentNode = page.content;
HTMLNode container = contentNode.addChild("div", "class", "container");
//Add the list of folders
HTMLNode folderList = container.addChild("div", "class", "folderlist");
String identity = sessionManager.useSession(ctx).getUserID();
FreemailAccount account = accountManager.getAccount(identity);
MessageBank topLevelMessageBank = account.getMessageBank();
addMessageBank(folderList, topLevelMessageBank, "inbox");
//Add the message
String folderName = req.getParam("folder", "inbox");
MessageBank messageBank;
if(folderName.equals("inbox")) {
messageBank = account.getMessageBank();
} else {
folderName = folderName.substring("index.".length());
messageBank = MessageBankTools.getMessageBank(account.getMessageBank(), folderName);
}
int messageUid;
try {
messageUid = Integer.parseInt(req.getParam("uid"));
} catch(NumberFormatException e) {
Logger.error(this, "Got invalid uid: " + req.getParam("uid"));
messageUid = 0;
}
MailMessage msg = MessageBankTools.getMessage(messageBank, messageUid);
if(msg == null) {
/* FIXME: L10n */
HTMLNode infobox = addErrorbox(container, "Message doesn't exist");
infobox.addChild("p", "The message you requested doesn't exist");
writeHTMLReply(ctx, 200, "OK", pageNode.generate());
return;
}
HTMLNode messageNode = container.addChild("div", "class", "message");
addMessageButtons(ctx, messageNode, folderName, messageUid);
addMessageHeaders(messageNode, msg);
addMessageContents(messageNode, msg);
//Mark message as read
if(!msg.flags.get("\\seen")) {
msg.flags.set("\\seen", true);
msg.storeFlags();
}
writeHTMLReply(ctx, 200, "OK", pageNode.generate());
}
| void makeWebPageGet(URI uri, HTTPRequest req, ToadletContext ctx, PageNode page) throws ToadletContextClosedException, IOException {
HTMLNode pageNode = page.outer;
HTMLNode contentNode = page.content;
HTMLNode container = contentNode.addChild("div", "class", "container");
//Add the list of folders
HTMLNode folderList = container.addChild("div", "class", "folderlist");
String identity = sessionManager.useSession(ctx).getUserID();
FreemailAccount account = accountManager.getAccount(identity);
MessageBank topLevelMessageBank = account.getMessageBank();
addMessageBank(folderList, topLevelMessageBank, "inbox");
//Add the message
String folderName = req.getParam("folder", "inbox");
MessageBank messageBank = MessageBankTools.getMessageBank(account, folderName);
int messageUid;
try {
messageUid = Integer.parseInt(req.getParam("uid"));
} catch(NumberFormatException e) {
Logger.error(this, "Got invalid uid: " + req.getParam("uid"));
messageUid = 0;
}
MailMessage msg = MessageBankTools.getMessage(messageBank, messageUid);
if(msg == null) {
/* FIXME: L10n */
HTMLNode infobox = addErrorbox(container, "Message doesn't exist");
infobox.addChild("p", "The message you requested doesn't exist");
writeHTMLReply(ctx, 200, "OK", pageNode.generate());
return;
}
HTMLNode messageNode = container.addChild("div", "class", "message");
addMessageButtons(ctx, messageNode, folderName, messageUid);
addMessageHeaders(messageNode, msg);
addMessageContents(messageNode, msg);
//Mark message as read
if(!msg.flags.get("\\seen")) {
msg.flags.set("\\seen", true);
msg.storeFlags();
}
writeHTMLReply(ctx, 200, "OK", pageNode.generate());
}
|
diff --git a/gerrit-gwtui/src/main/java/com/google/gerrit/client/account/RegisterScreen.java b/gerrit-gwtui/src/main/java/com/google/gerrit/client/account/RegisterScreen.java
index 084ea6f89..2810931e8 100644
--- a/gerrit-gwtui/src/main/java/com/google/gerrit/client/account/RegisterScreen.java
+++ b/gerrit-gwtui/src/main/java/com/google/gerrit/client/account/RegisterScreen.java
@@ -1,141 +1,141 @@
// Copyright (C) 2009 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 com.google.gerrit.client.account;
import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.ui.AccountScreen;
import com.google.gerrit.client.ui.InlineHyperlink;
import com.google.gerrit.client.ui.SmallHeading;
import com.google.gerrit.common.PageLinks;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Account.FieldName;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
public class RegisterScreen extends AccountScreen {
private final String nextToken;
public RegisterScreen(final String next) {
nextToken = next;
}
@Override
protected void onLoad() {
super.onLoad();
display();
}
@Override
protected void onInitUI() {
super.onInitUI();
setPageTitle(Util.C.welcomeToGerritCodeReview());
final FlowPanel formBody = new FlowPanel();
final FlowPanel contactGroup = new FlowPanel();
contactGroup.setStyleName(Gerrit.RESOURCES.css().registerScreenSection());
contactGroup.add(new SmallHeading(Util.C.welcomeReviewContact()));
final HTML whereFrom = new HTML(Util.C.welcomeContactFrom());
whereFrom.setStyleName(Gerrit.RESOURCES.css().registerScreenExplain());
contactGroup.add(whereFrom);
contactGroup.add(new ContactPanelShort() {
@Override
protected void display(final Account userAccount) {
super.display(userAccount);
if ("".equals(nameTxt.getText())) {
// No name? Encourage the user to provide us something.
//
nameTxt.setFocus(true);
save.setEnabled(true);
}
}
});
formBody.add(contactGroup);
if (Gerrit.getUserAccount().getUserName() == null
&& Gerrit.getConfig().canEdit(FieldName.USER_NAME)) {
final FlowPanel fp = new FlowPanel();
fp.setStyleName(Gerrit.RESOURCES.css().registerScreenSection());
fp.add(new SmallHeading(Util.C.welcomeUsernameHeading()));
final Grid userInfo = new Grid(1, 2);
final CellFormatter fmt = userInfo.getCellFormatter();
userInfo.setStyleName(Gerrit.RESOURCES.css().infoBlock());
userInfo.addStyleName(Gerrit.RESOURCES.css().accountInfoBlock());
fp.add(userInfo);
fmt.addStyleName(0, 0, Gerrit.RESOURCES.css().topmost());
fmt.addStyleName(0, 1, Gerrit.RESOURCES.css().topmost());
fmt.addStyleName(0, 0, Gerrit.RESOURCES.css().bottomheader());
UsernameField field = new UsernameField();
if (LocaleInfo.getCurrentLocale().isRTL()) {
userInfo.setText(0, 1, Util.C.userName());
userInfo.setWidget(0, 0, field);
fmt.addStyleName(0, 1, Gerrit.RESOURCES.css().header());
} else {
userInfo.setText(0, 0, Util.C.userName());
userInfo.setWidget(0, 1, field);
fmt.addStyleName(0, 0, Gerrit.RESOURCES.css().header());
}
formBody.add(fp);
}
if (Gerrit.getConfig().getSshdAddress() != null) {
final FlowPanel sshKeyGroup = new FlowPanel();
sshKeyGroup.setStyleName(Gerrit.RESOURCES.css().registerScreenSection());
sshKeyGroup.add(new SmallHeading(Util.C.welcomeSshKeyHeading()));
final HTML whySshKey = new HTML(Util.C.welcomeSshKeyText());
whySshKey.setStyleName(Gerrit.RESOURCES.css().registerScreenExplain());
sshKeyGroup.add(whySshKey);
sshKeyGroup.add(new SshPanel() {
{
setKeyTableVisible(false);
}
});
formBody.add(sshKeyGroup);
}
final FlowPanel choices = new FlowPanel();
choices.setStyleName(Gerrit.RESOURCES.css().registerScreenNextLinks());
if (Gerrit.getConfig().isUseContributorAgreements()) {
final FlowPanel agreementGroup = new FlowPanel();
agreementGroup.setStyleName(Gerrit.RESOURCES.css().registerScreenSection());
agreementGroup.add(new SmallHeading(Util.C.welcomeAgreementHeading()));
final HTML whyAgreement = new HTML(Util.C.welcomeAgreementText());
whyAgreement.setStyleName(Gerrit.RESOURCES.css().registerScreenExplain());
agreementGroup.add(whyAgreement);
choices.add(new InlineHyperlink(Util.C.newAgreement(),
- PageLinks.SETTINGS_NEW_AGREEMENT + "," + nextToken));
+ PageLinks.SETTINGS_NEW_AGREEMENT));
choices
.add(new InlineHyperlink(Util.C.welcomeAgreementLater(), nextToken));
formBody.add(agreementGroup);
} else {
choices.add(new InlineHyperlink(Util.C.welcomeContinue(), nextToken));
}
formBody.add(choices);
final FormPanel form = new FormPanel();
form.add(formBody);
add(form);
}
}
| true | true | protected void onInitUI() {
super.onInitUI();
setPageTitle(Util.C.welcomeToGerritCodeReview());
final FlowPanel formBody = new FlowPanel();
final FlowPanel contactGroup = new FlowPanel();
contactGroup.setStyleName(Gerrit.RESOURCES.css().registerScreenSection());
contactGroup.add(new SmallHeading(Util.C.welcomeReviewContact()));
final HTML whereFrom = new HTML(Util.C.welcomeContactFrom());
whereFrom.setStyleName(Gerrit.RESOURCES.css().registerScreenExplain());
contactGroup.add(whereFrom);
contactGroup.add(new ContactPanelShort() {
@Override
protected void display(final Account userAccount) {
super.display(userAccount);
if ("".equals(nameTxt.getText())) {
// No name? Encourage the user to provide us something.
//
nameTxt.setFocus(true);
save.setEnabled(true);
}
}
});
formBody.add(contactGroup);
if (Gerrit.getUserAccount().getUserName() == null
&& Gerrit.getConfig().canEdit(FieldName.USER_NAME)) {
final FlowPanel fp = new FlowPanel();
fp.setStyleName(Gerrit.RESOURCES.css().registerScreenSection());
fp.add(new SmallHeading(Util.C.welcomeUsernameHeading()));
final Grid userInfo = new Grid(1, 2);
final CellFormatter fmt = userInfo.getCellFormatter();
userInfo.setStyleName(Gerrit.RESOURCES.css().infoBlock());
userInfo.addStyleName(Gerrit.RESOURCES.css().accountInfoBlock());
fp.add(userInfo);
fmt.addStyleName(0, 0, Gerrit.RESOURCES.css().topmost());
fmt.addStyleName(0, 1, Gerrit.RESOURCES.css().topmost());
fmt.addStyleName(0, 0, Gerrit.RESOURCES.css().bottomheader());
UsernameField field = new UsernameField();
if (LocaleInfo.getCurrentLocale().isRTL()) {
userInfo.setText(0, 1, Util.C.userName());
userInfo.setWidget(0, 0, field);
fmt.addStyleName(0, 1, Gerrit.RESOURCES.css().header());
} else {
userInfo.setText(0, 0, Util.C.userName());
userInfo.setWidget(0, 1, field);
fmt.addStyleName(0, 0, Gerrit.RESOURCES.css().header());
}
formBody.add(fp);
}
if (Gerrit.getConfig().getSshdAddress() != null) {
final FlowPanel sshKeyGroup = new FlowPanel();
sshKeyGroup.setStyleName(Gerrit.RESOURCES.css().registerScreenSection());
sshKeyGroup.add(new SmallHeading(Util.C.welcomeSshKeyHeading()));
final HTML whySshKey = new HTML(Util.C.welcomeSshKeyText());
whySshKey.setStyleName(Gerrit.RESOURCES.css().registerScreenExplain());
sshKeyGroup.add(whySshKey);
sshKeyGroup.add(new SshPanel() {
{
setKeyTableVisible(false);
}
});
formBody.add(sshKeyGroup);
}
final FlowPanel choices = new FlowPanel();
choices.setStyleName(Gerrit.RESOURCES.css().registerScreenNextLinks());
if (Gerrit.getConfig().isUseContributorAgreements()) {
final FlowPanel agreementGroup = new FlowPanel();
agreementGroup.setStyleName(Gerrit.RESOURCES.css().registerScreenSection());
agreementGroup.add(new SmallHeading(Util.C.welcomeAgreementHeading()));
final HTML whyAgreement = new HTML(Util.C.welcomeAgreementText());
whyAgreement.setStyleName(Gerrit.RESOURCES.css().registerScreenExplain());
agreementGroup.add(whyAgreement);
choices.add(new InlineHyperlink(Util.C.newAgreement(),
PageLinks.SETTINGS_NEW_AGREEMENT + "," + nextToken));
choices
.add(new InlineHyperlink(Util.C.welcomeAgreementLater(), nextToken));
formBody.add(agreementGroup);
} else {
choices.add(new InlineHyperlink(Util.C.welcomeContinue(), nextToken));
}
formBody.add(choices);
final FormPanel form = new FormPanel();
form.add(formBody);
add(form);
}
| protected void onInitUI() {
super.onInitUI();
setPageTitle(Util.C.welcomeToGerritCodeReview());
final FlowPanel formBody = new FlowPanel();
final FlowPanel contactGroup = new FlowPanel();
contactGroup.setStyleName(Gerrit.RESOURCES.css().registerScreenSection());
contactGroup.add(new SmallHeading(Util.C.welcomeReviewContact()));
final HTML whereFrom = new HTML(Util.C.welcomeContactFrom());
whereFrom.setStyleName(Gerrit.RESOURCES.css().registerScreenExplain());
contactGroup.add(whereFrom);
contactGroup.add(new ContactPanelShort() {
@Override
protected void display(final Account userAccount) {
super.display(userAccount);
if ("".equals(nameTxt.getText())) {
// No name? Encourage the user to provide us something.
//
nameTxt.setFocus(true);
save.setEnabled(true);
}
}
});
formBody.add(contactGroup);
if (Gerrit.getUserAccount().getUserName() == null
&& Gerrit.getConfig().canEdit(FieldName.USER_NAME)) {
final FlowPanel fp = new FlowPanel();
fp.setStyleName(Gerrit.RESOURCES.css().registerScreenSection());
fp.add(new SmallHeading(Util.C.welcomeUsernameHeading()));
final Grid userInfo = new Grid(1, 2);
final CellFormatter fmt = userInfo.getCellFormatter();
userInfo.setStyleName(Gerrit.RESOURCES.css().infoBlock());
userInfo.addStyleName(Gerrit.RESOURCES.css().accountInfoBlock());
fp.add(userInfo);
fmt.addStyleName(0, 0, Gerrit.RESOURCES.css().topmost());
fmt.addStyleName(0, 1, Gerrit.RESOURCES.css().topmost());
fmt.addStyleName(0, 0, Gerrit.RESOURCES.css().bottomheader());
UsernameField field = new UsernameField();
if (LocaleInfo.getCurrentLocale().isRTL()) {
userInfo.setText(0, 1, Util.C.userName());
userInfo.setWidget(0, 0, field);
fmt.addStyleName(0, 1, Gerrit.RESOURCES.css().header());
} else {
userInfo.setText(0, 0, Util.C.userName());
userInfo.setWidget(0, 1, field);
fmt.addStyleName(0, 0, Gerrit.RESOURCES.css().header());
}
formBody.add(fp);
}
if (Gerrit.getConfig().getSshdAddress() != null) {
final FlowPanel sshKeyGroup = new FlowPanel();
sshKeyGroup.setStyleName(Gerrit.RESOURCES.css().registerScreenSection());
sshKeyGroup.add(new SmallHeading(Util.C.welcomeSshKeyHeading()));
final HTML whySshKey = new HTML(Util.C.welcomeSshKeyText());
whySshKey.setStyleName(Gerrit.RESOURCES.css().registerScreenExplain());
sshKeyGroup.add(whySshKey);
sshKeyGroup.add(new SshPanel() {
{
setKeyTableVisible(false);
}
});
formBody.add(sshKeyGroup);
}
final FlowPanel choices = new FlowPanel();
choices.setStyleName(Gerrit.RESOURCES.css().registerScreenNextLinks());
if (Gerrit.getConfig().isUseContributorAgreements()) {
final FlowPanel agreementGroup = new FlowPanel();
agreementGroup.setStyleName(Gerrit.RESOURCES.css().registerScreenSection());
agreementGroup.add(new SmallHeading(Util.C.welcomeAgreementHeading()));
final HTML whyAgreement = new HTML(Util.C.welcomeAgreementText());
whyAgreement.setStyleName(Gerrit.RESOURCES.css().registerScreenExplain());
agreementGroup.add(whyAgreement);
choices.add(new InlineHyperlink(Util.C.newAgreement(),
PageLinks.SETTINGS_NEW_AGREEMENT));
choices
.add(new InlineHyperlink(Util.C.welcomeAgreementLater(), nextToken));
formBody.add(agreementGroup);
} else {
choices.add(new InlineHyperlink(Util.C.welcomeContinue(), nextToken));
}
formBody.add(choices);
final FormPanel form = new FormPanel();
form.add(formBody);
add(form);
}
|
diff --git a/src/com/dmdirc/ui/swing/textpane/TextPane.java b/src/com/dmdirc/ui/swing/textpane/TextPane.java
index bb11ba2c9..cfe68f1d9 100644
--- a/src/com/dmdirc/ui/swing/textpane/TextPane.java
+++ b/src/com/dmdirc/ui/swing/textpane/TextPane.java
@@ -1,731 +1,733 @@
/*
* Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* 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 com.dmdirc.ui.swing.textpane;
import com.dmdirc.FrameContainer;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.ui.IconManager;
import com.dmdirc.ui.messages.IRCTextAttribute;
import com.dmdirc.ui.messages.Styliser;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.font.ImageGraphicAttribute;
import java.awt.font.TextAttribute;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.Enumeration;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JScrollBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.StyleConstants.CharacterConstants;
import javax.swing.text.StyleConstants.ColorConstants;
import javax.swing.text.StyleConstants.FontConstants;
import javax.swing.text.StyledDocument;
import net.miginfocom.swing.MigLayout;
/**
* Styled, scrollable text pane.
*/
public final class TextPane extends JComponent implements AdjustmentListener,
MouseWheelListener, IRCDocumentListener {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 5;
/** Scrollbar for the component. */
private final JScrollBar scrollBar;
/** Canvas object, used to draw text. */
private final TextPaneCanvas canvas;
/** IRCDocument. */
private final IRCDocument document;
/** Parent Frame. */
private final FrameContainer frame;
/** Click types. */
public enum ClickType {
/** Hyperlink. */
HYPERLINK,
/** Channel. */
CHANNEL,
/** Nickname. */
NICKNAME,
/** Normal. */
NORMAL,
}
/**
* Creates a new instance of TextPane.
*
* @param frame Parent Frame
*/
public TextPane(final FrameContainer frame) {
super();
this.frame = frame;
document = new IRCDocument();
setMinimumSize(new Dimension(0, 0));
setLayout(new MigLayout("fill"));
canvas = new TextPaneCanvas(this, document);
setBorder(UIManager.getBorder("TextField.border"));
add(canvas, "dock center");
scrollBar = new JScrollBar(JScrollBar.VERTICAL);
add(scrollBar, "dock east");
setAutoscrolls(true);
scrollBar.setMaximum(document.getNumLines());
scrollBar.setBlockIncrement(10);
scrollBar.setUnitIncrement(1);
scrollBar.addAdjustmentListener(this);
addMouseWheelListener(this);
document.addIRCDocumentListener(this);
MouseMotionListener doScrollRectToVisible = new MouseMotionAdapter() {
/** {@inheritDoc} */
@Override
public void mouseDragged(MouseEvent e) {
if (e.getXOnScreen() > getLocationOnScreen().getX() && e.getXOnScreen() < (getLocationOnScreen().
getX() + getWidth()) && e.getModifiersEx() ==
MouseEvent.BUTTON1_DOWN_MASK) {
if (getLocationOnScreen().getY() > e.getYOnScreen()) {
setScrollBarPosition(scrollBar.getValue() - 1);
} else if (getLocationOnScreen().getY() + getHeight() <
e.getYOnScreen()) {
setScrollBarPosition(scrollBar.getValue() + 1);
}
canvas.highlightEvent(TextPaneCanvas.MouseEventType.DRAG, e);
}
}
};
addMouseMotionListener(doScrollRectToVisible);
}
/**
* Adds styled text to the textpane.
* @param text styled text to add
*/
public void addText(final AttributedString text) {
document.addText(text);
}
/**
* Adds styled text to the textpane.
* @param text styled text to add
*/
public void addText(final List<AttributedString> text) {
document.addText(text);
}
/**
* Stylises the specified string and adds it to the passed TextPane.
*
* @param string The line to be stylised and added
*/
public void addStyledString(final String string) {
addStyledString(new String[]{string,});
}
/**
* Stylises the specified string and adds it to the passed TextPane.
*
* @param strings The strings to be stylised and added to a line
*/
public void addStyledString(final String[] strings) {
addText(styledDocumentToAttributedString(
Styliser.getStyledString(strings)));
}
/**
* Converts a StyledDocument into an AttributedString.
*
* @param doc StyledDocument to convert
*
* @return AttributedString representing the specified StyledDocument
*/
public static AttributedString styledDocumentToAttributedString(
final StyledDocument doc) {
//Now lets get hacky, loop through the styled document and add all
//styles to an attributedString
AttributedString attString = null;
final Element line = doc.getParagraphElement(0);
try {
attString = new AttributedString(line.getDocument().getText(0,
line.getDocument().getLength()));
} catch (BadLocationException ex) {
Logger.userError(ErrorLevel.MEDIUM,
"Unable to insert styled string: " + ex.getMessage());
}
if (attString.getIterator().getEndIndex() != 0) {
attString.addAttribute(TextAttribute.SIZE,
UIManager.getFont("TextPane.font").getSize());
attString.addAttribute(TextAttribute.FAMILY,
UIManager.getFont("TextPane.font").getFamily());
}
for (int i = 0; i < line.getElementCount(); i++) {
final Element element = line.getElement(i);
final AttributeSet as = element.getAttributes();
final Enumeration<?> ae = as.getAttributeNames();
while (ae.hasMoreElements()) {
final Object attrib = ae.nextElement();
if (attrib == IRCTextAttribute.HYPERLINK) {
//Hyperlink
attString.addAttribute(IRCTextAttribute.HYPERLINK,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == IRCTextAttribute.NICKNAME) {
//Nicknames
attString.addAttribute(IRCTextAttribute.NICKNAME,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == IRCTextAttribute.CHANNEL) {
//Channels
attString.addAttribute(IRCTextAttribute.CHANNEL,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == ColorConstants.Foreground) {
//Foreground
attString.addAttribute(TextAttribute.FOREGROUND,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == ColorConstants.Background) {
//Background
attString.addAttribute(TextAttribute.BACKGROUND,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == FontConstants.Bold) {
//Bold
attString.addAttribute(TextAttribute.WEIGHT,
TextAttribute.WEIGHT_BOLD, element.getStartOffset(),
element.getEndOffset());
} else if (attrib == FontConstants.Family) {
//Family
attString.addAttribute(TextAttribute.FAMILY,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == FontConstants.Italic) {
//italics
attString.addAttribute(TextAttribute.POSTURE,
TextAttribute.POSTURE_OBLIQUE,
element.getStartOffset(),
element.getEndOffset());
} else if (attrib == CharacterConstants.Underline) {
//Underline
attString.addAttribute(TextAttribute.UNDERLINE,
TextAttribute.UNDERLINE_ON, element.getStartOffset(),
element.getEndOffset());
} else if (attrib == IRCTextAttribute.SMILEY) {
+ /* Lets avoid showing broken smileys shall we!
final Image image = IconManager.getIconManager().getImage((String) as.getAttribute(attrib)).
getScaledInstance(14, 14, Image.SCALE_DEFAULT);
ImageGraphicAttribute iga = new ImageGraphicAttribute(image,
(int) BOTTOM_ALIGNMENT, 5, 5);
attString.addAttribute(TextAttribute.CHAR_REPLACEMENT, iga,
element.getStartOffset(), element.getEndOffset());
+ */
}
}
}
if (attString.getIterator().getEndIndex() == 0) {
return new AttributedString("\n");
}
return attString;
}
/**
* Sets the new position for the scrollbar and the associated position
* to render the text from.
* @param position new position of the scrollbar
*/
public void setScrollBarPosition(final int position) {
scrollBar.setValue(position);
canvas.setScrollBarPosition(position);
}
/**
* Enables or disabled the scrollbar for the textpane.
*
* @param enabled State for the scrollbar
*/
public void setScrollEnabled(final boolean enabled) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
scrollBar.setEnabled(enabled);
}
});
}
/**
* Returns the last visible line in the textpane.
*
* @return Last visible line index
*/
public int getLastVisibleLine() {
return scrollBar.getValue();
}
/**
* Returns the line count in the textpane.
*
* @return Line count
*/
public int getNumLines() {
return document.getNumLines();
}
/**
* Returns the specified line in the textpane.
*
* @param line Line to return
*
* @return AttributedString at the specified line
*/
public AttributedString getLine(final int line) {
return document.getLine(line);
}
/**
* Sets the scrollbar's maximum position. If the current position is
* within <code>linesAllowed</code> of the end of the document, the
* scrollbar's current position is set to the end of the document.
*
* @param linesAllowed The number of lines allowed below the current position
* @since 0.6
*/
protected void setScrollBarMax(final int linesAllowed) {
final int lines = document.getNumLines() - 1;
if (lines == 0) {
canvas.repaint();
}
scrollBar.setMaximum(lines);
if (!scrollBar.getValueIsAdjusting() && scrollBar.getValue() == lines -
linesAllowed) {
setScrollBarPosition(lines);
}
}
/**
* {@inheritDoc}
*
* @param e Mouse wheel event
*/
@Override
public void adjustmentValueChanged(final AdjustmentEvent e) {
setScrollBarPosition(e.getValue());
}
/**
* {@inheritDoc}
*
* @param e Mouse wheel event
*/
@Override
public void mouseWheelMoved(final MouseWheelEvent e) {
if (scrollBar.isEnabled()) {
if (e.getWheelRotation() > 0) {
setScrollBarPosition(scrollBar.getValue() + e.getScrollAmount());
} else {
setScrollBarPosition(scrollBar.getValue() - e.getScrollAmount());
}
}
}
/**
*
* Returns the line information from a mouse click inside the textpane.
*
* @param point mouse position
*
* @return line number, line part, position in whole line
*/
public LineInfo getClickPosition(final Point point) {
return canvas.getClickPosition(point);
}
/**
* Returns the selected text.
*
* * <li>0 = start line</li>
* <li>1 = start char</li>
* <li>2 = end line</li>
* <li>3 = end char</li>
*
* @return Selected text
*/
public String getSelectedText() {
final StringBuffer selectedText = new StringBuffer();
final LinePosition selectedRange = canvas.getSelectedRange();
for (int i = selectedRange.getStartLine(); i <=
selectedRange.getEndLine(); i++) {
if (i != selectedRange.getStartLine()) {
selectedText.append('\n');
}
if (document.getNumLines() <= i) {
return selectedText.toString();
}
final AttributedCharacterIterator iterator = document.getLine(i).
getIterator();
if (selectedRange.getEndLine() == selectedRange.getStartLine()) {
//loop through range
selectedText.append(getTextFromLine(iterator,
selectedRange.getStartPos(), selectedRange.getEndPos()));
} else if (i == selectedRange.getStartLine()) {
//loop from start of range to the end
selectedText.append(getTextFromLine(iterator,
selectedRange.getStartPos(), iterator.getEndIndex()));
} else if (i == selectedRange.getEndLine()) {
//loop from start to end of range
selectedText.append(getTextFromLine(iterator, 0,
selectedRange.getEndPos()));
} else {
//loop the whole line
selectedText.append(getTextFromLine(iterator, 0,
iterator.getEndIndex()));
}
}
return selectedText.toString();
}
/**
* Returns the selected range.
*
* @return selected range
*/
public LinePosition getSelectedRange() {
return canvas.getSelectedRange();
}
/**
* Returns whether there is a selected range.
*
* @return true iif there is a selected range
*/
public boolean hasSelectedRange() {
final LinePosition selectedRange = canvas.getSelectedRange();
return !(selectedRange.getStartLine() == selectedRange.getEndLine() &&
selectedRange.getStartPos() == selectedRange.getEndPos());
}
/**
* Selects the specified region of text.
*
* @param position Line position
*/
public void setSelectedTexT(final LinePosition position) {
canvas.setSelectedRange(position);
}
/**
* Returns the entire text from the specified line.
*
* @param line line to retrieve text from
*
* @return Text from the line
*/
public String getTextFromLine(final int line) {
final AttributedCharacterIterator iterator = document.getLine(line).
getIterator();
return getTextFromLine(iterator, 0, iterator.getEndIndex(), document);
}
/**
* Returns the entire text from the specified line.
*
* @param line line to retrieve text from
* @param document Document to retrieve text from
*
* @return Text from the line
*/
public static String getTextFromLine(final int line,
final IRCDocument document) {
final AttributedCharacterIterator iterator = document.getLine(line).
getIterator();
return getTextFromLine(iterator, 0, iterator.getEndIndex(), document);
}
/**
* Returns the range of text from the specified iterator.
*
* @param line line to retrieve text from
* @param start Start index in the iterator
* @param end End index in the iterator
*
* @return Text in the range from the line
*/
public String getTextFromLine(final int line, final int start,
final int end) {
return getTextFromLine(document.getLine(line).getIterator(), start, end,
document);
}
/**
* Returns the range of text from the specified iterator.
*
* @param line line to retrieve text from
* @param start Start index in the iterator
* @param end End index in the iterator
* @param document Document to retrieve text from
*
* @return Text in the range from the line
*/
public static String getTextFromLine(final int line, final int start,
final int end, final IRCDocument document) {
return getTextFromLine(document.getLine(line).getIterator(), start, end,
document);
}
/**
* Returns the range of text from the specified iterator.
*
* @param iterator iterator to get text from
*
* @return Text in the range from the line
*/
public String getTextFromLine(final AttributedCharacterIterator iterator) {
return getTextFromLine(iterator, iterator.getBeginIndex(),
iterator.getEndIndex(), document);
}
/**
* Returns the range of text from the specified iterator.
*
* @param iterator iterator to get text from
* @param document Document to retrieve text from
*
* @return Text in the range from the line
*/
public static String getTextFromLine(final AttributedCharacterIterator iterator,
final IRCDocument document) {
return getTextFromLine(iterator, iterator.getBeginIndex(),
iterator.getEndIndex(), document);
}
/**
* Returns the range of text from the specified iterator.
*
* @param iterator iterator to get text from
* @param start Start index in the iterator
* @param end End index in the iterator
*
* @return Text in the range from the line
*/
public String getTextFromLine(final AttributedCharacterIterator iterator,
final int start, final int end) {
return getTextFromLine(iterator, start, end, document);
}
/**
* Returns the range of text from the specified iterator.
*
* @param iterator iterator to get text from
* @param start Start index in the iterator
* @param end End index in the iterator
* @param document Document to retrieve text from
*
* @return Text in the range from the line
*/
public static String getTextFromLine(final AttributedCharacterIterator iterator,
final int start, final int end, final IRCDocument document) {
return document.getLineText(iterator, start, end);
}
/**
* Returns the type of text this click represents.
*
* @param lineInfo Line info of click.
*
* @return Click type for specified position
*/
public ClickType getClickType(final LineInfo lineInfo) {
return canvas.getClickType(lineInfo);
}
/**
* Returns the surrouding word at the specified position.
*
* @param lineNumber Line number to get word from
* @param index Position to get surrounding word
*
* @return Surrounding word
*/
public String getWordAtIndex(final int lineNumber, final int index) {
if (lineNumber == -1) {
return "";
}
final int[] indexes =
canvas.getSurroundingWordIndexes(getTextFromLine(lineNumber),
index);
return getTextFromLine(lineNumber, indexes[0], indexes[1]);
}
/**
* Returns the atrriute value for the specified location.
*
* @param lineInfo Specified location
*
* @return Specified value
*/
public Object getAttributeValueAtPoint(LineInfo lineInfo) {
return canvas.getAttributeValueAtPoint(lineInfo);
}
/** Adds the selected text to the clipboard. */
public void copy() {
if (getSelectedText() != null && !getSelectedText().isEmpty()) {
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
new StringSelection(getSelectedText()), null);
}
}
/** Clears the textpane. */
public void clear() {
document.clear();
setScrollBarPosition(0);
setScrollBarMax(1);
canvas.repaint();
}
/** Clears the selection. */
public void clearSelection() {
canvas.clearSelection();
}
/**
* Trims the document to the specified number of lines.
*
* @param numLines Number of lines to trim the document to
*/
public void trim(final int numLines) {
if (document.getNumLines() < numLines) {
return;
}
final int trimmedLines = document.getNumLines() - numLines;
final LinePosition selectedRange = getSelectedRange();
selectedRange.setStartLine(selectedRange.getStartLine() - trimmedLines);
selectedRange.setEndLine(selectedRange.getEndLine() - trimmedLines);
if (selectedRange.getStartLine() < 0) {
selectedRange.setStartLine(0);
}
if (selectedRange.getEndLine() < 0) {
selectedRange.setEndLine(0);
}
setSelectedTexT(selectedRange);
document.trim(numLines);
}
/** Scrolls one page up in the textpane. */
public void pageDown() {
//setScrollBarPosition(scrollBar.getValue() + canvas.getLastVisibleLine()
// - canvas.getFirstVisibleLine() + 1);
//use this method for now, its consistent with the block unit for the scrollbar
setScrollBarPosition(scrollBar.getValue() + 10);
}
/** Scrolls one page down in the textpane. */
public void pageUp() {
//setScrollBarPosition(canvas.getFirstVisibleLine());
//use this method for now, its consistent with the block unit for the scrollbar
setScrollBarPosition(scrollBar.getValue() - 10);
}
/** {@inheritDoc}. */
@Override
public void lineAdded(final int line, final int size) {
setScrollBarMax(1);
}
/** {@inheritDoc}. */
@Override
public void trimmed(final int numLines) {
canvas.clearWrapCache();
setScrollBarMax(1);
}
/** {@inheritDoc}. */
@Override
public void cleared() {
canvas.clearWrapCache();
}
/** {@inheritDoc}. */
@Override
public void linesAdded(int line, int length, int size) {
setScrollBarMax(length);
}
/**
* Retrieves this textpane's IRCDocument.
*
* @return This textpane's IRC document
*/
public IRCDocument getDocument() {
return document;
}
}
| false | true | public static AttributedString styledDocumentToAttributedString(
final StyledDocument doc) {
//Now lets get hacky, loop through the styled document and add all
//styles to an attributedString
AttributedString attString = null;
final Element line = doc.getParagraphElement(0);
try {
attString = new AttributedString(line.getDocument().getText(0,
line.getDocument().getLength()));
} catch (BadLocationException ex) {
Logger.userError(ErrorLevel.MEDIUM,
"Unable to insert styled string: " + ex.getMessage());
}
if (attString.getIterator().getEndIndex() != 0) {
attString.addAttribute(TextAttribute.SIZE,
UIManager.getFont("TextPane.font").getSize());
attString.addAttribute(TextAttribute.FAMILY,
UIManager.getFont("TextPane.font").getFamily());
}
for (int i = 0; i < line.getElementCount(); i++) {
final Element element = line.getElement(i);
final AttributeSet as = element.getAttributes();
final Enumeration<?> ae = as.getAttributeNames();
while (ae.hasMoreElements()) {
final Object attrib = ae.nextElement();
if (attrib == IRCTextAttribute.HYPERLINK) {
//Hyperlink
attString.addAttribute(IRCTextAttribute.HYPERLINK,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == IRCTextAttribute.NICKNAME) {
//Nicknames
attString.addAttribute(IRCTextAttribute.NICKNAME,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == IRCTextAttribute.CHANNEL) {
//Channels
attString.addAttribute(IRCTextAttribute.CHANNEL,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == ColorConstants.Foreground) {
//Foreground
attString.addAttribute(TextAttribute.FOREGROUND,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == ColorConstants.Background) {
//Background
attString.addAttribute(TextAttribute.BACKGROUND,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == FontConstants.Bold) {
//Bold
attString.addAttribute(TextAttribute.WEIGHT,
TextAttribute.WEIGHT_BOLD, element.getStartOffset(),
element.getEndOffset());
} else if (attrib == FontConstants.Family) {
//Family
attString.addAttribute(TextAttribute.FAMILY,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == FontConstants.Italic) {
//italics
attString.addAttribute(TextAttribute.POSTURE,
TextAttribute.POSTURE_OBLIQUE,
element.getStartOffset(),
element.getEndOffset());
} else if (attrib == CharacterConstants.Underline) {
//Underline
attString.addAttribute(TextAttribute.UNDERLINE,
TextAttribute.UNDERLINE_ON, element.getStartOffset(),
element.getEndOffset());
} else if (attrib == IRCTextAttribute.SMILEY) {
final Image image = IconManager.getIconManager().getImage((String) as.getAttribute(attrib)).
getScaledInstance(14, 14, Image.SCALE_DEFAULT);
ImageGraphicAttribute iga = new ImageGraphicAttribute(image,
(int) BOTTOM_ALIGNMENT, 5, 5);
attString.addAttribute(TextAttribute.CHAR_REPLACEMENT, iga,
element.getStartOffset(), element.getEndOffset());
}
}
}
if (attString.getIterator().getEndIndex() == 0) {
return new AttributedString("\n");
}
return attString;
}
| public static AttributedString styledDocumentToAttributedString(
final StyledDocument doc) {
//Now lets get hacky, loop through the styled document and add all
//styles to an attributedString
AttributedString attString = null;
final Element line = doc.getParagraphElement(0);
try {
attString = new AttributedString(line.getDocument().getText(0,
line.getDocument().getLength()));
} catch (BadLocationException ex) {
Logger.userError(ErrorLevel.MEDIUM,
"Unable to insert styled string: " + ex.getMessage());
}
if (attString.getIterator().getEndIndex() != 0) {
attString.addAttribute(TextAttribute.SIZE,
UIManager.getFont("TextPane.font").getSize());
attString.addAttribute(TextAttribute.FAMILY,
UIManager.getFont("TextPane.font").getFamily());
}
for (int i = 0; i < line.getElementCount(); i++) {
final Element element = line.getElement(i);
final AttributeSet as = element.getAttributes();
final Enumeration<?> ae = as.getAttributeNames();
while (ae.hasMoreElements()) {
final Object attrib = ae.nextElement();
if (attrib == IRCTextAttribute.HYPERLINK) {
//Hyperlink
attString.addAttribute(IRCTextAttribute.HYPERLINK,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == IRCTextAttribute.NICKNAME) {
//Nicknames
attString.addAttribute(IRCTextAttribute.NICKNAME,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == IRCTextAttribute.CHANNEL) {
//Channels
attString.addAttribute(IRCTextAttribute.CHANNEL,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == ColorConstants.Foreground) {
//Foreground
attString.addAttribute(TextAttribute.FOREGROUND,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == ColorConstants.Background) {
//Background
attString.addAttribute(TextAttribute.BACKGROUND,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == FontConstants.Bold) {
//Bold
attString.addAttribute(TextAttribute.WEIGHT,
TextAttribute.WEIGHT_BOLD, element.getStartOffset(),
element.getEndOffset());
} else if (attrib == FontConstants.Family) {
//Family
attString.addAttribute(TextAttribute.FAMILY,
as.getAttribute(attrib), element.getStartOffset(),
element.getEndOffset());
} else if (attrib == FontConstants.Italic) {
//italics
attString.addAttribute(TextAttribute.POSTURE,
TextAttribute.POSTURE_OBLIQUE,
element.getStartOffset(),
element.getEndOffset());
} else if (attrib == CharacterConstants.Underline) {
//Underline
attString.addAttribute(TextAttribute.UNDERLINE,
TextAttribute.UNDERLINE_ON, element.getStartOffset(),
element.getEndOffset());
} else if (attrib == IRCTextAttribute.SMILEY) {
/* Lets avoid showing broken smileys shall we!
final Image image = IconManager.getIconManager().getImage((String) as.getAttribute(attrib)).
getScaledInstance(14, 14, Image.SCALE_DEFAULT);
ImageGraphicAttribute iga = new ImageGraphicAttribute(image,
(int) BOTTOM_ALIGNMENT, 5, 5);
attString.addAttribute(TextAttribute.CHAR_REPLACEMENT, iga,
element.getStartOffset(), element.getEndOffset());
*/
}
}
}
if (attString.getIterator().getEndIndex() == 0) {
return new AttributedString("\n");
}
return attString;
}
|
diff --git a/taglist/src/main/java/org/sonar/plugins/taglist/ViolationsDecorator.java b/taglist/src/main/java/org/sonar/plugins/taglist/ViolationsDecorator.java
index 1bb2c7546..363ecc8ff 100644
--- a/taglist/src/main/java/org/sonar/plugins/taglist/ViolationsDecorator.java
+++ b/taglist/src/main/java/org/sonar/plugins/taglist/ViolationsDecorator.java
@@ -1,130 +1,130 @@
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2009 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar 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.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.taglist;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.*;
import org.sonar.api.measures.CountDistributionBuilder;
import org.sonar.api.measures.Metric;
import org.sonar.api.measures.PersistenceMode;
import org.sonar.api.profiles.RulesProfile;
import org.sonar.api.resources.Java;
import org.sonar.api.resources.Project;
import org.sonar.api.resources.Resource;
import org.sonar.api.rules.*;
import org.sonar.api.utils.SonarException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
@DependsUpon(DecoratorBarriers.END_OF_VIOLATIONS_GENERATION)
public class ViolationsDecorator implements Decorator {
private static final String CHECKSTYLE_RULE_CONFIG_KEY = "Checker/TreeWalker/TodoComment";
private static final String NOSONAR_RULE_CONFIG_KEY = "NoSonar";
private RulesProfile rulesProfile;
private RuleFinder ruleFinder;
public ViolationsDecorator(RulesProfile rulesProfile, RuleFinder ruleFinder) {
this.rulesProfile = rulesProfile;
this.ruleFinder = ruleFinder;
}
@DependedUpon
public List<Metric> dependedUpon() {
return Arrays.asList(TaglistMetrics.TAGS, TaglistMetrics.OPTIONAL_TAGS, TaglistMetrics.MANDATORY_TAGS, TaglistMetrics.NOSONAR_TAGS,
TaglistMetrics.TAGS_DISTRIBUTION);
}
public boolean shouldExecuteOnProject(Project project) {
return Java.INSTANCE.equals(project.getLanguage());
}
public void decorate(Resource resource, DecoratorContext context) {
if (Resource.QUALIFIER_CLASS.equals(resource.getQualifier())) {
Collection<Rule> rules = new HashSet<Rule>();
RuleQuery ruleQuery = RuleQuery.create()
.withRepositoryKey(CoreProperties.CHECKSTYLE_PLUGIN)
.withConfigKey(CHECKSTYLE_RULE_CONFIG_KEY);
rules.addAll(ruleFinder.findAll(ruleQuery));
ruleQuery = RuleQuery.create()
.withRepositoryKey(CoreProperties.SQUID_PLUGIN)
.withKey(NOSONAR_RULE_CONFIG_KEY);
rules.addAll(ruleFinder.findAll(ruleQuery));
saveFileMeasures(context, rules);
}
}
protected void saveFileMeasures(DecoratorContext context, Collection<Rule> rules) {
CountDistributionBuilder distrib = new CountDistributionBuilder(TaglistMetrics.TAGS_DISTRIBUTION);
int mandatory = 0;
int optional = 0;
int noSonarTags = 0;
for (Rule rule : rules) {
ActiveRule activeRule = rulesProfile.getActiveRule(rule);
if (activeRule != null) {
for (Violation violation : context.getViolations()) {
if (violation.getRule().equals(rule)) {
- if (isMandatory(activeRule.getPriority())) {
+ if (isMandatory(activeRule.getSeverity())) {
mandatory++;
} else {
optional++;
}
if (CoreProperties.SQUID_PLUGIN.equals(rule.getRepositoryKey())) {
noSonarTags++;
}
distrib.add(getTagName(activeRule));
}
}
}
}
saveMeasure(context, TaglistMetrics.TAGS, mandatory + optional);
saveMeasure(context, TaglistMetrics.MANDATORY_TAGS, mandatory);
saveMeasure(context, TaglistMetrics.OPTIONAL_TAGS, optional);
saveMeasure(context, TaglistMetrics.NOSONAR_TAGS, noSonarTags);
if (!distrib.isEmpty()) {
context.saveMeasure(distrib.build().setPersistenceMode(PersistenceMode.MEMORY));
}
}
protected static boolean isMandatory(RulePriority priority) {
return priority.equals(RulePriority.BLOCKER) || priority.equals(RulePriority.CRITICAL);
}
private String getTagName(ActiveRule rule) {
if (CoreProperties.CHECKSTYLE_PLUGIN.equals(rule.getRepositoryKey())) {
return rule.getParameter("format");
} else if (CoreProperties.SQUID_PLUGIN.equals(rule.getRepositoryKey())) {
return "NOSONAR";
}
throw new SonarException("Taglist plugin doesn't work with rule: " + rule);
}
private void saveMeasure(DecoratorContext context, Metric metric, int value) {
if (value > 0) {
context.saveMeasure(metric, (double) value);
}
}
}
| true | true | protected void saveFileMeasures(DecoratorContext context, Collection<Rule> rules) {
CountDistributionBuilder distrib = new CountDistributionBuilder(TaglistMetrics.TAGS_DISTRIBUTION);
int mandatory = 0;
int optional = 0;
int noSonarTags = 0;
for (Rule rule : rules) {
ActiveRule activeRule = rulesProfile.getActiveRule(rule);
if (activeRule != null) {
for (Violation violation : context.getViolations()) {
if (violation.getRule().equals(rule)) {
if (isMandatory(activeRule.getPriority())) {
mandatory++;
} else {
optional++;
}
if (CoreProperties.SQUID_PLUGIN.equals(rule.getRepositoryKey())) {
noSonarTags++;
}
distrib.add(getTagName(activeRule));
}
}
}
}
saveMeasure(context, TaglistMetrics.TAGS, mandatory + optional);
saveMeasure(context, TaglistMetrics.MANDATORY_TAGS, mandatory);
saveMeasure(context, TaglistMetrics.OPTIONAL_TAGS, optional);
saveMeasure(context, TaglistMetrics.NOSONAR_TAGS, noSonarTags);
if (!distrib.isEmpty()) {
context.saveMeasure(distrib.build().setPersistenceMode(PersistenceMode.MEMORY));
}
}
| protected void saveFileMeasures(DecoratorContext context, Collection<Rule> rules) {
CountDistributionBuilder distrib = new CountDistributionBuilder(TaglistMetrics.TAGS_DISTRIBUTION);
int mandatory = 0;
int optional = 0;
int noSonarTags = 0;
for (Rule rule : rules) {
ActiveRule activeRule = rulesProfile.getActiveRule(rule);
if (activeRule != null) {
for (Violation violation : context.getViolations()) {
if (violation.getRule().equals(rule)) {
if (isMandatory(activeRule.getSeverity())) {
mandatory++;
} else {
optional++;
}
if (CoreProperties.SQUID_PLUGIN.equals(rule.getRepositoryKey())) {
noSonarTags++;
}
distrib.add(getTagName(activeRule));
}
}
}
}
saveMeasure(context, TaglistMetrics.TAGS, mandatory + optional);
saveMeasure(context, TaglistMetrics.MANDATORY_TAGS, mandatory);
saveMeasure(context, TaglistMetrics.OPTIONAL_TAGS, optional);
saveMeasure(context, TaglistMetrics.NOSONAR_TAGS, noSonarTags);
if (!distrib.isEmpty()) {
context.saveMeasure(distrib.build().setPersistenceMode(PersistenceMode.MEMORY));
}
}
|
diff --git a/JTT/src/com/aragaer/jtt/JTTService.java b/JTT/src/com/aragaer/jtt/JTTService.java
index b6c40a6..8021d9f 100644
--- a/JTT/src/com/aragaer/jtt/JTTService.java
+++ b/JTT/src/com/aragaer/jtt/JTTService.java
@@ -1,252 +1,254 @@
package com.aragaer.jtt;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.PowerManager;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.RemoteViews;
public class JTTService extends Service {
private static final String TAG = JTTService.class.getSimpleName();
private JTT calculator;
private NotificationManager nm;
private static final int flags_ongoing = Notification.FLAG_ONGOING_EVENT
| Notification.FLAG_NO_CLEAR;
private static final int APP_ID = 0;
private PendingIntent pending_main;
private JTTHour.StringsHelper hs;
private JTTTicker ticker = new JTTTicker();
private boolean notify, force_stop = false;
ArrayList<Messenger> mClients = new ArrayList<Messenger>();
public static final int MSG_TOGGLE_NOTIFY = 0;
public static final int MSG_UPDATE_LOCATION = 1;
public static final int MSG_REGISTER_CLIENT = 2;
public static final int MSG_UNREGISTER_CLIENT = 3;
public static final int MSG_HOUR = 4;
public static final int MSG_STOP = 5;
final Messenger mMessenger = new Messenger(new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_TOGGLE_NOTIFY:
notify = msg.getData().getBoolean("notify");
if (notify)
notify_helper(ticker.hn, ticker.hf);
else
nm.cancel(APP_ID);
break;
case MSG_UPDATE_LOCATION:
String ll[] = msg.getData().getString("latlon").split(":");
calculator.move(Float.parseFloat(ll[0]),
Float.parseFloat(ll[1]));
+ ticker.stop_ticking();
ticker.reset();
+ ticker.start_ticking();
break;
case MSG_REGISTER_CLIENT:
try {
msg.replyTo.send(Message.obtain(null, MSG_HOUR, ticker.hn,
ticker.hf));
mClients.add(msg.replyTo);
} catch (RemoteException e) {
Log.w(TAG, "Client registered but failed to get data");
}
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;
case MSG_STOP:
force_stop = true;
stopSelf();
break;
default:
super.handleMessage(msg);
break;
}
}
});
private String app_name;
private static final DateFormat df = new SimpleDateFormat("HH:mm");
private void notify_helper(int hn, int hf) {
Notification n = new Notification(R.drawable.notification_icon,
app_name, System.currentTimeMillis());
RemoteViews rv = new RemoteViews(getPackageName(),
R.layout.notification);
n.flags = flags_ongoing;
n.iconLevel = hn;
rv.setTextViewText(R.id.image, JTTHour.Glyphs[hn]);
rv.setTextViewText(R.id.title, hs.getHrOf(hn));
rv.setTextViewText(R.id.percent, String.format("%d%%", hf));
rv.setProgressBar(R.id.fraction, 100, hf, false);
rv.setTextViewText(R.id.start, df.format(ticker.start));
rv.setTextViewText(R.id.end, df.format(ticker.end));
n.contentIntent = pending_main;
n.contentView = rv;
nm.notify(APP_ID, n);
}
private void doNotify(int n, int f) {
if (notify)
notify_helper(n, f);
int i = mClients.size();
if (i == 0)
return;
Message msg = Message.obtain(null, MSG_HOUR, n, f);
while (i-- > 0)
try {
mClients.get(i).send(msg);
} catch (RemoteException e) {
/*
* The client is dead. Remove it from the list; we are going
* through the list from back to front so this is safe to do
* inside the loop.
*/
mClients.remove(i);
}
}
@Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
private final BroadcastReceiver on = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ticker.start_ticking();
}
};
private final BroadcastReceiver off = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ticker.stop_ticking();
}
};
private final BroadcastReceiver timeset = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ticker.stop_ticking();
ticker.reset();
ticker.start_ticking();
}
};
@Override
public void onStart(Intent intent, int startid) {
Log.i(TAG, "Service starting");
hs = new JTTHour.StringsHelper(this);
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
String[] ll = settings.getString("jtt_loc", "0.0:0.0").split(":");
calculator = new JTT(Float.parseFloat(ll[0]), Float.parseFloat(ll[1]));
Intent JTTMain = new Intent(getBaseContext(), JTTMainActivity.class);
pending_main = PendingIntent.getActivity(this, 0, JTTMain, 0);
notify = settings.getBoolean("jtt_notify", true);
app_name = getString(R.string.app_name);
nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (!notify)
nm.cancel(APP_ID);
registerReceiver(on, new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(off, new IntentFilter(Intent.ACTION_SCREEN_OFF));
registerReceiver(timeset, new IntentFilter(Intent.ACTION_TIME_CHANGED));
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (pm.isScreenOn())
ticker.start_ticking();
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "Service destroying");
unregisterReceiver(on);
unregisterReceiver(off);
unregisterReceiver(timeset);
ticker.stop_ticking();
if (force_stop)
nm.cancel(APP_ID);
else {
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
final boolean boot = settings.getBoolean("jtt_bootup", true);
if (notify || boot) {
Notification n = new Notification(R.drawable.notification_icon,
app_name, System.currentTimeMillis());
n.setLatestEventInfo(JTTService.this, getString(R.string.srv_fail),
getString(R.string.srv_fail_ex), pending_main);
n.flags = boot ? flags_ongoing : 0;
nm.notify(APP_ID, n);
}
}
}
public static class JTTStartupReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean("jtt_bootup", true))
context.startService(new Intent(context, JTTService.class));
}
}
private final class JTTTicker extends Ticker {
protected int day;
public int hn, hf;
public JTTTicker() {
super(6, 100);
day = JTT.longToJDN(System.currentTimeMillis());
}
@Override
public void exhausted() {
long[] t = calculator.computeTr(day++);
for (long l : t)
tr.add(l);
}
@Override
public void reset() {
day = JTT.longToJDN(System.currentTimeMillis());
super.reset();
}
@Override
public void handleSub(int tick, int sub) {
doNotify(hn, hf = sub);
}
@Override
public void handleTick(int tick, int sub) {
// we're always adding 2 times to tr - 1 sunrise and 1 sunset
// during day tr[0] is sunrise and total number is even
// on sunset it is discarded and total number is odd
int isDay = 1 - tr.size() % 2;
doNotify(hn = (tick + isDay * 6) % 12, hf = sub);
}
};
}
| false | true | public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_TOGGLE_NOTIFY:
notify = msg.getData().getBoolean("notify");
if (notify)
notify_helper(ticker.hn, ticker.hf);
else
nm.cancel(APP_ID);
break;
case MSG_UPDATE_LOCATION:
String ll[] = msg.getData().getString("latlon").split(":");
calculator.move(Float.parseFloat(ll[0]),
Float.parseFloat(ll[1]));
ticker.reset();
break;
case MSG_REGISTER_CLIENT:
try {
msg.replyTo.send(Message.obtain(null, MSG_HOUR, ticker.hn,
ticker.hf));
mClients.add(msg.replyTo);
} catch (RemoteException e) {
Log.w(TAG, "Client registered but failed to get data");
}
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;
case MSG_STOP:
force_stop = true;
stopSelf();
break;
default:
super.handleMessage(msg);
break;
}
}
| public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_TOGGLE_NOTIFY:
notify = msg.getData().getBoolean("notify");
if (notify)
notify_helper(ticker.hn, ticker.hf);
else
nm.cancel(APP_ID);
break;
case MSG_UPDATE_LOCATION:
String ll[] = msg.getData().getString("latlon").split(":");
calculator.move(Float.parseFloat(ll[0]),
Float.parseFloat(ll[1]));
ticker.stop_ticking();
ticker.reset();
ticker.start_ticking();
break;
case MSG_REGISTER_CLIENT:
try {
msg.replyTo.send(Message.obtain(null, MSG_HOUR, ticker.hn,
ticker.hf));
mClients.add(msg.replyTo);
} catch (RemoteException e) {
Log.w(TAG, "Client registered but failed to get data");
}
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;
case MSG_STOP:
force_stop = true;
stopSelf();
break;
default:
super.handleMessage(msg);
break;
}
}
|
diff --git a/src/org/gridlab/gridsphere/provider/portletui/tags/ActionTag.java b/src/org/gridlab/gridsphere/provider/portletui/tags/ActionTag.java
index be57cfa85..25c744488 100644
--- a/src/org/gridlab/gridsphere/provider/portletui/tags/ActionTag.java
+++ b/src/org/gridlab/gridsphere/provider/portletui/tags/ActionTag.java
@@ -1,351 +1,349 @@
/**
* @author <a href="mailto:[email protected]">Jason Novotny</a>
* @version $Id$
*/
package org.gridlab.gridsphere.provider.portletui.tags;
import org.gridlab.gridsphere.portlet.*;
import org.gridlab.gridsphere.portlet.Portlet;
import org.gridlab.gridsphere.portlet.PortletResponse;
import org.gridlab.gridsphere.portlet.impl.SportletProperties;
import org.gridlab.gridsphere.portlet.jsrimpl.PortletURLImpl;
import org.gridlab.gridsphere.provider.portletui.beans.ActionParamBean;
import org.gridlab.gridsphere.provider.portletui.beans.ImageBean;
import javax.portlet.*;
import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagData;
import javax.servlet.jsp.tagext.TagExtraInfo;
import javax.servlet.jsp.tagext.VariableInfo;
import java.util.Iterator;
import java.util.List;
/**
* The abstract <code>ActionTag</code> is used by other Action tags to contain <code>DefaultPortletAction</code>s
* and possibly <code>ActionParamTag</code>s
*/
public abstract class ActionTag extends BaseComponentTag {
protected String action = null;
protected String anchor = null;
protected String var = null;
protected String key = null;
protected boolean isSecure = false;
protected PortletURI actionURI = null;
protected PortletURLImpl actionURL = null;
protected String windowState = null;
protected String portletMode = null;
protected DefaultPortletAction portletAction = null;
protected List paramBeans = null;
protected String label = null;
protected ImageBean imageBean = null;
protected boolean paramPrefixing = true;
public static class TEI extends TagExtraInfo {
public VariableInfo[] getVariableInfo(TagData tagData) {
VariableInfo vi[] = null;
String var = tagData.getAttributeString("var");
if (var != null) {
vi = new VariableInfo[1];
vi[0] = new VariableInfo(var, "java.lang.String", true, VariableInfo.AT_BEGIN);
}
return vi;
}
}
/**
* Sets the name of the variable to export as a RenderURL object
*
* @param var the name of the variable to export as a RenderURL object
*/
public void setVar(String var) {
this.var = var;
}
/**
* Returns the name of the exported RenderURL object
*
* @return the exported variable
*/
public String getVar() {
return var;
}
/**
* Sets the text that should be added at the end of generated URL
*
* @param anchor the action link key
*/
public void setAnchor(String anchor) {
this.anchor = anchor;
}
/**
* Returns the anchor used to identify text that should be added at the end of generated URL
*
* @return the anchor
*/
public String getAnchor() {
return anchor;
}
/**
* Sets the action link key used to locate localized text
*
* @param key the action link key
*/
public void setKey(String key) {
this.key = key;
}
/**
* Returns the action link key used to locate localized text
*
* @return the action link key
*/
public String getKey() {
return key;
}
/**
* Sets the label identified with the portlet component to link to
*
* @param label the action link key
*/
public void setLabel(String label) {
this.label = label;
}
/**
* Returns the label identified with the portlet component to link to
*
* @return the label
*/
public String getLabel() {
return label;
}
/**
* If secure is true, then use https, otherwise use http
*
* @param isSecure
*/
public void setSecure(boolean isSecure) {
this.isSecure = isSecure;
}
/**
* Returns true if this actiontag is secure e.g. https, flase otherwise
*
* @return true if this actiontag is secure, false otherwise
*/
public boolean getSecure() {
return isSecure;
}
public void setPortletMode(String portletMode) {
this.portletMode = portletMode;
}
public String getPortletMode() {
return portletMode;
}
public void setWindowState(String windowState) {
this.windowState = windowState;
}
public String getWindowState() {
return windowState;
}
public void setAction(String action) {
this.action = action;
}
public String getAction() {
return action;
}
public void setPortletAction(DefaultPortletAction portletAction) {
this.portletAction = portletAction;
}
public DefaultPortletAction getPortletAction() {
return portletAction;
}
public void addParamBean(ActionParamBean paramBean) {
paramBeans.add(paramBean);
}
public void removeParamBean(ActionParamBean paramBean) {
paramBeans.remove(paramBean);
}
public List getParamBeans() {
return paramBeans;
}
protected String createJSRActionURI(PortletURL url) throws JspException {
// Builds a URI containing the actin and associated params
RenderResponse res = (RenderResponse) pageContext.getAttribute(SportletProperties.RENDER_RESPONSE, PageContext.REQUEST_SCOPE);
this.actionURL = (PortletURLImpl) url;
RenderRequest req = (RenderRequest) pageContext.getAttribute(SportletProperties.RENDER_REQUEST, PageContext.REQUEST_SCOPE);
// action is a required attribute except for FormTag
if (windowState == null) {
windowState = req.getWindowState().toString();
}
if (portletMode == null) {
portletMode = req.getPortletMode().toString();
}
if (label != null) {
- //paramPrefixing = false;
res.setProperty("label", label);
actionURL.setComponentID(label);
}
if (windowState != null) {
WindowState state = new WindowState(windowState);
try {
- //actionURL = res.createRenderURL();
//System.err.println("set state to:" + state);
actionURL.setWindowState(state);
} catch (WindowStateException e) {
throw new JspException("Unknown window state in renderURL tag: " + windowState);
}
}
if (portletMode != null) {
PortletMode mode = new PortletMode(portletMode);
try {
//actionURL = res.createRenderURL();
actionURL.setPortletMode(mode);
//System.err.println("set mode to:" + mode);
} catch (PortletModeException e) {
throw new JspException("Unknown portlet mode in renderURL tag: " + portletMode);
}
}
ServletRequest request = pageContext.getRequest();
String compId = (String) request.getAttribute(SportletProperties.GP_COMPONENT_ID);
if (action != null) {
if (compId == null) {
actionURL.setAction(action);
portletAction = new DefaultPortletAction(action);
} else {
actionURL.setAction(compId + "%" + action);
portletAction = new DefaultPortletAction(compId + "%" + action);
}
} else {
if (compId == null) {
portletAction = new DefaultPortletAction(action);
} else {
portletAction = new DefaultPortletAction(compId + "%" + action);
}
}
if (!paramBeans.isEmpty()) {
String id = createUniquePrefix(2);
Iterator it = paramBeans.iterator();
if (paramPrefixing) {
actionURL.setParameter(SportletProperties.PREFIX, id);
portletAction.addParameter(SportletProperties.PREFIX, id);
}
while (it.hasNext()) {
ActionParamBean pbean = (ActionParamBean) it.next();
//System.err.println("have param bean name= " + pbean.getName() + " value= " + pbean.getValue());
if (paramPrefixing) {
actionURL.setParameter(id + "_" + pbean.getName(), pbean.getValue());
portletAction.addParameter(id + "_" + pbean.getName(), pbean.getValue());
} else {
actionURL.setParameter(pbean.getName(), pbean.getValue());
portletAction.addParameter(pbean.getName(), pbean.getValue());
}
}
}
//System.err.println("printing action URL = " + actionURL.toString());
return actionURL.toString();
}
public String createActionURI() throws JspException {
if (isJSR()) {
RenderResponse res = (RenderResponse) pageContext.getAttribute(SportletProperties.RENDER_RESPONSE, PageContext.REQUEST_SCOPE);
return createJSRActionURI(res.createActionURL());
}
return createGSActionURI();
}
public String createGSActionURI() throws JspException {
// Builds a URI containing the actin and associated params
PortletResponse res = (PortletResponse) pageContext.getAttribute("portletResponse");
// action is a required attribute except for FormTag
if (label != null) {
actionURI = res.createURI(label, isSecure);
} else if (windowState != null) {
PortletWindow.State state = PortletWindow.State.toState(windowState);
actionURI = res.createURI(state);
} else if (portletMode != null) {
Portlet.Mode mode = Portlet.Mode.toMode(portletMode);
actionURI = res.createURI(mode);
} else {
actionURI = res.createURI(isSecure);
}
if (action != null) {
ServletRequest request = pageContext.getRequest();
String compId = (String) request.getAttribute(SportletProperties.GP_COMPONENT_ID);
if (compId == null) {
portletAction = new DefaultPortletAction(action);
} else {
portletAction = new DefaultPortletAction(compId + "%" + action);
}
Iterator it = paramBeans.iterator();
if (!paramBeans.isEmpty()) {
String id = createUniquePrefix(2);
portletAction.addParameter(SportletProperties.PREFIX, id);
while (it.hasNext()) {
ActionParamBean pbean = (ActionParamBean) it.next();
portletAction.addParameter(id + "_" + pbean.getName(), pbean.getValue());
}
}
actionURI.addAction(portletAction);
}
return actionURI.toString();
}
/**
* A string utility that produces a string composed of
* <code>numChars</code> number of characters
*
* @param numChars the number of characters in the resulting <code>String</code>
* @return the <code>String</code>
*/
private String createUniquePrefix(int numChars) {
StringBuffer s = new StringBuffer();
for (int i = 0; i <= numChars; i++) {
int nextChar = (int) (Math.random() * 62);
if (nextChar < 10) //0-9
s.append(nextChar);
else if (nextChar < 36) //a-z
s.append((char) (nextChar - 10 + 'a'));
else
s.append((char) (nextChar - 36 + 'A'));
}
return s.toString();
}
}
| false | true | protected String createJSRActionURI(PortletURL url) throws JspException {
// Builds a URI containing the actin and associated params
RenderResponse res = (RenderResponse) pageContext.getAttribute(SportletProperties.RENDER_RESPONSE, PageContext.REQUEST_SCOPE);
this.actionURL = (PortletURLImpl) url;
RenderRequest req = (RenderRequest) pageContext.getAttribute(SportletProperties.RENDER_REQUEST, PageContext.REQUEST_SCOPE);
// action is a required attribute except for FormTag
if (windowState == null) {
windowState = req.getWindowState().toString();
}
if (portletMode == null) {
portletMode = req.getPortletMode().toString();
}
if (label != null) {
//paramPrefixing = false;
res.setProperty("label", label);
actionURL.setComponentID(label);
}
if (windowState != null) {
WindowState state = new WindowState(windowState);
try {
//actionURL = res.createRenderURL();
//System.err.println("set state to:" + state);
actionURL.setWindowState(state);
} catch (WindowStateException e) {
throw new JspException("Unknown window state in renderURL tag: " + windowState);
}
}
if (portletMode != null) {
PortletMode mode = new PortletMode(portletMode);
try {
//actionURL = res.createRenderURL();
actionURL.setPortletMode(mode);
//System.err.println("set mode to:" + mode);
} catch (PortletModeException e) {
throw new JspException("Unknown portlet mode in renderURL tag: " + portletMode);
}
}
ServletRequest request = pageContext.getRequest();
String compId = (String) request.getAttribute(SportletProperties.GP_COMPONENT_ID);
if (action != null) {
if (compId == null) {
actionURL.setAction(action);
portletAction = new DefaultPortletAction(action);
} else {
actionURL.setAction(compId + "%" + action);
portletAction = new DefaultPortletAction(compId + "%" + action);
}
} else {
if (compId == null) {
portletAction = new DefaultPortletAction(action);
} else {
portletAction = new DefaultPortletAction(compId + "%" + action);
}
}
if (!paramBeans.isEmpty()) {
String id = createUniquePrefix(2);
Iterator it = paramBeans.iterator();
if (paramPrefixing) {
actionURL.setParameter(SportletProperties.PREFIX, id);
portletAction.addParameter(SportletProperties.PREFIX, id);
}
while (it.hasNext()) {
ActionParamBean pbean = (ActionParamBean) it.next();
//System.err.println("have param bean name= " + pbean.getName() + " value= " + pbean.getValue());
if (paramPrefixing) {
actionURL.setParameter(id + "_" + pbean.getName(), pbean.getValue());
portletAction.addParameter(id + "_" + pbean.getName(), pbean.getValue());
} else {
actionURL.setParameter(pbean.getName(), pbean.getValue());
portletAction.addParameter(pbean.getName(), pbean.getValue());
}
}
}
//System.err.println("printing action URL = " + actionURL.toString());
return actionURL.toString();
}
| protected String createJSRActionURI(PortletURL url) throws JspException {
// Builds a URI containing the actin and associated params
RenderResponse res = (RenderResponse) pageContext.getAttribute(SportletProperties.RENDER_RESPONSE, PageContext.REQUEST_SCOPE);
this.actionURL = (PortletURLImpl) url;
RenderRequest req = (RenderRequest) pageContext.getAttribute(SportletProperties.RENDER_REQUEST, PageContext.REQUEST_SCOPE);
// action is a required attribute except for FormTag
if (windowState == null) {
windowState = req.getWindowState().toString();
}
if (portletMode == null) {
portletMode = req.getPortletMode().toString();
}
if (label != null) {
res.setProperty("label", label);
actionURL.setComponentID(label);
}
if (windowState != null) {
WindowState state = new WindowState(windowState);
try {
//System.err.println("set state to:" + state);
actionURL.setWindowState(state);
} catch (WindowStateException e) {
throw new JspException("Unknown window state in renderURL tag: " + windowState);
}
}
if (portletMode != null) {
PortletMode mode = new PortletMode(portletMode);
try {
//actionURL = res.createRenderURL();
actionURL.setPortletMode(mode);
//System.err.println("set mode to:" + mode);
} catch (PortletModeException e) {
throw new JspException("Unknown portlet mode in renderURL tag: " + portletMode);
}
}
ServletRequest request = pageContext.getRequest();
String compId = (String) request.getAttribute(SportletProperties.GP_COMPONENT_ID);
if (action != null) {
if (compId == null) {
actionURL.setAction(action);
portletAction = new DefaultPortletAction(action);
} else {
actionURL.setAction(compId + "%" + action);
portletAction = new DefaultPortletAction(compId + "%" + action);
}
} else {
if (compId == null) {
portletAction = new DefaultPortletAction(action);
} else {
portletAction = new DefaultPortletAction(compId + "%" + action);
}
}
if (!paramBeans.isEmpty()) {
String id = createUniquePrefix(2);
Iterator it = paramBeans.iterator();
if (paramPrefixing) {
actionURL.setParameter(SportletProperties.PREFIX, id);
portletAction.addParameter(SportletProperties.PREFIX, id);
}
while (it.hasNext()) {
ActionParamBean pbean = (ActionParamBean) it.next();
//System.err.println("have param bean name= " + pbean.getName() + " value= " + pbean.getValue());
if (paramPrefixing) {
actionURL.setParameter(id + "_" + pbean.getName(), pbean.getValue());
portletAction.addParameter(id + "_" + pbean.getName(), pbean.getValue());
} else {
actionURL.setParameter(pbean.getName(), pbean.getValue());
portletAction.addParameter(pbean.getName(), pbean.getValue());
}
}
}
//System.err.println("printing action URL = " + actionURL.toString());
return actionURL.toString();
}
|
diff --git a/src/cz/muni/fi/spc/SchedVis/ui/SliderPanel.java b/src/cz/muni/fi/spc/SchedVis/ui/SliderPanel.java
index 2bb8733..a717393 100644
--- a/src/cz/muni/fi/spc/SchedVis/ui/SliderPanel.java
+++ b/src/cz/muni/fi/spc/SchedVis/ui/SliderPanel.java
@@ -1,188 +1,188 @@
/*
* This file is part of SchedVis.
*
* SchedVis 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.
*
* SchedVis 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 SchedVis. If not, see <http://www.gnu.org/licenses/>.
*/
/**
*
*/
package cz.muni.fi.spc.SchedVis.ui;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.tree.DefaultMutableTreeNode;
import cz.muni.fi.spc.SchedVis.Main;
import cz.muni.fi.spc.SchedVis.background.LookAhead;
import cz.muni.fi.spc.SchedVis.background.Player;
import cz.muni.fi.spc.SchedVis.model.entities.Event;
import cz.muni.fi.spc.SchedVis.model.entities.Machine;
import cz.muni.fi.spc.SchedVis.model.models.TimelineSliderModel;
/**
* Implements a timeline "widget," used to move forward or backwards on the
* timeline.
*
* @author Lukáš Petrovický <[email protected]>
*
*/
public final class SliderPanel extends JPanel implements ChangeListener,
ActionListener {
private static final long serialVersionUID = 6091479520934383104L;
private TimelineSliderModel tlsm = null;
private final JButton btnStart = new JButton("|<");
private final JButton btnEnd = new JButton(">|");
private final JButton btnPlay = new JButton("|>");
private final JButton btnPrev = new JButton("<<");
private final JButton btnNext = new JButton(">>");
private boolean playing = false;
/**
* The constructor.
*/
public SliderPanel() {
this.setLayout(new BorderLayout());
// left-side buttons
final JPanel innerPane = new JPanel();
innerPane.setLayout(new FlowLayout());
this.btnStart.setEnabled(false);
this.btnPrev.setEnabled(false);
innerPane.add(this.btnStart);
innerPane.add(this.btnPrev);
// middle slider
this.add(innerPane, BorderLayout.LINE_START);
final TimelineSlider slider = new TimelineSlider();
this.tlsm = TimelineSliderModel.getInstance(this);
slider.setModel(this.tlsm);
this.add(slider, BorderLayout.CENTER);
// right-side buttons
final JPanel innerPane2 = new JPanel();
innerPane2.setLayout(new FlowLayout());
innerPane2.add(this.btnPlay);
innerPane2.add(this.btnNext);
innerPane2.add(this.btnEnd);
this.add(innerPane2, BorderLayout.LINE_END);
// add action listeners to buttons
final JButton[] buttons = new JButton[] { this.btnStart, this.btnEnd,
this.btnNext, this.btnPrev, this.btnPlay };
for (final JButton b : buttons) {
b.addActionListener(this);
}
}
/**
* Listens to actions on the timeline buttons.
*/
@Override
public void actionPerformed(final ActionEvent e) {
final Object src = e.getSource();
if (src.equals(this.btnEnd)) {
this.tlsm.setValue(this.tlsm.getMaximum());
} else if (src.equals(this.btnStart)) {
this.tlsm.setValue(this.tlsm.getMinimum());
} else if (src.equals(this.btnPlay)) {
this.playing = !this.playing;
this.btnPlay.removeAll();
if (this.playing) {
this.btnPlay.add(new JLabel("||"));
} else {
this.btnPlay.add(new JLabel("|>"));
}
this.btnPlay.updateUI();
Player.getInstance().toggleStatus();
} else if (src.equals(this.btnNext) || src.equals(this.btnPrev)) {
if (src.equals(this.btnPrev)) {
try {
this.tlsm.setValue(Event.getPrevious(this.tlsm.getValue())
.getVirtualClock());
} catch (Exception ex) {
this.tlsm.setValue(Event.getFirst().getVirtualClock());
}
} else {
try {
this.tlsm.setValue(Event.getNext(this.tlsm.getValue())
.getVirtualClock());
} catch (Exception ex) {
this.tlsm.setValue(Event.getLast().getVirtualClock());
}
}
}
}
/**
* Listens to changes on the timeline slider.
*/
public void stateChanged(final ChangeEvent e) {
final Object src = e.getSource();
if (src.equals(this.tlsm)) {
- if (this.tlsm.getValue() <= 1) {
+ if (this.tlsm.getValue() < 1) {
return;
}
Integer value = this.tlsm.getValue();
if (!Event.existsTick(value)) {
this.tlsm.setValue(Event.getPrevious(value).getVirtualClock());
}
if (value.equals(this.tlsm.getMinimum())) {
this.btnPrev.setEnabled(false);
this.btnStart.setEnabled(false);
this.btnPlay.setEnabled(true);
this.btnNext.setEnabled(true);
this.btnEnd.setEnabled(true);
} else if (value.equals(this.tlsm.getMaximum())) {
this.btnPrev.setEnabled(true);
this.btnStart.setEnabled(true);
this.btnPlay.setEnabled(false);
this.btnNext.setEnabled(false);
this.btnEnd.setEnabled(false);
} else {
this.btnPlay.setEnabled(true);
this.btnPrev.setEnabled(true);
this.btnStart.setEnabled(true);
this.btnNext.setEnabled(true);
this.btnEnd.setEnabled(true);
}
if (!this.tlsm.getValueIsAdjusting()) {
Main.getFrame().setCursor(
Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
ScheduleTree.getInstance().updateUI();
// update the detail pane based on the tree selection
try {
DefaultMutableTreeNode n = (DefaultMutableTreeNode) ScheduleTree
.getInstance().getLastSelectedPathComponent();
if (n.getUserObject() instanceof Machine) {
Main.getFrame().updateDetail((Machine) n.getUserObject());
} else {
Main.getFrame().updateDetail(null);
}
} catch (NullPointerException ex) {
Main.getFrame().updateDetail(null);
}
DescriptionPane.getInstance().updateFrame(this.tlsm.getValue());
LookAhead.submit();
Main.getFrame().setCursor(
Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
}
}
| true | true | public void stateChanged(final ChangeEvent e) {
final Object src = e.getSource();
if (src.equals(this.tlsm)) {
if (this.tlsm.getValue() <= 1) {
return;
}
Integer value = this.tlsm.getValue();
if (!Event.existsTick(value)) {
this.tlsm.setValue(Event.getPrevious(value).getVirtualClock());
}
if (value.equals(this.tlsm.getMinimum())) {
this.btnPrev.setEnabled(false);
this.btnStart.setEnabled(false);
this.btnPlay.setEnabled(true);
this.btnNext.setEnabled(true);
this.btnEnd.setEnabled(true);
} else if (value.equals(this.tlsm.getMaximum())) {
this.btnPrev.setEnabled(true);
this.btnStart.setEnabled(true);
this.btnPlay.setEnabled(false);
this.btnNext.setEnabled(false);
this.btnEnd.setEnabled(false);
} else {
this.btnPlay.setEnabled(true);
this.btnPrev.setEnabled(true);
this.btnStart.setEnabled(true);
this.btnNext.setEnabled(true);
this.btnEnd.setEnabled(true);
}
if (!this.tlsm.getValueIsAdjusting()) {
Main.getFrame().setCursor(
Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
ScheduleTree.getInstance().updateUI();
// update the detail pane based on the tree selection
try {
DefaultMutableTreeNode n = (DefaultMutableTreeNode) ScheduleTree
.getInstance().getLastSelectedPathComponent();
if (n.getUserObject() instanceof Machine) {
Main.getFrame().updateDetail((Machine) n.getUserObject());
} else {
Main.getFrame().updateDetail(null);
}
} catch (NullPointerException ex) {
Main.getFrame().updateDetail(null);
}
DescriptionPane.getInstance().updateFrame(this.tlsm.getValue());
LookAhead.submit();
Main.getFrame().setCursor(
Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
}
| public void stateChanged(final ChangeEvent e) {
final Object src = e.getSource();
if (src.equals(this.tlsm)) {
if (this.tlsm.getValue() < 1) {
return;
}
Integer value = this.tlsm.getValue();
if (!Event.existsTick(value)) {
this.tlsm.setValue(Event.getPrevious(value).getVirtualClock());
}
if (value.equals(this.tlsm.getMinimum())) {
this.btnPrev.setEnabled(false);
this.btnStart.setEnabled(false);
this.btnPlay.setEnabled(true);
this.btnNext.setEnabled(true);
this.btnEnd.setEnabled(true);
} else if (value.equals(this.tlsm.getMaximum())) {
this.btnPrev.setEnabled(true);
this.btnStart.setEnabled(true);
this.btnPlay.setEnabled(false);
this.btnNext.setEnabled(false);
this.btnEnd.setEnabled(false);
} else {
this.btnPlay.setEnabled(true);
this.btnPrev.setEnabled(true);
this.btnStart.setEnabled(true);
this.btnNext.setEnabled(true);
this.btnEnd.setEnabled(true);
}
if (!this.tlsm.getValueIsAdjusting()) {
Main.getFrame().setCursor(
Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
ScheduleTree.getInstance().updateUI();
// update the detail pane based on the tree selection
try {
DefaultMutableTreeNode n = (DefaultMutableTreeNode) ScheduleTree
.getInstance().getLastSelectedPathComponent();
if (n.getUserObject() instanceof Machine) {
Main.getFrame().updateDetail((Machine) n.getUserObject());
} else {
Main.getFrame().updateDetail(null);
}
} catch (NullPointerException ex) {
Main.getFrame().updateDetail(null);
}
DescriptionPane.getInstance().updateFrame(this.tlsm.getValue());
LookAhead.submit();
Main.getFrame().setCursor(
Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
}
|
diff --git a/gdx/src/com/badlogic/gdx/utils/GdxNativesLoader.java b/gdx/src/com/badlogic/gdx/utils/GdxNativesLoader.java
index de3c66e81..9ac6a1ece 100644
--- a/gdx/src/com/badlogic/gdx/utils/GdxNativesLoader.java
+++ b/gdx/src/com/badlogic/gdx/utils/GdxNativesLoader.java
@@ -1,116 +1,117 @@
/*
* Copyright 2010 Mario Zechner ([email protected]), Nathan Sweet ([email protected])
*
* 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.badlogic.gdx.utils;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
public class GdxNativesLoader {
static boolean nativesLoaded = false;
/**
* loads the necessary libraries depending on the operating system
*/
public static boolean loadLibraries() {
if (nativesLoaded)
return true;
String os = System.getProperty("os.name");
String arch = System.getProperty("os.arch");
boolean is64Bit = false;
if (arch.equals("amd64"))
is64Bit = true;
String prefix = getLibraryPrefix();
String suffix = getLibrarySuffix();
String libName = prefix + "gdx" + (is64Bit?"-64":"") + suffix;
if(!loadLibrary(libName, "/", System.getProperty("java.io.tmpdir") + File.separator)) {
return false;
} else {
nativesLoaded = true;
return true;
}
}
public static String getLibraryPrefix() {
String os = System.getProperty("os.name");
if(os.contains("Windows"))
return "";
else
return "lib";
}
public static String getLibrarySuffix() {
String os = System.getProperty("os.name");
if(os.contains("Windows"))
return ".dll";
if(os.contains("Linux"))
return ".so";
if(os.contains("Mac"))
return ".dylib";
return "";
}
public static boolean is64Bit() {
String arch = System.getProperty("os.arch");
return arch.toLowerCase().contains("amd64");
}
public static boolean loadLibrary(String libName, String classPath,
String outputPath) {
// if (new File(outputPath + libName).exists())
// return true;
InputStream in = null;
BufferedOutputStream out = null;
try {
+ String tmpName = System.nanoTime() + libName;
in = GdxNativesLoader.class
.getResourceAsStream(classPath + libName);
out = new BufferedOutputStream(new FileOutputStream(outputPath
- + libName));
+ + tmpName));
byte[] bytes = new byte[1024 * 4];
while (true) {
int read_bytes = in.read(bytes);
if (read_bytes == -1)
break;
out.write(bytes, 0, read_bytes);
}
out.close();
out = null;
in.close();
in = null;
- System.load(outputPath + libName);
+ System.load(outputPath + tmpName);
return true;
} catch (Throwable t) {
System.err.println("GdxNativesLoader: Couldn't unpack and load native '" + libName + "'");
return false;
} finally {
if (out != null)
try {
out.close();
} catch (Exception ex) {
}
;
if (in != null)
try {
in.close();
} catch (Exception ex) {
}
}
}
}
| false | true | public static boolean loadLibrary(String libName, String classPath,
String outputPath) {
// if (new File(outputPath + libName).exists())
// return true;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = GdxNativesLoader.class
.getResourceAsStream(classPath + libName);
out = new BufferedOutputStream(new FileOutputStream(outputPath
+ libName));
byte[] bytes = new byte[1024 * 4];
while (true) {
int read_bytes = in.read(bytes);
if (read_bytes == -1)
break;
out.write(bytes, 0, read_bytes);
}
out.close();
out = null;
in.close();
in = null;
System.load(outputPath + libName);
return true;
} catch (Throwable t) {
System.err.println("GdxNativesLoader: Couldn't unpack and load native '" + libName + "'");
return false;
} finally {
if (out != null)
try {
out.close();
} catch (Exception ex) {
}
;
if (in != null)
try {
in.close();
} catch (Exception ex) {
}
}
}
| public static boolean loadLibrary(String libName, String classPath,
String outputPath) {
// if (new File(outputPath + libName).exists())
// return true;
InputStream in = null;
BufferedOutputStream out = null;
try {
String tmpName = System.nanoTime() + libName;
in = GdxNativesLoader.class
.getResourceAsStream(classPath + libName);
out = new BufferedOutputStream(new FileOutputStream(outputPath
+ tmpName));
byte[] bytes = new byte[1024 * 4];
while (true) {
int read_bytes = in.read(bytes);
if (read_bytes == -1)
break;
out.write(bytes, 0, read_bytes);
}
out.close();
out = null;
in.close();
in = null;
System.load(outputPath + tmpName);
return true;
} catch (Throwable t) {
System.err.println("GdxNativesLoader: Couldn't unpack and load native '" + libName + "'");
return false;
} finally {
if (out != null)
try {
out.close();
} catch (Exception ex) {
}
;
if (in != null)
try {
in.close();
} catch (Exception ex) {
}
}
}
|
diff --git a/src/org/apache/fop/fo/flow/ExternalGraphic.java b/src/org/apache/fop/fo/flow/ExternalGraphic.java
index ff175c124..e5ce14930 100644
--- a/src/org/apache/fop/fo/flow/ExternalGraphic.java
+++ b/src/org/apache/fop/fo/flow/ExternalGraphic.java
@@ -1,267 +1,268 @@
/*
* $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
*/
package org.apache.fop.fo.flow;
// FOP
import org.apache.fop.fo.*;
import org.apache.fop.fo.properties.*;
import org.apache.fop.layout.*;
import org.apache.fop.apps.FOPException;
import org.apache.fop.image.*;
// Java
import java.util.Enumeration;
import java.util.Hashtable;
import java.net.URL;
import java.net.MalformedURLException;
public class ExternalGraphic extends FObj {
int breakAfter;
int breakBefore;
int align;
int startIndent;
int endIndent;
int spaceBefore;
int spaceAfter;
String src;
int height;
int width;
String id;
ImageArea imageArea;
public ExternalGraphic(FObj parent, PropertyList propertyList) {
super(parent, propertyList);
this.name = "fo:external-graphic";
}
public Status layout(Area area) throws FOPException {
if (this.marker == START) {
// Common Accessibility Properties
AccessibilityProps mAccProps = propMgr.getAccessibilityProps();
// Common Aural Properties
AuralProps mAurProps = propMgr.getAuralProps();
// Common Border, Padding, and Background Properties
BorderAndPadding bap = propMgr.getBorderAndPadding();
BackgroundProps bProps = propMgr.getBackgroundProps();
// Common Margin Properties-Inline
MarginInlineProps mProps = propMgr.getMarginInlineProps();
// Common Relative Position Properties
RelativePositionProps mRelProps = propMgr.getRelativePositionProps();
// this.properties.get("alignment-adjust");
// this.properties.get("alignment-baseline");
// this.properties.get("baseline-shift");
// this.properties.get("block-progression-dimension");
// this.properties.get("content-height");
// this.properties.get("content-type");
// this.properties.get("content-width");
// this.properties.get("display-align");
// this.properties.get("dominant-baseline");
// this.properties.get("height");
// this.properties.get("id");
// this.properties.get("inline-progression-dimension");
// this.properties.get("keep-with-next");
// this.properties.get("keep-with-previous");
// this.properties.get("line-height");
// this.properties.get("line-height-shift-adjustment");
// this.properties.get("overflow");
// this.properties.get("scaling");
// this.properties.get("scaling-method");
// this.properties.get("src");
// this.properties.get("text-align");
// this.properties.get("width");
// FIXME
this.align = this.properties.get("text-align").getEnum();
this.startIndent =
this.properties.get("start-indent").getLength().mvalue();
this.endIndent =
this.properties.get("end-indent").getLength().mvalue();
this.spaceBefore =
this.properties.get("space-before.optimum").getLength().mvalue();
this.spaceAfter =
this.properties.get("space-after.optimum").getLength().mvalue();
this.src = this.properties.get("src").getString();
this.width = this.properties.get("width").getLength().mvalue();
this.height = this.properties.get("height").getLength().mvalue();
this.id = this.properties.get("id").getString();
area.getIDReferences().createID(id);
/*
* if (area instanceof BlockArea) {
* area.end();
* }
* if (this.isInTableCell) {
* startIndent += forcedStartOffset;
* endIndent = area.getAllocationWidth() - forcedWidth -
* forcedStartOffset;
* }
*/
this.marker = 0;
}
try {
FopImage img = FopImageFactory.Make(src);
// if width / height needs to be computed
if ((width == 0) || (height == 0)) {
// aspect ratio
double imgWidth = img.getWidth();
double imgHeight = img.getHeight();
if ((width == 0) && (height == 0)) {
width = (int)((imgWidth * 1000d));
height = (int)((imgHeight * 1000d));
} else if (height == 0) {
height = (int)((imgHeight * ((double)width)) / imgWidth);
} else if (width == 0) {
width = (int)((imgWidth * ((double)height)) / imgHeight);
}
}
// scale image if it doesn't fit in the area/page
// Need to be more tested...
double ratio = ((double)width) / ((double)height);
int areaWidth = area.getAllocationWidth() - startIndent
- endIndent;
- int pageHeight = area.getPage().getHeight();
+ int pageHeight = area.getPage().getBody().getMaxHeight()
+ - spaceBefore;
if (height > pageHeight) {
height = pageHeight;
width = (int)(ratio * ((double)height));
}
if (width > areaWidth) {
width = areaWidth;
height = (int)(((double)width) / ratio);
}
if (area.spaceLeft() < (height + spaceBefore)) {
return new Status(Status.AREA_FULL_NONE);
}
this.imageArea =
new ImageArea(propMgr.getFontState(area.getFontInfo()), img,
area.getAllocationWidth(), width, height,
startIndent, endIndent, align);
if ((spaceBefore != 0) && (this.marker == 0)) {
area.addDisplaySpace(spaceBefore);
}
if (marker == 0) {
// configure id
area.getIDReferences().configureID(id, area);
}
imageArea.start();
imageArea.end();
// area.addChild(imageArea);
// area.increaseHeight(imageArea.getHeight());
if (spaceAfter != 0) {
area.addDisplaySpace(spaceAfter);
}
if (breakBefore == BreakBefore.PAGE
|| ((spaceBefore + imageArea.getHeight())
> area.spaceLeft())) {
return new Status(Status.FORCE_PAGE_BREAK);
}
if (breakBefore == BreakBefore.ODD_PAGE) {
return new Status(Status.FORCE_PAGE_BREAK_ODD);
}
if (breakBefore == BreakBefore.EVEN_PAGE) {
return new Status(Status.FORCE_PAGE_BREAK_EVEN);
}
if (area instanceof BlockArea) {
BlockArea ba = (BlockArea)area;
LineArea la = ba.getCurrentLineArea();
if (la == null) {
return new Status(Status.AREA_FULL_NONE);
}
la.addPending();
if (imageArea.getContentWidth() > la.getRemainingWidth()) {
la = ba.createNextLineArea();
if (la == null) {
return new Status(Status.AREA_FULL_NONE);
}
}
la.addInlineArea(imageArea);
} else {
area.addChild(imageArea);
area.increaseHeight(imageArea.getContentHeight());
}
imageArea.setPage(area.getPage());
if (breakAfter == BreakAfter.PAGE) {
this.marker = BREAK_AFTER;
return new Status(Status.FORCE_PAGE_BREAK);
}
if (breakAfter == BreakAfter.ODD_PAGE) {
this.marker = BREAK_AFTER;
return new Status(Status.FORCE_PAGE_BREAK_ODD);
}
if (breakAfter == BreakAfter.EVEN_PAGE) {
this.marker = BREAK_AFTER;
return new Status(Status.FORCE_PAGE_BREAK_EVEN);
}
} catch (MalformedURLException urlex) {
// bad URL
log.error("Error while creating area : "
+ urlex.getMessage());
} catch (FopImageException imgex) {
// image error
log.error("Error while creating area : "
+ imgex.getMessage());
}
// if (area instanceof BlockArea) {
// area.start();
// }
return new Status(Status.OK);
}
public static FObj.Maker maker() {
return new ExternalGraphic.Maker();
}
public static class Maker extends FObj.Maker {
public FObj make(FObj parent,
PropertyList propertyList) throws FOPException {
return new ExternalGraphic(parent, propertyList);
}
}
}
| true | true | public Status layout(Area area) throws FOPException {
if (this.marker == START) {
// Common Accessibility Properties
AccessibilityProps mAccProps = propMgr.getAccessibilityProps();
// Common Aural Properties
AuralProps mAurProps = propMgr.getAuralProps();
// Common Border, Padding, and Background Properties
BorderAndPadding bap = propMgr.getBorderAndPadding();
BackgroundProps bProps = propMgr.getBackgroundProps();
// Common Margin Properties-Inline
MarginInlineProps mProps = propMgr.getMarginInlineProps();
// Common Relative Position Properties
RelativePositionProps mRelProps = propMgr.getRelativePositionProps();
// this.properties.get("alignment-adjust");
// this.properties.get("alignment-baseline");
// this.properties.get("baseline-shift");
// this.properties.get("block-progression-dimension");
// this.properties.get("content-height");
// this.properties.get("content-type");
// this.properties.get("content-width");
// this.properties.get("display-align");
// this.properties.get("dominant-baseline");
// this.properties.get("height");
// this.properties.get("id");
// this.properties.get("inline-progression-dimension");
// this.properties.get("keep-with-next");
// this.properties.get("keep-with-previous");
// this.properties.get("line-height");
// this.properties.get("line-height-shift-adjustment");
// this.properties.get("overflow");
// this.properties.get("scaling");
// this.properties.get("scaling-method");
// this.properties.get("src");
// this.properties.get("text-align");
// this.properties.get("width");
// FIXME
this.align = this.properties.get("text-align").getEnum();
this.startIndent =
this.properties.get("start-indent").getLength().mvalue();
this.endIndent =
this.properties.get("end-indent").getLength().mvalue();
this.spaceBefore =
this.properties.get("space-before.optimum").getLength().mvalue();
this.spaceAfter =
this.properties.get("space-after.optimum").getLength().mvalue();
this.src = this.properties.get("src").getString();
this.width = this.properties.get("width").getLength().mvalue();
this.height = this.properties.get("height").getLength().mvalue();
this.id = this.properties.get("id").getString();
area.getIDReferences().createID(id);
/*
* if (area instanceof BlockArea) {
* area.end();
* }
* if (this.isInTableCell) {
* startIndent += forcedStartOffset;
* endIndent = area.getAllocationWidth() - forcedWidth -
* forcedStartOffset;
* }
*/
this.marker = 0;
}
try {
FopImage img = FopImageFactory.Make(src);
// if width / height needs to be computed
if ((width == 0) || (height == 0)) {
// aspect ratio
double imgWidth = img.getWidth();
double imgHeight = img.getHeight();
if ((width == 0) && (height == 0)) {
width = (int)((imgWidth * 1000d));
height = (int)((imgHeight * 1000d));
} else if (height == 0) {
height = (int)((imgHeight * ((double)width)) / imgWidth);
} else if (width == 0) {
width = (int)((imgWidth * ((double)height)) / imgHeight);
}
}
// scale image if it doesn't fit in the area/page
// Need to be more tested...
double ratio = ((double)width) / ((double)height);
int areaWidth = area.getAllocationWidth() - startIndent
- endIndent;
int pageHeight = area.getPage().getHeight();
if (height > pageHeight) {
height = pageHeight;
width = (int)(ratio * ((double)height));
}
if (width > areaWidth) {
width = areaWidth;
height = (int)(((double)width) / ratio);
}
if (area.spaceLeft() < (height + spaceBefore)) {
return new Status(Status.AREA_FULL_NONE);
}
this.imageArea =
new ImageArea(propMgr.getFontState(area.getFontInfo()), img,
area.getAllocationWidth(), width, height,
startIndent, endIndent, align);
if ((spaceBefore != 0) && (this.marker == 0)) {
area.addDisplaySpace(spaceBefore);
}
if (marker == 0) {
// configure id
area.getIDReferences().configureID(id, area);
}
imageArea.start();
imageArea.end();
// area.addChild(imageArea);
// area.increaseHeight(imageArea.getHeight());
if (spaceAfter != 0) {
area.addDisplaySpace(spaceAfter);
}
if (breakBefore == BreakBefore.PAGE
|| ((spaceBefore + imageArea.getHeight())
> area.spaceLeft())) {
return new Status(Status.FORCE_PAGE_BREAK);
}
if (breakBefore == BreakBefore.ODD_PAGE) {
return new Status(Status.FORCE_PAGE_BREAK_ODD);
}
if (breakBefore == BreakBefore.EVEN_PAGE) {
return new Status(Status.FORCE_PAGE_BREAK_EVEN);
}
if (area instanceof BlockArea) {
BlockArea ba = (BlockArea)area;
LineArea la = ba.getCurrentLineArea();
if (la == null) {
return new Status(Status.AREA_FULL_NONE);
}
la.addPending();
if (imageArea.getContentWidth() > la.getRemainingWidth()) {
la = ba.createNextLineArea();
if (la == null) {
return new Status(Status.AREA_FULL_NONE);
}
}
la.addInlineArea(imageArea);
} else {
area.addChild(imageArea);
area.increaseHeight(imageArea.getContentHeight());
}
imageArea.setPage(area.getPage());
if (breakAfter == BreakAfter.PAGE) {
this.marker = BREAK_AFTER;
return new Status(Status.FORCE_PAGE_BREAK);
}
if (breakAfter == BreakAfter.ODD_PAGE) {
this.marker = BREAK_AFTER;
return new Status(Status.FORCE_PAGE_BREAK_ODD);
}
if (breakAfter == BreakAfter.EVEN_PAGE) {
this.marker = BREAK_AFTER;
return new Status(Status.FORCE_PAGE_BREAK_EVEN);
}
} catch (MalformedURLException urlex) {
// bad URL
log.error("Error while creating area : "
+ urlex.getMessage());
} catch (FopImageException imgex) {
// image error
log.error("Error while creating area : "
+ imgex.getMessage());
}
// if (area instanceof BlockArea) {
// area.start();
// }
return new Status(Status.OK);
}
| public Status layout(Area area) throws FOPException {
if (this.marker == START) {
// Common Accessibility Properties
AccessibilityProps mAccProps = propMgr.getAccessibilityProps();
// Common Aural Properties
AuralProps mAurProps = propMgr.getAuralProps();
// Common Border, Padding, and Background Properties
BorderAndPadding bap = propMgr.getBorderAndPadding();
BackgroundProps bProps = propMgr.getBackgroundProps();
// Common Margin Properties-Inline
MarginInlineProps mProps = propMgr.getMarginInlineProps();
// Common Relative Position Properties
RelativePositionProps mRelProps = propMgr.getRelativePositionProps();
// this.properties.get("alignment-adjust");
// this.properties.get("alignment-baseline");
// this.properties.get("baseline-shift");
// this.properties.get("block-progression-dimension");
// this.properties.get("content-height");
// this.properties.get("content-type");
// this.properties.get("content-width");
// this.properties.get("display-align");
// this.properties.get("dominant-baseline");
// this.properties.get("height");
// this.properties.get("id");
// this.properties.get("inline-progression-dimension");
// this.properties.get("keep-with-next");
// this.properties.get("keep-with-previous");
// this.properties.get("line-height");
// this.properties.get("line-height-shift-adjustment");
// this.properties.get("overflow");
// this.properties.get("scaling");
// this.properties.get("scaling-method");
// this.properties.get("src");
// this.properties.get("text-align");
// this.properties.get("width");
// FIXME
this.align = this.properties.get("text-align").getEnum();
this.startIndent =
this.properties.get("start-indent").getLength().mvalue();
this.endIndent =
this.properties.get("end-indent").getLength().mvalue();
this.spaceBefore =
this.properties.get("space-before.optimum").getLength().mvalue();
this.spaceAfter =
this.properties.get("space-after.optimum").getLength().mvalue();
this.src = this.properties.get("src").getString();
this.width = this.properties.get("width").getLength().mvalue();
this.height = this.properties.get("height").getLength().mvalue();
this.id = this.properties.get("id").getString();
area.getIDReferences().createID(id);
/*
* if (area instanceof BlockArea) {
* area.end();
* }
* if (this.isInTableCell) {
* startIndent += forcedStartOffset;
* endIndent = area.getAllocationWidth() - forcedWidth -
* forcedStartOffset;
* }
*/
this.marker = 0;
}
try {
FopImage img = FopImageFactory.Make(src);
// if width / height needs to be computed
if ((width == 0) || (height == 0)) {
// aspect ratio
double imgWidth = img.getWidth();
double imgHeight = img.getHeight();
if ((width == 0) && (height == 0)) {
width = (int)((imgWidth * 1000d));
height = (int)((imgHeight * 1000d));
} else if (height == 0) {
height = (int)((imgHeight * ((double)width)) / imgWidth);
} else if (width == 0) {
width = (int)((imgWidth * ((double)height)) / imgHeight);
}
}
// scale image if it doesn't fit in the area/page
// Need to be more tested...
double ratio = ((double)width) / ((double)height);
int areaWidth = area.getAllocationWidth() - startIndent
- endIndent;
int pageHeight = area.getPage().getBody().getMaxHeight()
- spaceBefore;
if (height > pageHeight) {
height = pageHeight;
width = (int)(ratio * ((double)height));
}
if (width > areaWidth) {
width = areaWidth;
height = (int)(((double)width) / ratio);
}
if (area.spaceLeft() < (height + spaceBefore)) {
return new Status(Status.AREA_FULL_NONE);
}
this.imageArea =
new ImageArea(propMgr.getFontState(area.getFontInfo()), img,
area.getAllocationWidth(), width, height,
startIndent, endIndent, align);
if ((spaceBefore != 0) && (this.marker == 0)) {
area.addDisplaySpace(spaceBefore);
}
if (marker == 0) {
// configure id
area.getIDReferences().configureID(id, area);
}
imageArea.start();
imageArea.end();
// area.addChild(imageArea);
// area.increaseHeight(imageArea.getHeight());
if (spaceAfter != 0) {
area.addDisplaySpace(spaceAfter);
}
if (breakBefore == BreakBefore.PAGE
|| ((spaceBefore + imageArea.getHeight())
> area.spaceLeft())) {
return new Status(Status.FORCE_PAGE_BREAK);
}
if (breakBefore == BreakBefore.ODD_PAGE) {
return new Status(Status.FORCE_PAGE_BREAK_ODD);
}
if (breakBefore == BreakBefore.EVEN_PAGE) {
return new Status(Status.FORCE_PAGE_BREAK_EVEN);
}
if (area instanceof BlockArea) {
BlockArea ba = (BlockArea)area;
LineArea la = ba.getCurrentLineArea();
if (la == null) {
return new Status(Status.AREA_FULL_NONE);
}
la.addPending();
if (imageArea.getContentWidth() > la.getRemainingWidth()) {
la = ba.createNextLineArea();
if (la == null) {
return new Status(Status.AREA_FULL_NONE);
}
}
la.addInlineArea(imageArea);
} else {
area.addChild(imageArea);
area.increaseHeight(imageArea.getContentHeight());
}
imageArea.setPage(area.getPage());
if (breakAfter == BreakAfter.PAGE) {
this.marker = BREAK_AFTER;
return new Status(Status.FORCE_PAGE_BREAK);
}
if (breakAfter == BreakAfter.ODD_PAGE) {
this.marker = BREAK_AFTER;
return new Status(Status.FORCE_PAGE_BREAK_ODD);
}
if (breakAfter == BreakAfter.EVEN_PAGE) {
this.marker = BREAK_AFTER;
return new Status(Status.FORCE_PAGE_BREAK_EVEN);
}
} catch (MalformedURLException urlex) {
// bad URL
log.error("Error while creating area : "
+ urlex.getMessage());
} catch (FopImageException imgex) {
// image error
log.error("Error while creating area : "
+ imgex.getMessage());
}
// if (area instanceof BlockArea) {
// area.start();
// }
return new Status(Status.OK);
}
|
diff --git a/achartengine/src/org/achartengine/chart/BarChart.java b/achartengine/src/org/achartengine/chart/BarChart.java
index 0bba697..3ac69e9 100644
--- a/achartengine/src/org/achartengine/chart/BarChart.java
+++ b/achartengine/src/org/achartengine/chart/BarChart.java
@@ -1,315 +1,319 @@
/**
* Copyright (C) 2009 - 2012 SC 4ViewSoft SRL
*
* 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.achartengine.chart;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
/**
* The bar chart rendering class.
*/
public class BarChart extends XYChart {
/** The constant to identify this chart type. */
public static final String TYPE = "Bar";
/** The legend shape width. */
private static final int SHAPE_WIDTH = 12;
/** The chart type. */
protected Type mType = Type.DEFAULT;
/**
* The bar chart type enum.
*/
public enum Type {
DEFAULT, STACKED;
}
BarChart() {
}
/**
* Builds a new bar chart instance.
*
* @param dataset the multiple series dataset
* @param renderer the multiple series renderer
* @param type the bar chart type
*/
public BarChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer, Type type) {
super(dataset, renderer);
mType = type;
}
@Override
protected ClickableArea[] clickableAreasForPoints(float[] points, double[] values,
float yAxisValue, int seriesIndex, int startIndex) {
int seriesNr = mDataset.getSeriesCount();
int length = points.length;
ClickableArea[] ret = new ClickableArea[length / 2];
float halfDiffX = getHalfDiffX(points, length, seriesNr);
for (int i = 0; i < length; i += 2) {
float x = points[i];
float y = points[i + 1];
if (mType == Type.STACKED) {
ret[i / 2] = new ClickableArea(new RectF(x - halfDiffX, y, x + halfDiffX, yAxisValue),
values[i], values[i + 1]);
} else {
float startX = x - seriesNr * halfDiffX + seriesIndex * 2 * halfDiffX;
ret[i / 2] = new ClickableArea(new RectF(startX, y, startX + 2 * halfDiffX, yAxisValue),
values[i], values[i + 1]);
}
}
return ret;
}
/**
* The graphical representation of a series.
*
* @param canvas the canvas to paint to
* @param paint the paint to be used for drawing
* @param points the array of points to be used for drawing the series
* @param seriesRenderer the series renderer
* @param yAxisValue the minimum value of the y axis
* @param seriesIndex the index of the series currently being drawn
* @param startIndex the start index of the rendering points
*/
public void drawSeries(Canvas canvas, Paint paint, float[] points,
SimpleSeriesRenderer seriesRenderer, float yAxisValue, int seriesIndex, int startIndex) {
int seriesNr = mDataset.getSeriesCount();
int length = points.length;
paint.setColor(seriesRenderer.getColor());
paint.setStyle(Style.FILL);
float halfDiffX = getHalfDiffX(points, length, seriesNr);
for (int i = 0; i < length; i += 2) {
float x = points[i];
float y = points[i + 1];
drawBar(canvas, x, yAxisValue, x, y, halfDiffX, seriesNr, seriesIndex, paint);
}
paint.setColor(seriesRenderer.getColor());
}
/**
* Draws a bar.
*
* @param canvas the canvas
* @param xMin the X axis minimum
* @param yMin the Y axis minimum
* @param xMax the X axis maximum
* @param yMax the Y axis maximum
* @param halfDiffX half the size of a bar
* @param seriesNr the total number of series
* @param seriesIndex the current series index
* @param paint the paint
*/
protected void drawBar(Canvas canvas, float xMin, float yMin, float xMax, float yMax,
float halfDiffX, int seriesNr, int seriesIndex, Paint paint) {
int scale = mDataset.getSeriesAt(seriesIndex).getScaleNumber();
if (mType == Type.STACKED) {
drawBar(canvas, xMin - halfDiffX, yMax, xMax + halfDiffX, yMin, scale, seriesIndex, paint);
} else {
float startX = xMin - seriesNr * halfDiffX + seriesIndex * 2 * halfDiffX;
drawBar(canvas, startX, yMax, startX + 2 * halfDiffX, yMin, scale, seriesIndex, paint);
}
}
/**
* Draws a bar.
*
* @param canvas the canvas
* @param xMin the X axis minimum
* @param yMin the Y axis minimum
* @param xMax the X axis maximum
* @param yMax the Y axis maximum
* @param scale the scale index
* @param seriesIndex the current series index
* @param paint the paint
*/
private void drawBar(Canvas canvas, float xMin, float yMin, float xMax, float yMax, int scale,
int seriesIndex, Paint paint) {
SimpleSeriesRenderer renderer = mRenderer.getSeriesRendererAt(seriesIndex);
if (renderer.isGradientEnabled()) {
float minY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStopValue() }, scale)[1];
float maxY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStartValue() },
scale)[1];
float gradientMinY = Math.max(minY, yMin);
float gradientMaxY = Math.min(maxY, yMax);
int gradientMinColor = renderer.getGradientStopColor();
int gradientMaxColor = renderer.getGradientStartColor();
int gradientStartColor = gradientMaxColor;
int gradientStopColor = gradientMinColor;
if (yMin < minY) {
paint.setColor(gradientMinColor);
canvas.drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax),
Math.round(gradientMinY), paint);
} else {
gradientStopColor = getGradientPartialColor(gradientMinColor, gradientMaxColor,
(maxY - gradientMinY) / (maxY - minY));
}
if (yMax > maxY) {
paint.setColor(gradientMaxColor);
canvas.drawRect(Math.round(xMin), Math.round(gradientMaxY), Math.round(xMax),
Math.round(yMax), paint);
} else {
gradientStartColor = getGradientPartialColor(gradientMaxColor, gradientMinColor,
(gradientMaxY - minY) / (maxY - minY));
}
GradientDrawable gradient = new GradientDrawable(Orientation.BOTTOM_TOP, new int[] {
gradientStartColor, gradientStopColor });
gradient.setBounds(Math.round(xMin), Math.round(gradientMinY), Math.round(xMax),
Math.round(gradientMaxY));
gradient.draw(canvas);
} else {
- if (yMin == yMax) {
- yMin = yMax - 1;
+ if (Math.abs(yMin - yMax) < 1) {
+ if (yMin < yMax) {
+ yMax = yMin + 1;
+ } else {
+ yMax = yMin - 1;
+ }
}
canvas
.drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax), Math.round(yMax), paint);
}
}
private int getGradientPartialColor(int minColor, int maxColor, float fraction) {
int alpha = Math.round(fraction * Color.alpha(minColor) + (1 - fraction)
* Color.alpha(maxColor));
int r = Math.round(fraction * Color.red(minColor) + (1 - fraction) * Color.red(maxColor));
int g = Math.round(fraction * Color.green(minColor) + (1 - fraction) * Color.green(maxColor));
int b = Math.round(fraction * Color.blue(minColor) + (1 - fraction) * Color.blue((maxColor)));
return Color.argb(alpha, r, g, b);
}
/**
* The graphical representation of the series values as text.
*
* @param canvas the canvas to paint to
* @param series the series to be painted
* @param renderer the series renderer
* @param paint the paint to be used for drawing
* @param points the array of points to be used for drawing the series
* @param seriesIndex the index of the series currently being drawn
* @param startIndex the start index of the rendering points
*/
protected void drawChartValuesText(Canvas canvas, XYSeries series, SimpleSeriesRenderer renderer,
Paint paint, float[] points, int seriesIndex, int startIndex) {
int seriesNr = mDataset.getSeriesCount();
float halfDiffX = getHalfDiffX(points, points.length, seriesNr);
for (int i = 0; i < points.length; i += 2) {
int index = startIndex + i / 2;
if (!isNullValue(series.getY(index))) {
float x = points[i];
if (mType == Type.DEFAULT) {
x += seriesIndex * 2 * halfDiffX - (seriesNr - 1.5f) * halfDiffX;
}
drawText(canvas, getLabel(series.getY(index)), x,
points[i + 1] - renderer.getChartValuesSpacing(), paint, 0);
}
}
}
/**
* Returns the legend shape width.
*
* @param seriesIndex the series index
* @return the legend shape width
*/
public int getLegendShapeWidth(int seriesIndex) {
return SHAPE_WIDTH;
}
/**
* The graphical representation of the legend shape.
*
* @param canvas the canvas to paint to
* @param renderer the series renderer
* @param x the x value of the point the shape should be drawn at
* @param y the y value of the point the shape should be drawn at
* @param seriesIndex the series index
* @param paint the paint to be used for drawing
*/
public void drawLegendShape(Canvas canvas, SimpleSeriesRenderer renderer, float x, float y,
int seriesIndex, Paint paint) {
float halfShapeWidth = SHAPE_WIDTH / 2;
canvas.drawRect(x, y - halfShapeWidth, x + SHAPE_WIDTH, y + halfShapeWidth, paint);
}
/**
* Calculates and returns the half-distance in the graphical representation of
* 2 consecutive points.
*
* @param points the points
* @param length the points length
* @param seriesNr the series number
* @return the calculated half-distance value
*/
protected float getHalfDiffX(float[] points, int length, int seriesNr) {
int div = length;
if (length > 2) {
div = length - 2;
}
float halfDiffX = (points[length - 2] - points[0]) / div;
if (halfDiffX == 0) {
halfDiffX = 10;
}
if (mType != Type.STACKED) {
halfDiffX /= seriesNr;
}
return (float) (halfDiffX / (getCoeficient() * (1 + mRenderer.getBarSpacing())));
}
/**
* Returns the value of a constant used to calculate the half-distance.
*
* @return the constant value
*/
protected float getCoeficient() {
return 1f;
}
/**
* Returns if the chart should display the null values.
*
* @return if null values should be rendered
*/
protected boolean isRenderNullValues() {
return true;
}
/**
* Returns the default axis minimum.
*
* @return the default axis minimum
*/
public double getDefaultMinimum() {
return 0;
}
/**
* Returns the chart type identifier.
*
* @return the chart type
*/
public String getChartType() {
return TYPE;
}
}
| true | true | private void drawBar(Canvas canvas, float xMin, float yMin, float xMax, float yMax, int scale,
int seriesIndex, Paint paint) {
SimpleSeriesRenderer renderer = mRenderer.getSeriesRendererAt(seriesIndex);
if (renderer.isGradientEnabled()) {
float minY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStopValue() }, scale)[1];
float maxY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStartValue() },
scale)[1];
float gradientMinY = Math.max(minY, yMin);
float gradientMaxY = Math.min(maxY, yMax);
int gradientMinColor = renderer.getGradientStopColor();
int gradientMaxColor = renderer.getGradientStartColor();
int gradientStartColor = gradientMaxColor;
int gradientStopColor = gradientMinColor;
if (yMin < minY) {
paint.setColor(gradientMinColor);
canvas.drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax),
Math.round(gradientMinY), paint);
} else {
gradientStopColor = getGradientPartialColor(gradientMinColor, gradientMaxColor,
(maxY - gradientMinY) / (maxY - minY));
}
if (yMax > maxY) {
paint.setColor(gradientMaxColor);
canvas.drawRect(Math.round(xMin), Math.round(gradientMaxY), Math.round(xMax),
Math.round(yMax), paint);
} else {
gradientStartColor = getGradientPartialColor(gradientMaxColor, gradientMinColor,
(gradientMaxY - minY) / (maxY - minY));
}
GradientDrawable gradient = new GradientDrawable(Orientation.BOTTOM_TOP, new int[] {
gradientStartColor, gradientStopColor });
gradient.setBounds(Math.round(xMin), Math.round(gradientMinY), Math.round(xMax),
Math.round(gradientMaxY));
gradient.draw(canvas);
} else {
if (yMin == yMax) {
yMin = yMax - 1;
}
canvas
.drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax), Math.round(yMax), paint);
}
}
| private void drawBar(Canvas canvas, float xMin, float yMin, float xMax, float yMax, int scale,
int seriesIndex, Paint paint) {
SimpleSeriesRenderer renderer = mRenderer.getSeriesRendererAt(seriesIndex);
if (renderer.isGradientEnabled()) {
float minY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStopValue() }, scale)[1];
float maxY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStartValue() },
scale)[1];
float gradientMinY = Math.max(minY, yMin);
float gradientMaxY = Math.min(maxY, yMax);
int gradientMinColor = renderer.getGradientStopColor();
int gradientMaxColor = renderer.getGradientStartColor();
int gradientStartColor = gradientMaxColor;
int gradientStopColor = gradientMinColor;
if (yMin < minY) {
paint.setColor(gradientMinColor);
canvas.drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax),
Math.round(gradientMinY), paint);
} else {
gradientStopColor = getGradientPartialColor(gradientMinColor, gradientMaxColor,
(maxY - gradientMinY) / (maxY - minY));
}
if (yMax > maxY) {
paint.setColor(gradientMaxColor);
canvas.drawRect(Math.round(xMin), Math.round(gradientMaxY), Math.round(xMax),
Math.round(yMax), paint);
} else {
gradientStartColor = getGradientPartialColor(gradientMaxColor, gradientMinColor,
(gradientMaxY - minY) / (maxY - minY));
}
GradientDrawable gradient = new GradientDrawable(Orientation.BOTTOM_TOP, new int[] {
gradientStartColor, gradientStopColor });
gradient.setBounds(Math.round(xMin), Math.round(gradientMinY), Math.round(xMax),
Math.round(gradientMaxY));
gradient.draw(canvas);
} else {
if (Math.abs(yMin - yMax) < 1) {
if (yMin < yMax) {
yMax = yMin + 1;
} else {
yMax = yMin - 1;
}
}
canvas
.drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax), Math.round(yMax), paint);
}
}
|
diff --git a/extrabiomes/src/common/extrabiomes/blocks/BlockCrackedSand.java b/extrabiomes/src/common/extrabiomes/blocks/BlockCrackedSand.java
index b962b748..9ced37cc 100644
--- a/extrabiomes/src/common/extrabiomes/blocks/BlockCrackedSand.java
+++ b/extrabiomes/src/common/extrabiomes/blocks/BlockCrackedSand.java
@@ -1,114 +1,117 @@
package extrabiomes.blocks;
import java.util.ArrayList;
import java.util.Random;
import net.minecraft.src.Block;
import net.minecraft.src.EnumCreatureType;
import net.minecraft.src.ItemStack;
import net.minecraft.src.Material;
import net.minecraft.src.World;
import net.minecraft.src.forge.ITextureProvider;
import extrabiomes.api.BiomeManager;
import extrabiomes.api.TerrainGenManager;
import extrabiomes.config.ConfigureBlocks;
public class BlockCrackedSand extends Block implements ITextureProvider
{
private static boolean canGrow;
private static boolean restrictGrowthToBiome;
public BlockCrackedSand(int id) {
super(id, 0, Material.rock);
setHardness(1.2F);
setStepSound(Block.soundStoneFootstep);
if (ConfigureBlocks.crackedSandCanGrow) setTickRandomly(true);
canGrow = ConfigureBlocks.crackedSandCanGrow;
restrictGrowthToBiome = ConfigureBlocks.crackedSandGrowthRestrictedToWasteland;
TerrainGenManager.blockWasteland = this;
}
@Override
public void addCreativeItems(ArrayList itemList) {
itemList.add(new ItemStack(this));
}
@Override
public boolean canCreatureSpawn(EnumCreatureType type, World world,
int x, int y, int z)
{
return true;
}
private void changeNeighbor(World world, int x, int y, int z) {
if (world.getBlockLightValue(x, y + 1, z) < 9) return;
decayBlock(world, x, y, z);
}
private void decayBlock(World world, int x, int y, int z) {
final int id = world.getBlockId(x, y, z);
if (id == tilledField.blockID) {
final int metadata = world.getBlockMetadata(x, y, z);
if (metadata != 0)
world.setBlockMetadataWithNotify(x, y, z, metadata - 1);
else
world.setBlockWithNotify(x, y, z, dirt.blockID);
} else if (id == grass.blockID)
world.setBlockWithNotify(x, y, z, dirt.blockID);
else if (id == dirt.blockID)
- world.setBlockWithNotify(x, y, z, sandStone.blockID);
+ world.setBlockWithNotify(x, y, z, sand.blockID);
+ else if (id == sand.blockID) {
+ world.setBlockWithNotify(x, y, z, sandStone.blockID);
+ }
else if (id == sandStone.blockID) {
final int metadata = world.getBlockMetadata(x, y, z);
if (metadata != 0)
world.setBlockMetadataWithNotify(x, y, z, 0);
else
world.setBlockWithNotify(x, y, z, blockID);
} else if (id == waterStill.blockID)
if (isThreeSidesCrackedSand(world, x, y, z))
world.setBlockAndMetadataWithNotify(x, y, z,
waterMoving.blockID, 7);
}
@Override
public String getTextureFile() {
return "/extrabiomes/extrabiomes.png";
}
private boolean isThreeSidesCrackedSand(World world, int x, int y,
int z)
{
int count = 0;
for (int xTest = x - 1; xTest < x + 2; xTest += 2)
for (int zTest = z - 1; zTest < z + 2; zTest += 2)
if (world.getBlockId(xTest, y, zTest) == blockID)
count++;
return count >= 3;
}
@Override
public void updateTick(World world, int x, int y, int z, Random rand)
{
if (!canGrow) return;
if (!world.isRemote) {
if (restrictGrowthToBiome
&& world.getBiomeGenForCoords(x, z) != BiomeManager.wasteland)
return;
if (world.getBlockLightValue(x, y + 1, z) < 15) return;
for (int i = 0; i < 4; ++i) {
final int x1 = x + rand.nextInt(3) - 1;
final int y1 = y + rand.nextInt(5) - 3;
final int z1 = z + rand.nextInt(3) - 1;
if (!restrictGrowthToBiome
|| world.getBiomeGenForCoords(x1, z1) == BiomeManager.wasteland)
changeNeighbor(world, x1, y1, z1);
}
}
}
}
| true | true | private void decayBlock(World world, int x, int y, int z) {
final int id = world.getBlockId(x, y, z);
if (id == tilledField.blockID) {
final int metadata = world.getBlockMetadata(x, y, z);
if (metadata != 0)
world.setBlockMetadataWithNotify(x, y, z, metadata - 1);
else
world.setBlockWithNotify(x, y, z, dirt.blockID);
} else if (id == grass.blockID)
world.setBlockWithNotify(x, y, z, dirt.blockID);
else if (id == dirt.blockID)
world.setBlockWithNotify(x, y, z, sandStone.blockID);
else if (id == sandStone.blockID) {
final int metadata = world.getBlockMetadata(x, y, z);
if (metadata != 0)
world.setBlockMetadataWithNotify(x, y, z, 0);
else
world.setBlockWithNotify(x, y, z, blockID);
} else if (id == waterStill.blockID)
if (isThreeSidesCrackedSand(world, x, y, z))
world.setBlockAndMetadataWithNotify(x, y, z,
waterMoving.blockID, 7);
}
| private void decayBlock(World world, int x, int y, int z) {
final int id = world.getBlockId(x, y, z);
if (id == tilledField.blockID) {
final int metadata = world.getBlockMetadata(x, y, z);
if (metadata != 0)
world.setBlockMetadataWithNotify(x, y, z, metadata - 1);
else
world.setBlockWithNotify(x, y, z, dirt.blockID);
} else if (id == grass.blockID)
world.setBlockWithNotify(x, y, z, dirt.blockID);
else if (id == dirt.blockID)
world.setBlockWithNotify(x, y, z, sand.blockID);
else if (id == sand.blockID) {
world.setBlockWithNotify(x, y, z, sandStone.blockID);
}
else if (id == sandStone.blockID) {
final int metadata = world.getBlockMetadata(x, y, z);
if (metadata != 0)
world.setBlockMetadataWithNotify(x, y, z, 0);
else
world.setBlockWithNotify(x, y, z, blockID);
} else if (id == waterStill.blockID)
if (isThreeSidesCrackedSand(world, x, y, z))
world.setBlockAndMetadataWithNotify(x, y, z,
waterMoving.blockID, 7);
}
|
diff --git a/BuyIt/src/main/java/com/epam/lab/buyit/controller/web/servlet/CategoryServlet.java b/BuyIt/src/main/java/com/epam/lab/buyit/controller/web/servlet/CategoryServlet.java
index 6b21b0e..77a8b61 100644
--- a/BuyIt/src/main/java/com/epam/lab/buyit/controller/web/servlet/CategoryServlet.java
+++ b/BuyIt/src/main/java/com/epam/lab/buyit/controller/web/servlet/CategoryServlet.java
@@ -1,49 +1,50 @@
package com.epam.lab.buyit.controller.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.epam.lab.buyit.controller.service.product.ProductServiceImpl;
import com.epam.lab.buyit.controller.service.subcategory.SubCategoryServiceImpl;
import com.epam.lab.buyit.model.SubCategory;
public class CategoryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int ITEMS_ON_PAGE = 8;
private SubCategoryServiceImpl subCategoryServce;
private ProductServiceImpl productService;
public void init() {
subCategoryServce = new SubCategoryServiceImpl();
productService = new ProductServiceImpl();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
int subCategory_id = 0;
if (request.getParameter("id") != null)
subCategory_id = Integer.parseInt(request.getParameter("id"));
int page = 1;
if(request.getParameter("page") != null)
page = Integer.parseInt(request.getParameter("page"));
SubCategory subCategory = subCategoryServce.getWithProductSelection(
subCategory_id, (page-1) * ITEMS_ON_PAGE, ITEMS_ON_PAGE);
int numberOfRecords = productService.getCountBySubCategoryId(subCategory_id);
int numberOfPages = (int) Math.ceil(numberOfRecords * 1.0 / ITEMS_ON_PAGE);
+ request.setAttribute("categoryId", request.getParameter("categoryId"));
request.setAttribute("subCategory", subCategory);
request.setAttribute("noOfPages", numberOfPages);
request.setAttribute("page", page);
request.getRequestDispatcher("category").forward(request, response);
}
}
| true | true | protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
int subCategory_id = 0;
if (request.getParameter("id") != null)
subCategory_id = Integer.parseInt(request.getParameter("id"));
int page = 1;
if(request.getParameter("page") != null)
page = Integer.parseInt(request.getParameter("page"));
SubCategory subCategory = subCategoryServce.getWithProductSelection(
subCategory_id, (page-1) * ITEMS_ON_PAGE, ITEMS_ON_PAGE);
int numberOfRecords = productService.getCountBySubCategoryId(subCategory_id);
int numberOfPages = (int) Math.ceil(numberOfRecords * 1.0 / ITEMS_ON_PAGE);
request.setAttribute("subCategory", subCategory);
request.setAttribute("noOfPages", numberOfPages);
request.setAttribute("page", page);
request.getRequestDispatcher("category").forward(request, response);
}
| protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
int subCategory_id = 0;
if (request.getParameter("id") != null)
subCategory_id = Integer.parseInt(request.getParameter("id"));
int page = 1;
if(request.getParameter("page") != null)
page = Integer.parseInt(request.getParameter("page"));
SubCategory subCategory = subCategoryServce.getWithProductSelection(
subCategory_id, (page-1) * ITEMS_ON_PAGE, ITEMS_ON_PAGE);
int numberOfRecords = productService.getCountBySubCategoryId(subCategory_id);
int numberOfPages = (int) Math.ceil(numberOfRecords * 1.0 / ITEMS_ON_PAGE);
request.setAttribute("categoryId", request.getParameter("categoryId"));
request.setAttribute("subCategory", subCategory);
request.setAttribute("noOfPages", numberOfPages);
request.setAttribute("page", page);
request.getRequestDispatcher("category").forward(request, response);
}
|
diff --git a/join-tester/src/main/java/joins/queries/QueryGenerator.java b/join-tester/src/main/java/joins/queries/QueryGenerator.java
index 1e862cc..7c28019 100644
--- a/join-tester/src/main/java/joins/queries/QueryGenerator.java
+++ b/join-tester/src/main/java/joins/queries/QueryGenerator.java
@@ -1,136 +1,136 @@
package joins.queries;
import joins.indexer.WordLists;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class QueryGenerator {
private final String OUTPUT_FILE = "queries.txt";
private static final int ACL_RANGE = 10000;
protected QGen queryConsumer;
interface QGen {
void onQuery(String terms, String aclRange);
}
static class QueryFile implements QGen, Closeable{
private final BufferedWriter writer;
private String format;
QueryFile(String fileName, String format) throws IOException{
writer = new BufferedWriter(new FileWriter(fileName));
this.format = format;
}
@Override
public void close() throws IOException {
writer.close();
}
@Override
public void onQuery(String terms, String aclRange) {
try {
writer.write(String.format(format,
terms, aclRange ));
writer.newLine();
} catch (IOException e) {
throw new RuntimeException("wrap", e);
}
}
}
public static void main(String[] args) throws IOException {
final List<QueryFile> consumers = Arrays
.asList(new QueryFile("queries-join.txt", "q=text_all:(%s)" +
// "&fl=id,score&sort=score desc&fq={!join from=few_join_id to=few_id}acl:%s",
"&fl=id,score&sort=score desc&fq={!join from=join_id to=id}acl:%s"),
new QueryFile(
"queries-bjq-fq.txt",
"q=text_all:(%s)"
- + "&fl=id,score&sort=score desc&fq={!join from=join_id to=id}acl:%s"),
+ + "&fl=id,score&sort=score desc&fq={!parent which=kind:body}acl:%s"),
- new QueryFile("queries-bjq.txt",
- "q=text_all:(%s) AND _query_:\"{!join from=join_id to=id}acl:%s\""
+ new QueryFile("queries-bjq.txt", // AND _query_:\"{!parent which=kind:body}acl:%s\""
+ "q=text_all:(%s) AND _query_:\"{!parent which=kind:body}acl:%s\""
+ "&fl=id,score&sort=score desc"),
new QueryFile("queries-no-acls.txt",
"q=text_all:(%s)&fl=id,score&sort=score desc"));
QueryGenerator qg = new QueryGenerator();
qg.queryConsumer = new QGen() {
@Override
public void onQuery(String terms, String aclRange) {
for (QGen consumer : consumers) {
consumer.onQuery(terms, aclRange);
}
}
};
main(qg);
for (QueryFile consumer : consumers) {
consumer.close();
}
}
protected static void main(QueryGenerator qg) {
try {
WordLists.init();
qg.generateQueries();
} catch (Exception e) {
e.printStackTrace();
}
}
void generateQueries() throws Exception {
for (int idx = 0; idx < 10000; ++idx) {
// Solrmeter doesn't need the above in the text file, you enter that in a screen.
String terms = getTerms(idx);
String aclRange = getAclRange(idx);
String place = getPlace(idx);
// String raw = String.format("q=kind:instance OR text_all:(%s)" +
// "&fl=id,score&sort=score desc&fq={!bbox}&sfield=place&pt=%s&d=100",
// getTerms(idx), getPlace(idx));
// String uri = URLEncoder.encode(raw, "UTF-8");
queryConsumer.onQuery(terms, aclRange);
}
}
String getTerms(int idx) {
// Idea here is that if idx mod 10 is between 1-5 (inclusive), use one term. 6-7 two terms, 8-9 three terms. ORed.
int modulus = idx % 10;
if (modulus < 6) return String.format("%s", WordLists.getCommonWord());
if (modulus < 8) return String.format("%s OR %s", WordLists.getCommonWord(), WordLists.getCommonWord());
return String.format("%s OR %s OR %s", WordLists.getCommonWord(), WordLists.getCommonWord(), WordLists.getCommonWord());
}
String getAclRange(int idx) {
// Similarly to above. Two random numbers here, one is the base ACL number (range 1-10000) and the second the number
// of entries (up to 100). All this is arbitrary.
int base = WordLists.getInt(ACL_RANGE);
int count = WordLists.getInt(10);
if (base + count >= ACL_RANGE) base = (ACL_RANGE - 1) - count;
return String.format("[%s TO %s]", base, base + count);
}
String getPlace(int idx) {
Boolean doNeg = false;
if ((idx % 2) == 0) {
doNeg = true;
}
int lat = WordLists.getInt(90) * ((doNeg) ? 1 : -1);
int lon = WordLists.getInt(90) * ((doNeg) ? 1 : -1);
return String.format("%d,%d", lat, lon);
}
}
| false | true | public static void main(String[] args) throws IOException {
final List<QueryFile> consumers = Arrays
.asList(new QueryFile("queries-join.txt", "q=text_all:(%s)" +
// "&fl=id,score&sort=score desc&fq={!join from=few_join_id to=few_id}acl:%s",
"&fl=id,score&sort=score desc&fq={!join from=join_id to=id}acl:%s"),
new QueryFile(
"queries-bjq-fq.txt",
"q=text_all:(%s)"
+ "&fl=id,score&sort=score desc&fq={!join from=join_id to=id}acl:%s"),
new QueryFile("queries-bjq.txt",
"q=text_all:(%s) AND _query_:\"{!join from=join_id to=id}acl:%s\""
+ "&fl=id,score&sort=score desc"),
new QueryFile("queries-no-acls.txt",
"q=text_all:(%s)&fl=id,score&sort=score desc"));
QueryGenerator qg = new QueryGenerator();
qg.queryConsumer = new QGen() {
@Override
public void onQuery(String terms, String aclRange) {
for (QGen consumer : consumers) {
consumer.onQuery(terms, aclRange);
}
}
};
main(qg);
for (QueryFile consumer : consumers) {
consumer.close();
}
}
| public static void main(String[] args) throws IOException {
final List<QueryFile> consumers = Arrays
.asList(new QueryFile("queries-join.txt", "q=text_all:(%s)" +
// "&fl=id,score&sort=score desc&fq={!join from=few_join_id to=few_id}acl:%s",
"&fl=id,score&sort=score desc&fq={!join from=join_id to=id}acl:%s"),
new QueryFile(
"queries-bjq-fq.txt",
"q=text_all:(%s)"
+ "&fl=id,score&sort=score desc&fq={!parent which=kind:body}acl:%s"),
new QueryFile("queries-bjq.txt", // AND _query_:\"{!parent which=kind:body}acl:%s\""
"q=text_all:(%s) AND _query_:\"{!parent which=kind:body}acl:%s\""
+ "&fl=id,score&sort=score desc"),
new QueryFile("queries-no-acls.txt",
"q=text_all:(%s)&fl=id,score&sort=score desc"));
QueryGenerator qg = new QueryGenerator();
qg.queryConsumer = new QGen() {
@Override
public void onQuery(String terms, String aclRange) {
for (QGen consumer : consumers) {
consumer.onQuery(terms, aclRange);
}
}
};
main(qg);
for (QueryFile consumer : consumers) {
consumer.close();
}
}
|
diff --git a/java/modules/core/src/main/java/org/apache/synapse/config/xml/HeaderMediatorSerializer.java b/java/modules/core/src/main/java/org/apache/synapse/config/xml/HeaderMediatorSerializer.java
index ae9e9b276..7f93b4073 100644
--- a/java/modules/core/src/main/java/org/apache/synapse/config/xml/HeaderMediatorSerializer.java
+++ b/java/modules/core/src/main/java/org/apache/synapse/config/xml/HeaderMediatorSerializer.java
@@ -1,103 +1,103 @@
/*
* 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.synapse.config.xml;
import org.apache.axiom.om.OMElement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.SynapseException;
import org.apache.synapse.Mediator;
import org.apache.synapse.mediators.transform.HeaderMediator;
import javax.xml.namespace.QName;
/**
* Set header
* <pre>
* <header name="qname" (value="literal" | expression="xpath")/>
* </pre>
*
* Remove header
* <pre>
* <header name="qname" action="remove"/>
* </pre>
*/
public class HeaderMediatorSerializer extends BaseMediatorSerializer
implements MediatorSerializer {
private static final Log log = LogFactory.getLog(FilterMediatorSerializer.class);
public OMElement serializeMediator(OMElement parent, Mediator m) {
if (!(m instanceof HeaderMediator)) {
handleException("Unsupported mediator passed in for serialization : " + m.getType());
}
HeaderMediator mediator = (HeaderMediator) m;
OMElement header = fac.createOMElement("header", synNS);
QName qName = mediator.getQName();
if (qName != null) {
if (qName.getNamespaceURI() != null) {
header.addAttribute(fac.createOMAttribute(
"name", nullNS,
- (qName.getPrefix() != null || "".equals(qName.getPrefix())
+ (qName.getPrefix() != null && !"".equals(qName.getPrefix())
? qName.getPrefix() + ":" : "") +
qName.getLocalPart()));
header.declareNamespace(qName.getNamespaceURI(), qName.getPrefix());
} else {
header.addAttribute(fac.createOMAttribute(
"name", nullNS, qName.getLocalPart()));
}
}
if (mediator.getAction() == HeaderMediator.ACTION_REMOVE) {
header.addAttribute(fac.createOMAttribute(
"action", nullNS, "remove"));
} else {
if (mediator.getValue() != null) {
header.addAttribute(fac.createOMAttribute(
"value", nullNS, mediator.getValue()));
} else if (mediator.getExpression() != null) {
header.addAttribute(fac.createOMAttribute(
"expression", nullNS, mediator.getExpression().toString()));
super.serializeNamespaces(header, mediator.getExpression());
} else {
handleException("Value or expression required for a set header mediator");
}
}
if (parent != null) {
parent.addChild(header);
}
return header;
}
public String getMediatorClassName() {
return HeaderMediator.class.getName();
}
private void handleException(String msg) {
log.error(msg);
throw new SynapseException(msg);
}
}
| true | true | public OMElement serializeMediator(OMElement parent, Mediator m) {
if (!(m instanceof HeaderMediator)) {
handleException("Unsupported mediator passed in for serialization : " + m.getType());
}
HeaderMediator mediator = (HeaderMediator) m;
OMElement header = fac.createOMElement("header", synNS);
QName qName = mediator.getQName();
if (qName != null) {
if (qName.getNamespaceURI() != null) {
header.addAttribute(fac.createOMAttribute(
"name", nullNS,
(qName.getPrefix() != null || "".equals(qName.getPrefix())
? qName.getPrefix() + ":" : "") +
qName.getLocalPart()));
header.declareNamespace(qName.getNamespaceURI(), qName.getPrefix());
} else {
header.addAttribute(fac.createOMAttribute(
"name", nullNS, qName.getLocalPart()));
}
}
if (mediator.getAction() == HeaderMediator.ACTION_REMOVE) {
header.addAttribute(fac.createOMAttribute(
"action", nullNS, "remove"));
} else {
if (mediator.getValue() != null) {
header.addAttribute(fac.createOMAttribute(
"value", nullNS, mediator.getValue()));
} else if (mediator.getExpression() != null) {
header.addAttribute(fac.createOMAttribute(
"expression", nullNS, mediator.getExpression().toString()));
super.serializeNamespaces(header, mediator.getExpression());
} else {
handleException("Value or expression required for a set header mediator");
}
}
if (parent != null) {
parent.addChild(header);
}
return header;
}
| public OMElement serializeMediator(OMElement parent, Mediator m) {
if (!(m instanceof HeaderMediator)) {
handleException("Unsupported mediator passed in for serialization : " + m.getType());
}
HeaderMediator mediator = (HeaderMediator) m;
OMElement header = fac.createOMElement("header", synNS);
QName qName = mediator.getQName();
if (qName != null) {
if (qName.getNamespaceURI() != null) {
header.addAttribute(fac.createOMAttribute(
"name", nullNS,
(qName.getPrefix() != null && !"".equals(qName.getPrefix())
? qName.getPrefix() + ":" : "") +
qName.getLocalPart()));
header.declareNamespace(qName.getNamespaceURI(), qName.getPrefix());
} else {
header.addAttribute(fac.createOMAttribute(
"name", nullNS, qName.getLocalPart()));
}
}
if (mediator.getAction() == HeaderMediator.ACTION_REMOVE) {
header.addAttribute(fac.createOMAttribute(
"action", nullNS, "remove"));
} else {
if (mediator.getValue() != null) {
header.addAttribute(fac.createOMAttribute(
"value", nullNS, mediator.getValue()));
} else if (mediator.getExpression() != null) {
header.addAttribute(fac.createOMAttribute(
"expression", nullNS, mediator.getExpression().toString()));
super.serializeNamespaces(header, mediator.getExpression());
} else {
handleException("Value or expression required for a set header mediator");
}
}
if (parent != null) {
parent.addChild(header);
}
return header;
}
|
diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/ConfigurationElementSorter.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/ConfigurationElementSorter.java
index 9b0f7a987..a57ae978e 100644
--- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/ConfigurationElementSorter.java
+++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/ConfigurationElementSorter.java
@@ -1,180 +1,180 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.texteditor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.osgi.util.ManifestElement;
import org.eclipse.jface.text.Assert;
import org.eclipse.ui.internal.texteditor.TextEditorPlugin;
/**
* Allows to sort an array based on their elements' configuration elements
* according to the prerequisite relation of their defining plug-ins.
* <p>
* This class may be subclassed.
* </p>
*
* @since 3.0
*/
public abstract class ConfigurationElementSorter {
/**
* Sorts the given array based on its elements' configuration elements
* according to the prerequisite relation of their defining plug-ins.
*
* @param elements the array to be sorted
*/
public final void sort(Object[] elements) {
Arrays.sort(elements, new ConfigurationElementComparator(elements));
}
/**
* Returns the configuration element for the given object.
*
* @param object the object
* @return the object's configuration element, must not be <code>null</code>
*/
public abstract IConfigurationElement getConfigurationElement(Object object);
/**
* Compare configuration elements according to the prerequisite relation
* of their defining plug-ins.
*/
private class ConfigurationElementComparator implements Comparator {
private Map fDescriptorMapping;
private Map fPrereqsMapping;
public ConfigurationElementComparator(Object[] elements) {
Assert.isNotNull(elements);
initialize(elements);
}
/*
* @see Comparator#compare(java.lang.Object, java.lang.Object)
* @since 2.0
*/
public int compare(Object object0, Object object1) {
if (dependsOn(object0, object1))
return -1;
if (dependsOn(object1, object0))
return +1;
return 0;
}
/**
* Returns whether one configuration element depends on the other element.
* This is done by checking the dependency chain of the defining plug-ins.
*
* @param element0 the first element
* @param element1 the second element
* @return <code>true</code> if <code>element0</code> depends on <code>element1</code>.
* @since 2.0
*/
private boolean dependsOn(Object element0, Object element1) {
if (element0 == null || element1 == null)
return false;
String pluginDesc0= (String)fDescriptorMapping.get(element0);
String pluginDesc1= (String)fDescriptorMapping.get(element1);
// performance tuning - code below would give same result
if (pluginDesc0.equals(pluginDesc1))
return false;
Set prereqUIds0= (Set)fPrereqsMapping.get(pluginDesc0);
return prereqUIds0.contains(pluginDesc1);
}
/**
* Initialize this comparator.
*
* @param elements an array of Java editor hover descriptors
*/
private void initialize(Object[] elements) {
int length= elements.length;
fDescriptorMapping= new HashMap(length);
fPrereqsMapping= new HashMap(length);
Set fBundleSet= new HashSet(length);
for (int i= 0; i < length; i++) {
IExtension extension = getConfigurationElement(elements[i]).getDeclaringExtension();
Bundle bundle = Platform.getBundle(extension.getNamespace());
fDescriptorMapping.put(elements[i], bundle.getSymbolicName());
fBundleSet.add(bundle);
}
Iterator iter= fBundleSet.iterator();
while (iter.hasNext()) {
Bundle bundle= (Bundle)iter.next();
List toTest= new ArrayList(fBundleSet);
toTest.remove(bundle);
Set prereqUIds= new HashSet(Math.max(0, toTest.size() - 1));
fPrereqsMapping.put(bundle.getSymbolicName(), prereqUIds);
String requires = (String)bundle.getHeaders().get(Constants.REQUIRE_BUNDLE);
ManifestElement[] manifestElements;
try {
manifestElements = ManifestElement.parseHeader(Constants.REQUIRE_BUNDLE, requires);
} catch (BundleException e) {
- String message= "ConfigurationElementSorter: getting required plug-ins for " + bundle.getSymbolicName() + "failed"; //$NON-NLS-1$ //$NON-NLS-2$
+ String message= "ConfigurationElementSorter: getting required plug-ins for '" + bundle.getSymbolicName() + "' failed"; //$NON-NLS-1$ //$NON-NLS-2$
Status status= new Status(IStatus.ERROR, TextEditorPlugin.PLUGIN_ID, IStatus.OK, message, e);
TextEditorPlugin.getDefault().getLog().log(status);
continue;
}
if (manifestElements == null)
continue;
int i= 0;
while (i < manifestElements.length && !toTest.isEmpty()) {
String prereqUId= manifestElements[i].getValue();
for (int j= 0; j < toTest.size();) {
Bundle toTest_j= (Bundle)toTest.get(j);
if (toTest_j.getSymbolicName().equals(prereqUId)) {
toTest.remove(toTest_j);
prereqUIds.add(toTest_j.getSymbolicName());
} else
j++;
}
i++;
}
}
}
}
}
| true | true | private void initialize(Object[] elements) {
int length= elements.length;
fDescriptorMapping= new HashMap(length);
fPrereqsMapping= new HashMap(length);
Set fBundleSet= new HashSet(length);
for (int i= 0; i < length; i++) {
IExtension extension = getConfigurationElement(elements[i]).getDeclaringExtension();
Bundle bundle = Platform.getBundle(extension.getNamespace());
fDescriptorMapping.put(elements[i], bundle.getSymbolicName());
fBundleSet.add(bundle);
}
Iterator iter= fBundleSet.iterator();
while (iter.hasNext()) {
Bundle bundle= (Bundle)iter.next();
List toTest= new ArrayList(fBundleSet);
toTest.remove(bundle);
Set prereqUIds= new HashSet(Math.max(0, toTest.size() - 1));
fPrereqsMapping.put(bundle.getSymbolicName(), prereqUIds);
String requires = (String)bundle.getHeaders().get(Constants.REQUIRE_BUNDLE);
ManifestElement[] manifestElements;
try {
manifestElements = ManifestElement.parseHeader(Constants.REQUIRE_BUNDLE, requires);
} catch (BundleException e) {
String message= "ConfigurationElementSorter: getting required plug-ins for " + bundle.getSymbolicName() + "failed"; //$NON-NLS-1$ //$NON-NLS-2$
Status status= new Status(IStatus.ERROR, TextEditorPlugin.PLUGIN_ID, IStatus.OK, message, e);
TextEditorPlugin.getDefault().getLog().log(status);
continue;
}
if (manifestElements == null)
continue;
int i= 0;
while (i < manifestElements.length && !toTest.isEmpty()) {
String prereqUId= manifestElements[i].getValue();
for (int j= 0; j < toTest.size();) {
Bundle toTest_j= (Bundle)toTest.get(j);
if (toTest_j.getSymbolicName().equals(prereqUId)) {
toTest.remove(toTest_j);
prereqUIds.add(toTest_j.getSymbolicName());
} else
j++;
}
i++;
}
}
}
| private void initialize(Object[] elements) {
int length= elements.length;
fDescriptorMapping= new HashMap(length);
fPrereqsMapping= new HashMap(length);
Set fBundleSet= new HashSet(length);
for (int i= 0; i < length; i++) {
IExtension extension = getConfigurationElement(elements[i]).getDeclaringExtension();
Bundle bundle = Platform.getBundle(extension.getNamespace());
fDescriptorMapping.put(elements[i], bundle.getSymbolicName());
fBundleSet.add(bundle);
}
Iterator iter= fBundleSet.iterator();
while (iter.hasNext()) {
Bundle bundle= (Bundle)iter.next();
List toTest= new ArrayList(fBundleSet);
toTest.remove(bundle);
Set prereqUIds= new HashSet(Math.max(0, toTest.size() - 1));
fPrereqsMapping.put(bundle.getSymbolicName(), prereqUIds);
String requires = (String)bundle.getHeaders().get(Constants.REQUIRE_BUNDLE);
ManifestElement[] manifestElements;
try {
manifestElements = ManifestElement.parseHeader(Constants.REQUIRE_BUNDLE, requires);
} catch (BundleException e) {
String message= "ConfigurationElementSorter: getting required plug-ins for '" + bundle.getSymbolicName() + "' failed"; //$NON-NLS-1$ //$NON-NLS-2$
Status status= new Status(IStatus.ERROR, TextEditorPlugin.PLUGIN_ID, IStatus.OK, message, e);
TextEditorPlugin.getDefault().getLog().log(status);
continue;
}
if (manifestElements == null)
continue;
int i= 0;
while (i < manifestElements.length && !toTest.isEmpty()) {
String prereqUId= manifestElements[i].getValue();
for (int j= 0; j < toTest.size();) {
Bundle toTest_j= (Bundle)toTest.get(j);
if (toTest_j.getSymbolicName().equals(prereqUId)) {
toTest.remove(toTest_j);
prereqUIds.add(toTest_j.getSymbolicName());
} else
j++;
}
i++;
}
}
}
|
diff --git a/sonar-php-plugin/src/test/java/org/sonar/plugins/php/core/profiles/SonarWayProfileTest.java b/sonar-php-plugin/src/test/java/org/sonar/plugins/php/core/profiles/SonarWayProfileTest.java
index 720a9151..a2b05ef8 100644
--- a/sonar-php-plugin/src/test/java/org/sonar/plugins/php/core/profiles/SonarWayProfileTest.java
+++ b/sonar-php-plugin/src/test/java/org/sonar/plugins/php/core/profiles/SonarWayProfileTest.java
@@ -1,55 +1,55 @@
/*
* Sonar PHP Plugin
* Copyright (C) 2010 Codehaus Sonar Plugins
* [email protected]
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.php.core.profiles;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import java.util.List;
import org.junit.Test;
import org.sonar.api.platform.ServerFileSystem;
import org.sonar.api.profiles.RulesProfile;
import org.sonar.api.profiles.XMLProfileParser;
import org.sonar.api.rules.Rule;
import org.sonar.api.rules.RuleFinder;
import org.sonar.api.rules.XMLRuleParser;
import org.sonar.api.utils.ValidationMessages;
import org.sonar.plugins.php.codesniffer.PhpCodeSnifferProfileExporterTest.MockPhpCodeSnifferRuleFinder;
import org.sonar.plugins.php.codesniffer.PhpCodeSnifferRuleRepository;
public class SonarWayProfileTest {
@Test
public void testCreateProfileValidationMessages() {
ServerFileSystem fileSystem = mock(ServerFileSystem.class);
PhpCodeSnifferRuleRepository repository = new PhpCodeSnifferRuleRepository(fileSystem, new XMLRuleParser());
List<Rule> rules = repository.createRules();
RuleFinder ruleFinder = new MockPhpCodeSnifferRuleFinder(rules);
XMLProfileParser parser = new XMLProfileParser(ruleFinder);
SonarWayProfile profile = new SonarWayProfile(parser);
ValidationMessages messages = ValidationMessages.create();
RulesProfile rulesProfile = profile.createProfile(messages);
assertNotNull(rulesProfile);
- assertEquals("Sonar PHP Way", rulesProfile.getName());
+ assertEquals("Sonar Way", rulesProfile.getName());
}
}
| true | true | public void testCreateProfileValidationMessages() {
ServerFileSystem fileSystem = mock(ServerFileSystem.class);
PhpCodeSnifferRuleRepository repository = new PhpCodeSnifferRuleRepository(fileSystem, new XMLRuleParser());
List<Rule> rules = repository.createRules();
RuleFinder ruleFinder = new MockPhpCodeSnifferRuleFinder(rules);
XMLProfileParser parser = new XMLProfileParser(ruleFinder);
SonarWayProfile profile = new SonarWayProfile(parser);
ValidationMessages messages = ValidationMessages.create();
RulesProfile rulesProfile = profile.createProfile(messages);
assertNotNull(rulesProfile);
assertEquals("Sonar PHP Way", rulesProfile.getName());
}
| public void testCreateProfileValidationMessages() {
ServerFileSystem fileSystem = mock(ServerFileSystem.class);
PhpCodeSnifferRuleRepository repository = new PhpCodeSnifferRuleRepository(fileSystem, new XMLRuleParser());
List<Rule> rules = repository.createRules();
RuleFinder ruleFinder = new MockPhpCodeSnifferRuleFinder(rules);
XMLProfileParser parser = new XMLProfileParser(ruleFinder);
SonarWayProfile profile = new SonarWayProfile(parser);
ValidationMessages messages = ValidationMessages.create();
RulesProfile rulesProfile = profile.createProfile(messages);
assertNotNull(rulesProfile);
assertEquals("Sonar Way", rulesProfile.getName());
}
|
diff --git a/src/mitzi/MitziBrain.java b/src/mitzi/MitziBrain.java
index 2a92de1..d96194b 100644
--- a/src/mitzi/MitziBrain.java
+++ b/src/mitzi/MitziBrain.java
@@ -1,325 +1,325 @@
package mitzi;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import static mitzi.MateScores.*;
import mitzi.UCIReporter.InfoType;
public class MitziBrain implements IBrain {
private GameState game_state;
private long eval_counter;
private long table_counter = 0;
private IPositionAnalyzer board_analyzer = new BoardAnalyzer();
private long start_mtime = System.currentTimeMillis();
@Override
public void set(GameState game_state) {
this.game_state = game_state;
this.eval_counter = 0;
}
private long runTime() {
return System.currentTimeMillis() - start_mtime;
}
/**
* Sends updates about evaluation status to UCI GUI.
*
*/
class UCIUpdater extends TimerTask {
private long old_mtime;
private long old_eval_counter;
private long old_eval_counter_seldepth;
@Override
public void run() {
long mtime = System.currentTimeMillis();
long eval_span_0 = eval_counter - old_eval_counter;
long eval_span_sel = +BoardAnalyzer.eval_counter_seldepth
- old_eval_counter_seldepth;
long eval_span = eval_span_0 + eval_span_sel;
if (old_mtime != 0) {
long time_span = mtime - old_mtime;
UCIReporter.sendInfoNum(InfoType.NPS, eval_span * 1000
/ time_span);
UCIReporter.sendInfoNum(InfoType.HASHFULL,
ResultCache.getHashfull());
}
old_mtime = mtime;
old_eval_counter += eval_span_0;
old_eval_counter_seldepth += eval_span_sel;
}
}
/**
* NegaMax with Alpha Beta Pruning and Transposition Tables
*
* @see <a
* href="http://en.wikipedia.org/wiki/Negamax#NegaMax_with_Alpha_Beta_Pruning_and_Transposition_Tables">NegaMax
* with Alpha Beta Pruning and Transposition Tables</a>
* @param position
* the position to evaluate
* @param total_depth
* the total depth to search
* @param depth
* the remaining depth to search
* @param alpha
* the alpha value
* @param beta
* the beta value
* @return returns the result of the evaluation
*/
private AnalysisResult evalBoard(IPosition position, int total_depth,
int depth, int alpha, int beta) {
// ---------------------------------------------------------------------------------------
int alpha_old = alpha;
// Cache lookup
AnalysisResult entry = ResultCache.getResult(position);
if (entry != null && entry.plys_to_eval0 >= depth) {
table_counter++;
if (entry.flag == Flag.EXACT)
return entry.tinyCopy();
else if (entry.flag == Flag.LOWERBOUND)
alpha = Math.max(alpha, entry.score);
else if (entry.flag == Flag.UPPERBOUND)
beta = Math.min(beta, entry.score);
if (alpha >= beta)
return entry.tinyCopy();
}
// ---------------------------------------------------------------------------------------
// base of complete tree search
if (depth == 0) {
// position is a leaf node
return board_analyzer.evalBoard(position, alpha, beta);
}
// ---------------------------------------------------------------------------------------
// whose move is it?
Side side = position.getActiveColor();
int side_sign = Side.getSideSign(side);
// ---------------------------------------------------------------------------------------
// generate moves
List<IMove> moves = position.getPossibleMoves();
// check for mate and stalemate
if (moves.isEmpty()) {
eval_counter++;
if (position.isCheckPosition()) {
return new AnalysisResult(NEG_INF * side_sign, false, false, 0,
0, Flag.EXACT);
} else {
return new AnalysisResult(0, true, false, 0, 0, Flag.EXACT);
}
}
// ---------------------------------------------------------------------------------------
// Sort the moves:
ArrayList<IMove> ordered_moves = new ArrayList<IMove>(40);
ArrayList<IMove> remaining_moves = new ArrayList<IMove>(40);
BasicMoveComparator move_comparator = new BasicMoveComparator(position);
// Get Killer Moves:
List<IMove> killer_moves = KillerMoves.getKillerMoves(total_depth
- depth);
// if possible use the moves from Position cache as the moves with
// highest priority
if (entry != null) {
ordered_moves.addAll(entry.best_moves);
for (IMove k_move : killer_moves)
if (position.isPossibleMove(k_move)
&& !ordered_moves.contains(k_move))
ordered_moves.add(k_move);
} else {
// Killer_moves have highest priority
for (IMove k_move : killer_moves)
if (position.isPossibleMove(k_move))
ordered_moves.add(k_move);
}
// add the remaining moves and sort them using a basic heuristic
for (IMove move : moves)
if (!ordered_moves.contains(move))
remaining_moves.add(move);
Collections.sort(remaining_moves,
Collections.reverseOrder(move_comparator));
ordered_moves.addAll(remaining_moves);
// ---------------------------------------------------------------------------------------
if (entry != null && entry.plys_to_eval0 < depth)
entry.best_moves.clear();
// create new AnalysisResult and parent
AnalysisResult new_entry = null, parent = null;
if (entry == null)
new_entry = new AnalysisResult(0, null, false, 0, 0, null);
int best_value = NEG_INF; // this starts always at negative!
int i = 0;
// alpha beta search
for (IMove move : ordered_moves) {
if (depth == total_depth && total_depth >= 6) {
// output currently searched move to UCI
UCIReporter.sendInfoCurrMove(move, i + 1);
}
IPosition child_pos = position.doMove(move).new_position;
AnalysisResult result = evalBoard(child_pos, total_depth,
depth - 1, -beta, -alpha);
int negaval = result.score * side_sign;
// better variation found
- if (negaval > best_value) {
+ if (negaval > best_value || parent == null) {
best_value = negaval;
// update cache entry
if (entry != null && entry.plys_to_eval0 < depth)
entry.best_moves.add(move);
if (entry == null)
new_entry.best_moves.add(move);
// update AnalysisResult
byte old_seldepth = (parent == null ? 0
: parent.plys_to_seldepth);
parent = result; // change reference
parent.best_move = move;
parent.plys_to_eval0 = (byte) depth;
if (best_value != POS_INF) {
parent.plys_to_seldepth = (byte) Math.max(old_seldepth,
parent.plys_to_seldepth);
}
// output to UCI
// boolean truly_better = negaval > best_value;
if (depth == total_depth) { // && truly_better) {
position.updateAnalysisResult(parent);
UCIReporter.sendInfoPV(game_state.getPosition(), runTime());
}
}
// alpha beta cutoff
alpha = Math.max(alpha, negaval);
if (alpha >= beta) {
// set also KillerMove:
if (!killer_moves.contains(move))
KillerMoves.addKillerMove(total_depth - depth, move,
killer_moves);
break;
}
i++;
}
// ---------------------------------------------------------------------------------------
// Transposition Table Store; game_state is the lookup key for parent
if (parent.score <= alpha_old)
parent.flag = Flag.UPPERBOUND;
else if (parent.score >= beta)
parent.flag = Flag.LOWERBOUND;
else
parent.flag = Flag.EXACT;
if (entry != null && entry.plys_to_eval0 < depth) {
entry.tinySet(parent);
Collections.reverse(entry.best_moves);
}
if (entry == null) {
new_entry.tinySet(parent);
Collections.reverse(new_entry.best_moves);
ResultCache.setResult(position, new_entry);
}
return parent;
}
@Override
public IMove search(int movetime, int maxMoveTime, int searchDepth,
boolean infinite, List<IMove> searchMoves) {
// first of all, ignoring the timings and restriction to certain
// moves...
IPosition position = game_state.getPosition();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new UCIUpdater(), 1000, 5000);
start_mtime = System.currentTimeMillis();
// iterative deepening
AnalysisResult result = null;
// Parameters for aspiration windows
int alpha = NEG_INF; // initial value
int beta = POS_INF; // initial value
int asp_window = 25; // often 50 or 25 is used
int factor = 2; // factor for increasing if out of bounds
for (int current_depth = 1; current_depth <= searchDepth; current_depth++) {
table_counter = 0;
result = evalBoard(position, current_depth, current_depth, alpha,
beta);
position.updateAnalysisResult(result);
if (result.score == POS_INF || result.score == NEG_INF) {
break;
}
// If Value is out of bounds, redo search with larger bounds, but
// with the same variation tree
if (result.score <= alpha) {
alpha -= factor * asp_window;
current_depth--;
UCIReporter.sendInfoString("Boards found: " + table_counter);
continue;
} else if (result.score >= beta) {
beta += factor * asp_window;
current_depth--;
UCIReporter.sendInfoString("Boards found: " + table_counter);
continue;
}
alpha = result.score - asp_window;
beta = result.score + asp_window;
UCIReporter.sendInfoString("Boards found: " + table_counter);
}
timer.cancel();
UCIReporter.sendInfoPV(position, runTime());
KillerMoves.updateKillerMove();
return result.best_move;
}
@Override
public IMove stop() {
// TODO Auto-generated method stub
return null;
}
}
| true | true | private AnalysisResult evalBoard(IPosition position, int total_depth,
int depth, int alpha, int beta) {
// ---------------------------------------------------------------------------------------
int alpha_old = alpha;
// Cache lookup
AnalysisResult entry = ResultCache.getResult(position);
if (entry != null && entry.plys_to_eval0 >= depth) {
table_counter++;
if (entry.flag == Flag.EXACT)
return entry.tinyCopy();
else if (entry.flag == Flag.LOWERBOUND)
alpha = Math.max(alpha, entry.score);
else if (entry.flag == Flag.UPPERBOUND)
beta = Math.min(beta, entry.score);
if (alpha >= beta)
return entry.tinyCopy();
}
// ---------------------------------------------------------------------------------------
// base of complete tree search
if (depth == 0) {
// position is a leaf node
return board_analyzer.evalBoard(position, alpha, beta);
}
// ---------------------------------------------------------------------------------------
// whose move is it?
Side side = position.getActiveColor();
int side_sign = Side.getSideSign(side);
// ---------------------------------------------------------------------------------------
// generate moves
List<IMove> moves = position.getPossibleMoves();
// check for mate and stalemate
if (moves.isEmpty()) {
eval_counter++;
if (position.isCheckPosition()) {
return new AnalysisResult(NEG_INF * side_sign, false, false, 0,
0, Flag.EXACT);
} else {
return new AnalysisResult(0, true, false, 0, 0, Flag.EXACT);
}
}
// ---------------------------------------------------------------------------------------
// Sort the moves:
ArrayList<IMove> ordered_moves = new ArrayList<IMove>(40);
ArrayList<IMove> remaining_moves = new ArrayList<IMove>(40);
BasicMoveComparator move_comparator = new BasicMoveComparator(position);
// Get Killer Moves:
List<IMove> killer_moves = KillerMoves.getKillerMoves(total_depth
- depth);
// if possible use the moves from Position cache as the moves with
// highest priority
if (entry != null) {
ordered_moves.addAll(entry.best_moves);
for (IMove k_move : killer_moves)
if (position.isPossibleMove(k_move)
&& !ordered_moves.contains(k_move))
ordered_moves.add(k_move);
} else {
// Killer_moves have highest priority
for (IMove k_move : killer_moves)
if (position.isPossibleMove(k_move))
ordered_moves.add(k_move);
}
// add the remaining moves and sort them using a basic heuristic
for (IMove move : moves)
if (!ordered_moves.contains(move))
remaining_moves.add(move);
Collections.sort(remaining_moves,
Collections.reverseOrder(move_comparator));
ordered_moves.addAll(remaining_moves);
// ---------------------------------------------------------------------------------------
if (entry != null && entry.plys_to_eval0 < depth)
entry.best_moves.clear();
// create new AnalysisResult and parent
AnalysisResult new_entry = null, parent = null;
if (entry == null)
new_entry = new AnalysisResult(0, null, false, 0, 0, null);
int best_value = NEG_INF; // this starts always at negative!
int i = 0;
// alpha beta search
for (IMove move : ordered_moves) {
if (depth == total_depth && total_depth >= 6) {
// output currently searched move to UCI
UCIReporter.sendInfoCurrMove(move, i + 1);
}
IPosition child_pos = position.doMove(move).new_position;
AnalysisResult result = evalBoard(child_pos, total_depth,
depth - 1, -beta, -alpha);
int negaval = result.score * side_sign;
// better variation found
if (negaval > best_value) {
best_value = negaval;
// update cache entry
if (entry != null && entry.plys_to_eval0 < depth)
entry.best_moves.add(move);
if (entry == null)
new_entry.best_moves.add(move);
// update AnalysisResult
byte old_seldepth = (parent == null ? 0
: parent.plys_to_seldepth);
parent = result; // change reference
parent.best_move = move;
parent.plys_to_eval0 = (byte) depth;
if (best_value != POS_INF) {
parent.plys_to_seldepth = (byte) Math.max(old_seldepth,
parent.plys_to_seldepth);
}
// output to UCI
// boolean truly_better = negaval > best_value;
if (depth == total_depth) { // && truly_better) {
position.updateAnalysisResult(parent);
UCIReporter.sendInfoPV(game_state.getPosition(), runTime());
}
}
// alpha beta cutoff
alpha = Math.max(alpha, negaval);
if (alpha >= beta) {
// set also KillerMove:
if (!killer_moves.contains(move))
KillerMoves.addKillerMove(total_depth - depth, move,
killer_moves);
break;
}
i++;
}
// ---------------------------------------------------------------------------------------
// Transposition Table Store; game_state is the lookup key for parent
if (parent.score <= alpha_old)
parent.flag = Flag.UPPERBOUND;
else if (parent.score >= beta)
parent.flag = Flag.LOWERBOUND;
else
parent.flag = Flag.EXACT;
if (entry != null && entry.plys_to_eval0 < depth) {
entry.tinySet(parent);
Collections.reverse(entry.best_moves);
}
if (entry == null) {
new_entry.tinySet(parent);
Collections.reverse(new_entry.best_moves);
ResultCache.setResult(position, new_entry);
}
return parent;
}
@Override
public IMove search(int movetime, int maxMoveTime, int searchDepth,
boolean infinite, List<IMove> searchMoves) {
// first of all, ignoring the timings and restriction to certain
// moves...
IPosition position = game_state.getPosition();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new UCIUpdater(), 1000, 5000);
start_mtime = System.currentTimeMillis();
// iterative deepening
AnalysisResult result = null;
// Parameters for aspiration windows
int alpha = NEG_INF; // initial value
int beta = POS_INF; // initial value
int asp_window = 25; // often 50 or 25 is used
int factor = 2; // factor for increasing if out of bounds
for (int current_depth = 1; current_depth <= searchDepth; current_depth++) {
table_counter = 0;
result = evalBoard(position, current_depth, current_depth, alpha,
beta);
position.updateAnalysisResult(result);
if (result.score == POS_INF || result.score == NEG_INF) {
break;
}
// If Value is out of bounds, redo search with larger bounds, but
// with the same variation tree
if (result.score <= alpha) {
alpha -= factor * asp_window;
current_depth--;
UCIReporter.sendInfoString("Boards found: " + table_counter);
continue;
} else if (result.score >= beta) {
beta += factor * asp_window;
current_depth--;
UCIReporter.sendInfoString("Boards found: " + table_counter);
continue;
}
alpha = result.score - asp_window;
beta = result.score + asp_window;
UCIReporter.sendInfoString("Boards found: " + table_counter);
}
timer.cancel();
UCIReporter.sendInfoPV(position, runTime());
KillerMoves.updateKillerMove();
return result.best_move;
}
@Override
public IMove stop() {
// TODO Auto-generated method stub
return null;
}
}
| private AnalysisResult evalBoard(IPosition position, int total_depth,
int depth, int alpha, int beta) {
// ---------------------------------------------------------------------------------------
int alpha_old = alpha;
// Cache lookup
AnalysisResult entry = ResultCache.getResult(position);
if (entry != null && entry.plys_to_eval0 >= depth) {
table_counter++;
if (entry.flag == Flag.EXACT)
return entry.tinyCopy();
else if (entry.flag == Flag.LOWERBOUND)
alpha = Math.max(alpha, entry.score);
else if (entry.flag == Flag.UPPERBOUND)
beta = Math.min(beta, entry.score);
if (alpha >= beta)
return entry.tinyCopy();
}
// ---------------------------------------------------------------------------------------
// base of complete tree search
if (depth == 0) {
// position is a leaf node
return board_analyzer.evalBoard(position, alpha, beta);
}
// ---------------------------------------------------------------------------------------
// whose move is it?
Side side = position.getActiveColor();
int side_sign = Side.getSideSign(side);
// ---------------------------------------------------------------------------------------
// generate moves
List<IMove> moves = position.getPossibleMoves();
// check for mate and stalemate
if (moves.isEmpty()) {
eval_counter++;
if (position.isCheckPosition()) {
return new AnalysisResult(NEG_INF * side_sign, false, false, 0,
0, Flag.EXACT);
} else {
return new AnalysisResult(0, true, false, 0, 0, Flag.EXACT);
}
}
// ---------------------------------------------------------------------------------------
// Sort the moves:
ArrayList<IMove> ordered_moves = new ArrayList<IMove>(40);
ArrayList<IMove> remaining_moves = new ArrayList<IMove>(40);
BasicMoveComparator move_comparator = new BasicMoveComparator(position);
// Get Killer Moves:
List<IMove> killer_moves = KillerMoves.getKillerMoves(total_depth
- depth);
// if possible use the moves from Position cache as the moves with
// highest priority
if (entry != null) {
ordered_moves.addAll(entry.best_moves);
for (IMove k_move : killer_moves)
if (position.isPossibleMove(k_move)
&& !ordered_moves.contains(k_move))
ordered_moves.add(k_move);
} else {
// Killer_moves have highest priority
for (IMove k_move : killer_moves)
if (position.isPossibleMove(k_move))
ordered_moves.add(k_move);
}
// add the remaining moves and sort them using a basic heuristic
for (IMove move : moves)
if (!ordered_moves.contains(move))
remaining_moves.add(move);
Collections.sort(remaining_moves,
Collections.reverseOrder(move_comparator));
ordered_moves.addAll(remaining_moves);
// ---------------------------------------------------------------------------------------
if (entry != null && entry.plys_to_eval0 < depth)
entry.best_moves.clear();
// create new AnalysisResult and parent
AnalysisResult new_entry = null, parent = null;
if (entry == null)
new_entry = new AnalysisResult(0, null, false, 0, 0, null);
int best_value = NEG_INF; // this starts always at negative!
int i = 0;
// alpha beta search
for (IMove move : ordered_moves) {
if (depth == total_depth && total_depth >= 6) {
// output currently searched move to UCI
UCIReporter.sendInfoCurrMove(move, i + 1);
}
IPosition child_pos = position.doMove(move).new_position;
AnalysisResult result = evalBoard(child_pos, total_depth,
depth - 1, -beta, -alpha);
int negaval = result.score * side_sign;
// better variation found
if (negaval > best_value || parent == null) {
best_value = negaval;
// update cache entry
if (entry != null && entry.plys_to_eval0 < depth)
entry.best_moves.add(move);
if (entry == null)
new_entry.best_moves.add(move);
// update AnalysisResult
byte old_seldepth = (parent == null ? 0
: parent.plys_to_seldepth);
parent = result; // change reference
parent.best_move = move;
parent.plys_to_eval0 = (byte) depth;
if (best_value != POS_INF) {
parent.plys_to_seldepth = (byte) Math.max(old_seldepth,
parent.plys_to_seldepth);
}
// output to UCI
// boolean truly_better = negaval > best_value;
if (depth == total_depth) { // && truly_better) {
position.updateAnalysisResult(parent);
UCIReporter.sendInfoPV(game_state.getPosition(), runTime());
}
}
// alpha beta cutoff
alpha = Math.max(alpha, negaval);
if (alpha >= beta) {
// set also KillerMove:
if (!killer_moves.contains(move))
KillerMoves.addKillerMove(total_depth - depth, move,
killer_moves);
break;
}
i++;
}
// ---------------------------------------------------------------------------------------
// Transposition Table Store; game_state is the lookup key for parent
if (parent.score <= alpha_old)
parent.flag = Flag.UPPERBOUND;
else if (parent.score >= beta)
parent.flag = Flag.LOWERBOUND;
else
parent.flag = Flag.EXACT;
if (entry != null && entry.plys_to_eval0 < depth) {
entry.tinySet(parent);
Collections.reverse(entry.best_moves);
}
if (entry == null) {
new_entry.tinySet(parent);
Collections.reverse(new_entry.best_moves);
ResultCache.setResult(position, new_entry);
}
return parent;
}
@Override
public IMove search(int movetime, int maxMoveTime, int searchDepth,
boolean infinite, List<IMove> searchMoves) {
// first of all, ignoring the timings and restriction to certain
// moves...
IPosition position = game_state.getPosition();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new UCIUpdater(), 1000, 5000);
start_mtime = System.currentTimeMillis();
// iterative deepening
AnalysisResult result = null;
// Parameters for aspiration windows
int alpha = NEG_INF; // initial value
int beta = POS_INF; // initial value
int asp_window = 25; // often 50 or 25 is used
int factor = 2; // factor for increasing if out of bounds
for (int current_depth = 1; current_depth <= searchDepth; current_depth++) {
table_counter = 0;
result = evalBoard(position, current_depth, current_depth, alpha,
beta);
position.updateAnalysisResult(result);
if (result.score == POS_INF || result.score == NEG_INF) {
break;
}
// If Value is out of bounds, redo search with larger bounds, but
// with the same variation tree
if (result.score <= alpha) {
alpha -= factor * asp_window;
current_depth--;
UCIReporter.sendInfoString("Boards found: " + table_counter);
continue;
} else if (result.score >= beta) {
beta += factor * asp_window;
current_depth--;
UCIReporter.sendInfoString("Boards found: " + table_counter);
continue;
}
alpha = result.score - asp_window;
beta = result.score + asp_window;
UCIReporter.sendInfoString("Boards found: " + table_counter);
}
timer.cancel();
UCIReporter.sendInfoPV(position, runTime());
KillerMoves.updateKillerMove();
return result.best_move;
}
@Override
public IMove stop() {
// TODO Auto-generated method stub
return null;
}
}
|
diff --git a/map/map-impl/src/main/java/org/mobicents/protocols/ss7/map/service/callhandling/ProvideRoamingNumberResponseImpl.java b/map/map-impl/src/main/java/org/mobicents/protocols/ss7/map/service/callhandling/ProvideRoamingNumberResponseImpl.java
index b76fe1233..af9e2ca46 100644
--- a/map/map-impl/src/main/java/org/mobicents/protocols/ss7/map/service/callhandling/ProvideRoamingNumberResponseImpl.java
+++ b/map/map-impl/src/main/java/org/mobicents/protocols/ss7/map/service/callhandling/ProvideRoamingNumberResponseImpl.java
@@ -1,267 +1,267 @@
package org.mobicents.protocols.ss7.map.service.callhandling;
import java.io.IOException;
import org.mobicents.protocols.asn.AsnException;
import org.mobicents.protocols.asn.AsnInputStream;
import org.mobicents.protocols.asn.AsnOutputStream;
import org.mobicents.protocols.asn.Tag;
import org.mobicents.protocols.ss7.map.api.MAPException;
import org.mobicents.protocols.ss7.map.api.MAPMessageType;
import org.mobicents.protocols.ss7.map.api.MAPOperationCode;
import org.mobicents.protocols.ss7.map.api.MAPParsingComponentException;
import org.mobicents.protocols.ss7.map.api.MAPParsingComponentExceptionReason;
import org.mobicents.protocols.ss7.map.api.primitives.ISDNAddressString;
import org.mobicents.protocols.ss7.map.api.primitives.MAPExtensionContainer;
import org.mobicents.protocols.ss7.map.api.service.callhandling.ProvideRoamingNumberResponse;
import org.mobicents.protocols.ss7.map.primitives.ISDNAddressStringImpl;
import org.mobicents.protocols.ss7.map.primitives.MAPExtensionContainerImpl;
/**
*
* @author Lasith Waruna Perera
*
*/
public class ProvideRoamingNumberResponseImpl extends CallHandlingMessageImpl implements ProvideRoamingNumberResponse{
public ISDNAddressString roamingNumber;
public MAPExtensionContainer extensionContainer;
public boolean releaseResourcesSupported;
public ISDNAddressString vmscAddress;
private long mapProtocolVersion;
public ProvideRoamingNumberResponseImpl(ISDNAddressString roamingNumber,
MAPExtensionContainer extensionContainer,
boolean releaseResourcesSupported, ISDNAddressString vmscAddress,
long mapProtocolVersion) {
super();
this.roamingNumber = roamingNumber;
this.extensionContainer = extensionContainer;
this.releaseResourcesSupported = releaseResourcesSupported;
this.vmscAddress = vmscAddress;
this.mapProtocolVersion = mapProtocolVersion;
}
public ProvideRoamingNumberResponseImpl(long mapProtocolVersion){
this.mapProtocolVersion = mapProtocolVersion;
}
@Override
public MAPMessageType getMessageType() {
return MAPMessageType.privideRoamingNumber_Response;
}
@Override
public int getOperationCode() {
return MAPOperationCode.provideRoamingNumber;
}
@Override
public int getTag() throws MAPException {
if (this.mapProtocolVersion >= 3) {
return Tag.SEQUENCE;
} else {
return Tag.STRING_OCTET;
}
}
@Override
public int getTagClass() {
return Tag.CLASS_UNIVERSAL;
}
@Override
public boolean getIsPrimitive() {
if (this.mapProtocolVersion >= 3) {
return false;
} else {
return true;
}
}
@Override
public void decodeAll(AsnInputStream ansIS)
throws MAPParsingComponentException {
try {
int length = ansIS.readLength();
this._decode(ansIS, length);
} catch (IOException e) {
e.printStackTrace();
throw new MAPParsingComponentException("IOException when decoding ProvideRoamingNumberResponse: " + e.getMessage(), e,
MAPParsingComponentExceptionReason.MistypedParameter);
} catch (AsnException e) {
e.printStackTrace();
throw new MAPParsingComponentException("AsnException when decoding ProvideRoamingNumberResponse: " + e.getMessage(), e,
MAPParsingComponentExceptionReason.MistypedParameter);
} catch (Exception e) {
e.printStackTrace();
throw new MAPParsingComponentException("AsnException when decoding ProvideRoamingNumberResponse: " + e.getMessage(), e,
MAPParsingComponentExceptionReason.MistypedParameter);
}
}
@Override
public void decodeData(AsnInputStream ansIS, int length)
throws MAPParsingComponentException {
try {
this._decode(ansIS, length);
} catch (IOException e) {
e.printStackTrace();
throw new MAPParsingComponentException("IOException when decoding ProvideRoamingNumberResponse: " + e.getMessage(), e,
MAPParsingComponentExceptionReason.MistypedParameter);
} catch (AsnException e) {
e.printStackTrace();
throw new MAPParsingComponentException("AsnException when decoding ProvideRoamingNumberResponse: " + e.getMessage(), e,
MAPParsingComponentExceptionReason.MistypedParameter);
} catch (Exception e) {
e.printStackTrace();
}
}
private void _decode(AsnInputStream ansIS, int length) throws MAPParsingComponentException, IOException, AsnException {
this.roamingNumber = null;
this.extensionContainer = null;
this.releaseResourcesSupported = false;
this.vmscAddress = null;
AsnInputStream ais = ansIS.readSequenceStreamData(length);
if (this.mapProtocolVersion >= 3) {
int num = 0;
while (true) {
if (ais.available() == 0)
break;
int tag = ais.readTag();
if(num ==0){
if(ais.getTagClass() != Tag.CLASS_UNIVERSAL && tag != Tag.STRING_OCTET && !ais.isTagPrimitive()){
throw new MAPParsingComponentException("Error while decoding ProvideRoamingNumberResponse " +
".roamingNumber: Parameter 0 bad tag or tag class or not primitive", MAPParsingComponentExceptionReason.MistypedParameter);
}
this.roamingNumber = new ISDNAddressStringImpl();
((ISDNAddressStringImpl) this.roamingNumber).decodeAll(ais);
num++;
}else{
if (ais.getTagClass() == Tag.CLASS_UNIVERSAL) {
if(tag== Tag.STRING_OCTET){
this.vmscAddress = new ISDNAddressStringImpl();
((ISDNAddressStringImpl) this.roamingNumber).decodeAll(ais);
}else if(tag == Tag.SEQUENCE){
this.extensionContainer = new MAPExtensionContainerImpl();
((MAPExtensionContainerImpl)this.extensionContainer).decodeAll(ais);
}else if(tag == Tag.NULL){
ais.readNull();
this.releaseResourcesSupported = true;
}else{
ais.advanceElement();
}
}else{
ais.advanceElement();
}
}
}
}else{
this.roamingNumber = new ISDNAddressStringImpl();
- ((ISDNAddressStringImpl) this.roamingNumber).decodeData(ansIS, length);
+ ((ISDNAddressStringImpl) this.roamingNumber).decodeAll(ais);
}
}
@Override
public void encodeAll(AsnOutputStream asnOs) throws MAPException {
try {
this.encodeAll(asnOs, this.getTagClass(), this.getTag());
} catch (Exception e) {
e.printStackTrace();
throw new MAPException(e);
}
}
@Override
public void encodeAll(AsnOutputStream asnOs, int tagClass, int tag)
throws MAPException {
try {
asnOs.writeTag(tagClass, this.getIsPrimitive(), tag);
int pos = asnOs.StartContentDefiniteLength();
this.encodeData(asnOs);
asnOs.FinalizeContent(pos);
} catch (AsnException e) {
throw new MAPException("AsnException when encoding ProvideRoamingNumberResponse : " + e.getMessage(), e);
}
}
@Override
public void encodeData(AsnOutputStream asnOs) throws MAPException {
if (this.roamingNumber == null)
throw new MAPException("roamingNumber parameter must not be null");
try {
if (this.mapProtocolVersion >= 3) {
((ISDNAddressStringImpl) this.roamingNumber).encodeAll(asnOs);
if (this.extensionContainer != null){
((MAPExtensionContainerImpl) this.extensionContainer).encodeAll(asnOs);
}
if (this.releaseResourcesSupported){
asnOs.writeNull();
}
if (this.vmscAddress!=null){
((MAPExtensionContainerImpl) this.extensionContainer).encodeAll(asnOs);
}
} else {
((ISDNAddressStringImpl) this.roamingNumber).encodeAll(asnOs);
}
} catch (IOException e) {
throw new MAPException("IOException when encoding ProvideRoamingNumberResponse " + e.getMessage(), e);
} catch (AsnException e) {
throw new MAPException("AsnException when encoding ProvideRoamingNumberResponse " + e.getMessage(), e);
}
}
@Override
public ISDNAddressString getRoamingNumber() {
return this.roamingNumber;
}
@Override
public MAPExtensionContainer getExtensionContainer() {
return this.extensionContainer;
}
@Override
public boolean getReleaseResourcesSupported() {
return this.releaseResourcesSupported;
}
@Override
public ISDNAddressString getVmscAddress() {
return this.vmscAddress;
}
@Override
public long getMapProtocolVersion() {
return this.mapProtocolVersion;
}
}
| true | true | private void _decode(AsnInputStream ansIS, int length) throws MAPParsingComponentException, IOException, AsnException {
this.roamingNumber = null;
this.extensionContainer = null;
this.releaseResourcesSupported = false;
this.vmscAddress = null;
AsnInputStream ais = ansIS.readSequenceStreamData(length);
if (this.mapProtocolVersion >= 3) {
int num = 0;
while (true) {
if (ais.available() == 0)
break;
int tag = ais.readTag();
if(num ==0){
if(ais.getTagClass() != Tag.CLASS_UNIVERSAL && tag != Tag.STRING_OCTET && !ais.isTagPrimitive()){
throw new MAPParsingComponentException("Error while decoding ProvideRoamingNumberResponse " +
".roamingNumber: Parameter 0 bad tag or tag class or not primitive", MAPParsingComponentExceptionReason.MistypedParameter);
}
this.roamingNumber = new ISDNAddressStringImpl();
((ISDNAddressStringImpl) this.roamingNumber).decodeAll(ais);
num++;
}else{
if (ais.getTagClass() == Tag.CLASS_UNIVERSAL) {
if(tag== Tag.STRING_OCTET){
this.vmscAddress = new ISDNAddressStringImpl();
((ISDNAddressStringImpl) this.roamingNumber).decodeAll(ais);
}else if(tag == Tag.SEQUENCE){
this.extensionContainer = new MAPExtensionContainerImpl();
((MAPExtensionContainerImpl)this.extensionContainer).decodeAll(ais);
}else if(tag == Tag.NULL){
ais.readNull();
this.releaseResourcesSupported = true;
}else{
ais.advanceElement();
}
}else{
ais.advanceElement();
}
}
}
}else{
this.roamingNumber = new ISDNAddressStringImpl();
((ISDNAddressStringImpl) this.roamingNumber).decodeData(ansIS, length);
}
}
| private void _decode(AsnInputStream ansIS, int length) throws MAPParsingComponentException, IOException, AsnException {
this.roamingNumber = null;
this.extensionContainer = null;
this.releaseResourcesSupported = false;
this.vmscAddress = null;
AsnInputStream ais = ansIS.readSequenceStreamData(length);
if (this.mapProtocolVersion >= 3) {
int num = 0;
while (true) {
if (ais.available() == 0)
break;
int tag = ais.readTag();
if(num ==0){
if(ais.getTagClass() != Tag.CLASS_UNIVERSAL && tag != Tag.STRING_OCTET && !ais.isTagPrimitive()){
throw new MAPParsingComponentException("Error while decoding ProvideRoamingNumberResponse " +
".roamingNumber: Parameter 0 bad tag or tag class or not primitive", MAPParsingComponentExceptionReason.MistypedParameter);
}
this.roamingNumber = new ISDNAddressStringImpl();
((ISDNAddressStringImpl) this.roamingNumber).decodeAll(ais);
num++;
}else{
if (ais.getTagClass() == Tag.CLASS_UNIVERSAL) {
if(tag== Tag.STRING_OCTET){
this.vmscAddress = new ISDNAddressStringImpl();
((ISDNAddressStringImpl) this.roamingNumber).decodeAll(ais);
}else if(tag == Tag.SEQUENCE){
this.extensionContainer = new MAPExtensionContainerImpl();
((MAPExtensionContainerImpl)this.extensionContainer).decodeAll(ais);
}else if(tag == Tag.NULL){
ais.readNull();
this.releaseResourcesSupported = true;
}else{
ais.advanceElement();
}
}else{
ais.advanceElement();
}
}
}
}else{
this.roamingNumber = new ISDNAddressStringImpl();
((ISDNAddressStringImpl) this.roamingNumber).decodeAll(ais);
}
}
|
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/DataSetRuntime.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/DataSetRuntime.java
index e54b8281d..917bd8416 100644
--- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/DataSetRuntime.java
+++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/DataSetRuntime.java
@@ -1,532 +1,533 @@
/*
*************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*
*************************************************************************
*/
package org.eclipse.birt.data.engine.impl;
import java.util.List;
import java.util.Collection;
import java.util.logging.Logger;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.IBaseDataSetDesign;
import org.eclipse.birt.data.engine.api.IOdaDataSetDesign;
import org.eclipse.birt.data.engine.api.IResultMetaData;
import org.eclipse.birt.data.engine.api.IScriptDataSetDesign;
import org.eclipse.birt.data.engine.api.script.IDataRow;
import org.eclipse.birt.data.engine.api.script.IBaseDataSetEventHandler;
import org.eclipse.birt.data.engine.api.script.IDataSetInstanceHandle;
import org.eclipse.birt.data.engine.api.script.IDataSourceInstanceHandle;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.i18n.ResourceConstants;
import org.eclipse.birt.data.engine.odi.IResultIterator;
import org.eclipse.birt.data.engine.odi.IResultObject;
import org.eclipse.birt.data.engine.script.DataRow;
import org.eclipse.birt.data.engine.script.JSDataSet;
import org.eclipse.birt.data.engine.script.DataSetJSEventHandler;
import org.eclipse.birt.data.engine.script.JSOutputParams;
import org.eclipse.birt.data.engine.script.JSRowObject;
import org.eclipse.birt.data.engine.script.JSRows;
import org.eclipse.birt.data.engine.script.ScriptDataSetJSEventHandler;
import org.mozilla.javascript.Scriptable;
/**
* Encapsulates a runtime data set definition. A data set definition
* has two parts: design time properties specified in the report design that are
* static, and runtime properties (e.g., SQL query statement) that
* can be changed in scripts.
* A data set runtime also maintains the current data row. The row can come from
* either of these two sources at any given time: a IResultIterator (after result set has been generated),
* or from a IResultObject (during data set processing).
*/
public abstract class DataSetRuntime implements IDataSetInstanceHandle
{
/** Static design of data set */
private IBaseDataSetDesign dataSetDesign;
/** Javascript object implementing the DataSet class */
private Scriptable jsDataSetObject;
protected PreparedQuery.Executor queryExecutor;
protected static Logger logger = Logger.getLogger( DataSetRuntime.class.getName( ) );
// Fields related to current data row
/** IResultObject which is the current data row */
protected IResultObject resultObj;
/** The result iterator whose iterator position is the current data row */
protected IResultIterator resultSet;
/** Internal index of current data row */
protected int currentRowIndex = -1;
/** Whether update to current data row is allowed */
protected boolean allowUpdateRowData = false;
/** Metadata of curent row */
protected IResultMetaData rowMetaData;
/** Scriptable object implementing the Javascript "row" property */
private JSRowObject jsRowObject;
/** Scriptable object implementing the Javascript "rows" property */
private JSRows jsRowsObject;
/** Object implementing IDataRow interface */
private DataRow dataRow;
/** Scriptable object implementing the Javascript "outputParams" property */
private JSOutputParams jsOutputParamsObject;
/** Scriptable object implementing the internal "_aggr_value" property */
private Scriptable jsAggrValueObject;
private IBaseDataSetEventHandler eventHandler;
protected boolean isOpen;
protected DataSetRuntime( IBaseDataSetDesign dataSetDesign, PreparedQuery.Executor queryExecutor)
{
this.dataSetDesign = dataSetDesign;
this.queryExecutor = queryExecutor;
isOpen = true;
- eventHandler = dataSetDesign.getEventHandler();
+ if ( dataSetDesign != null )
+ eventHandler = dataSetDesign.getEventHandler();
/*
* TODO: TEMPORARY the follow code is temporary. It will be removed once Engine takes over
* script execution from DtE
*/
if ( eventHandler == null )
{
if ( dataSetDesign instanceof IScriptDataSetDesign )
eventHandler = new ScriptDataSetJSEventHandler(
(IScriptDataSetDesign) dataSetDesign );
else if ( dataSetDesign instanceof IOdaDataSetDesign)
eventHandler = new DataSetJSEventHandler( dataSetDesign );
}
/*
* END Temporary
*/
}
public PreparedQuery.Executor getQueryExecutor()
{
return queryExecutor;
}
/**
* Gets the instance of the Javascript 'row' object for this data set
*/
public Scriptable getJSRowObject()
{
if ( !isOpen )
return null;
if ( this.jsRowObject == null )
{
jsRowObject = new JSRowObject( this );
}
return jsRowObject;
}
/**
* Gets the instance of the Javascript 'outputParams' object for this data set
*/
public Scriptable getJSOutputParamsObject()
{
if ( !isOpen )
return null;
if ( jsOutputParamsObject == null )
{
jsOutputParamsObject = new JSOutputParams( this );
}
return jsOutputParamsObject;
}
/**
* Gets the instance of the Javascript 'rows' object for this data set
*/
public Scriptable getJSRowsObject() throws DataException
{
if ( !isOpen )
return null;
if ( this.jsRowsObject == null )
{
// Construct an array of nested data sets
int size = queryExecutor.nestedLevel;
DataSetRuntime[] dataSets = new DataSetRuntime[ size ];
PreparedQuery.Executor executor = queryExecutor;
dataSets[ size - 1 ] = executor.getDataSet();
for ( int i = size -2; i >=0; i--)
{
executor = executor.outerResults.queryExecutor;
dataSets[i] = executor.getDataSet();
}
jsRowsObject = new JSRows( dataSets );
}
return jsRowsObject;
}
public IDataRow getDataRow()
{
if ( !isOpen )
return null;
if (this.dataRow == null)
{
this.dataRow = new DataRow( this );
}
return dataRow;
}
/**
* @return Event handler for this data set
*/
protected IBaseDataSetEventHandler getEventHandler()
{
return eventHandler;
}
/**
* Gets the IBaseDataSetDesign object which defines the design time properties
* associated with this data set
*/
protected IBaseDataSetDesign getDesign()
{
return dataSetDesign;
}
/**
* Gets the name of the design time properties
* associated with this data set
*/
public String getName()
{
if ( dataSetDesign != null)
return dataSetDesign.getName();
else
return null;
}
/**
* @return cache row count
*/
public String getID( )
{
if ( dataSetDesign != null )
return dataSetDesign.getID( );
return null;
}
/**
* @return cache row count
*/
public int getCacheRowCount( )
{
if ( dataSetDesign != null )
return dataSetDesign.getCacheRowCount( );
return 0;
}
public String getDataSourceName()
{
if ( dataSetDesign != null)
return dataSetDesign.getDataSourceName();
else
return null;
}
/**
* Gets the runtime Data Source definition for this data set
*/
public IDataSourceInstanceHandle getDataSource()
{
return this.queryExecutor.dataSource;
}
/**
* Creates an instance of the appropriate subclass based on a specified
* design-time data set definition
* @param dataSetDefn Design-time data set definition.
*/
public static DataSetRuntime newInstance( IBaseDataSetDesign dataSetDefn,
PreparedQuery.Executor queryExecutor ) throws DataException
{
DataSetRuntime dataSet = null;
if ( dataSetDefn instanceof IOdaDataSetDesign )
{
dataSet = new OdaDataSetRuntime( (IOdaDataSetDesign) dataSetDefn, queryExecutor );
}
else if ( dataSetDefn instanceof IScriptDataSetDesign )
{
dataSet = new ScriptDataSetRuntime( (IScriptDataSetDesign) dataSetDefn, queryExecutor );
}
else
{
throw new DataException( ResourceConstants.UNSUPPORTED_DATASET_TYPE );
}
return dataSet;
}
/**
* Gets the Javascript object that wraps this data set runtime
*/
public Scriptable getJSDataSetObject()
{
// JS wrapper is created on demand
if ( jsDataSetObject == null )
{
jsDataSetObject = new JSDataSet( this, queryExecutor.getDataEngine().getSharedScope() );
}
return jsDataSetObject;
}
/**
* Gets the internal Javascript aggregate value object
*/
public Scriptable getJSAggrValueObject()
{
if ( !isOpen )
return null;
if (jsAggrValueObject == null && queryExecutor.aggregates != null )
{
jsAggrValueObject = queryExecutor.aggregates.getJSAggrValueObject();
}
return jsAggrValueObject;
}
/**
* Returns a Javascript scope suitable for running JS event handler code.
* @see org.eclipse.birt.data.engine.api.script.IJavascriptContext#getScriptScope()
*/
public Scriptable getScriptScope()
{
// Data set event handlers are executed as methods on the DataSet object
return getJSDataSetObject();
}
/**
* @see org.eclipse.birt.data.engine.api.script.IDataSetInstanceHandle#getResultMetaData()
*/
public IResultMetaData getResultMetaData() throws DataException
{
if ( !isOpen )
return null;
return queryExecutor.getResultMetaData();
}
public Collection getInputParamBindings()
{
if ( dataSetDesign != null)
return dataSetDesign.getInputParamBindings();
else
return null;
}
public List getComputedColumns()
{
if ( dataSetDesign != null)
return dataSetDesign.getComputedColumns();
else
return null;
}
public List getFilters()
{
if ( dataSetDesign != null)
return dataSetDesign.getFilters();
else
return null;
}
public List getParameters()
{
if ( dataSetDesign != null)
return dataSetDesign.getParameters();
else
return null;
}
public List getResultSetHints()
{
if ( dataSetDesign != null)
return dataSetDesign.getResultSetHints();
else
return null;
}
/** Executes the beforeOpen script associated with the data source */
public void beforeOpen() throws DataException
{
if ( getEventHandler() != null )
{
try
{
getEventHandler().handleBeforeOpen( this );
}
catch ( BirtException e )
{
throw DataException.wrap(e);
}
}
}
/** Executes the beforeClose script associated with the data source */
public void beforeClose() throws DataException
{
if ( getEventHandler() != null )
{
try
{
getEventHandler().handleBeforeClose( this );
}
catch ( BirtException e )
{
throw DataException.wrap(e);
}
}
}
/** Executes the afterOpen script associated with the data source */
public void afterOpen() throws DataException
{
if ( getEventHandler() != null )
{
try
{
getEventHandler().handleAfterOpen( this );
}
catch ( BirtException e )
{
throw DataException.wrap(e);
}
}
}
/** Executes the afterClose script associated with the data source */
public void afterClose() throws DataException
{
if ( getEventHandler() != null )
{
try
{
getEventHandler().handleAfterClose( this );
}
catch ( BirtException e )
{
throw DataException.wrap(e);
}
}
}
/** Executes the onFetch script associated with the data source */
public void onFetch() throws DataException
{
if ( getEventHandler() != null )
{
try
{
getEventHandler().handleOnFetch( this, getDataRow() );
}
catch ( BirtException e )
{
throw DataException.wrap(e);
}
}
}
/**
* Performs custom action to close a data set.
* <p>
* beforeClose and afterClose event scripts are NOT run in this method */
public void close() throws DataException
{
isOpen = false;
}
/**
* Binds the row object to an odi result set. Exising binding
* is replaced.
* @param resultSet Odi result iterator to bind to
* @param allowUpdate If true, update to current row's column values are allowed
*/
public void setResultSet( IResultIterator resultSet, boolean allowUpdate )
{
assert resultSet != null;
this.resultSet = resultSet;
resultObj = null;
this.allowUpdateRowData = allowUpdate;
this.rowMetaData = null;
}
/**
* Binds the row object to a IResultObject. Existing bindings
* is replaced
* @param resultObj Result object to bind to.
* @param allowUpdate If true, update to current row's column values are allowed
*/
public void setRowObject( IResultObject resultObj, boolean allowUpdate )
{
assert resultObj != null;
this.resultObj = resultObj;
resultSet = null;
this.allowUpdateRowData = allowUpdate;
this.rowMetaData = null;
}
/**
* Indicates the index of the current result row
*/
public void setCurrentRowIndex( int currentRowIndex )
{
this.currentRowIndex = currentRowIndex;
}
/**
* Get result object from IResultObject or IResultSetIterator
* @return current result object; can be null
*/
public IResultObject getCurrentRow( )
{
if ( !isOpen )
return null;
IResultObject resultObject;
if ( resultSet != null )
{
try
{
resultObject = resultSet.getCurrentResult( );
}
catch ( DataException e )
{
resultObject = null;
}
}
else
{
resultObject = resultObj;
}
return resultObject;
}
/**
* Gets value of row[0]
*/
public int getCurrentRowIndex( ) throws DataException
{
int rowID;
if ( resultSet != null )
rowID = resultSet.getCurrentResultIndex( );
else
rowID = this.currentRowIndex;
return rowID;
}
public boolean allowUpdateRowData()
{
return this.allowUpdateRowData;
}
}
| true | true | protected DataSetRuntime( IBaseDataSetDesign dataSetDesign, PreparedQuery.Executor queryExecutor)
{
this.dataSetDesign = dataSetDesign;
this.queryExecutor = queryExecutor;
isOpen = true;
eventHandler = dataSetDesign.getEventHandler();
/*
* TODO: TEMPORARY the follow code is temporary. It will be removed once Engine takes over
* script execution from DtE
*/
if ( eventHandler == null )
{
if ( dataSetDesign instanceof IScriptDataSetDesign )
eventHandler = new ScriptDataSetJSEventHandler(
(IScriptDataSetDesign) dataSetDesign );
else if ( dataSetDesign instanceof IOdaDataSetDesign)
eventHandler = new DataSetJSEventHandler( dataSetDesign );
}
/*
* END Temporary
*/
}
| protected DataSetRuntime( IBaseDataSetDesign dataSetDesign, PreparedQuery.Executor queryExecutor)
{
this.dataSetDesign = dataSetDesign;
this.queryExecutor = queryExecutor;
isOpen = true;
if ( dataSetDesign != null )
eventHandler = dataSetDesign.getEventHandler();
/*
* TODO: TEMPORARY the follow code is temporary. It will be removed once Engine takes over
* script execution from DtE
*/
if ( eventHandler == null )
{
if ( dataSetDesign instanceof IScriptDataSetDesign )
eventHandler = new ScriptDataSetJSEventHandler(
(IScriptDataSetDesign) dataSetDesign );
else if ( dataSetDesign instanceof IOdaDataSetDesign)
eventHandler = new DataSetJSEventHandler( dataSetDesign );
}
/*
* END Temporary
*/
}
|
diff --git a/meshkeeper-api/src/main/java/org/fusesource/meshkeeper/control/ControlServer.java b/meshkeeper-api/src/main/java/org/fusesource/meshkeeper/control/ControlServer.java
index 3cbd15c..fe910eb 100644
--- a/meshkeeper-api/src/main/java/org/fusesource/meshkeeper/control/ControlServer.java
+++ b/meshkeeper-api/src/main/java/org/fusesource/meshkeeper/control/ControlServer.java
@@ -1,202 +1,203 @@
/**************************************************************************************
* Copyright (C) 2009 Progress Software, Inc. All rights reserved. *
* http://fusesource.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the AGPL license *
* a copy of which has been included with this distribution in the license.txt file. *
**************************************************************************************/
package org.fusesource.meshkeeper.control;
import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.fusesource.meshkeeper.distribution.registry.RegistryClient;
import org.fusesource.meshkeeper.distribution.registry.RegistryFactory;
import org.fusesource.meshkeeper.MeshKeeperFactory;
/**
* ControlServer
* <p>
* Description: The control server hosts the servers used to facilitate the
* distributed test system.
*
* </p>
*
* @author cmacnaug
* @version 1.0
*/
public class ControlServer {
Log log = LogFactory.getLog(ControlServer.class);
private static final ControlServiceFactory SERVICE_FACTORY = new ControlServiceFactory();
public static final String DEFAULT_JMS_URI = "activemq:tcp://localhost:4041";
public static final String DEFAULT_REMOTING_URI = "rmiviajms:" + DEFAULT_JMS_URI;
public static final String DEFAULT_REGISTRY_URI = "zk:tcp://localhost:4040";
public static final String DEFAULT_EVENT_URI = "eventviajms:" + DEFAULT_JMS_URI;
public static final String REMOTING_URI_PATH = "/control/remoting-uri";
public static final String EVENTING_URI_PATH = "/control/eventing-uri";
public static final String REPOSITORY_URI_PATH = "/control/repository-uri";
ControlService rmiServer;
ControlService registryServer;
RegistryClient registry;
private String jmsUri = DEFAULT_JMS_URI;
private String registryUri = DEFAULT_REGISTRY_URI;
private String repositoryUri = System.getProperty("meshkeeper.repository.uri");
private String directory = MeshKeeperFactory.getDefaultServerDirectory().getPath();
private Thread shutdownHook;
public void start() throws Exception {
shutdownHook = new Thread("MeshKeeper Control Server Shutdown Hook") {
public void run() {
log.debug("Executing Shutdown Hook for " + ControlServer.this);
try {
ControlServer.this.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
};
//Start the jms server:
log.info("Creating JMS Server at " + jmsUri);
final String SLASH = File.separator;
try {
rmiServer = SERVICE_FACTORY.create(jmsUri);
rmiServer.setDirectory(directory + SLASH + "jms");
rmiServer.start();
log.info("JMS Server started: " + rmiServer.getName());
} catch (Exception e) {
log.error(e);
destroy();
throw new Exception("Error starting JMS Server", e);
}
//Start the registry server:
log.info("Creating Registry Server at " + registryUri);
try {
registryServer = SERVICE_FACTORY.create(registryUri);
registryServer.setDirectory(directory + SLASH + "registry");
registryServer.start();
log.info("Registry Server started: " + registryServer.getName() + " uri: " + registryServer.getServiceUri());
} catch (Exception e) {
log.error("Error starting regisry server", e);
destroy();
throw new Exception("Error starting Registry Server", e);
}
if (repositoryUri == null) {
// Just default it to a local directory.. Only really useful in the local test case.
repositoryUri = new File(directory + SLASH + "repository").toURI().toString();
}
//Connect to the registry and publish service connection info:
try {
- registry = new RegistryFactory().create("zk:" + registryUri);
+ log.info("Connecting to registry server at " + registryUri);
+ registry = new RegistryFactory().create(registryServer.getServiceUri());
//Register the control services:
//(note that we delete these first since
//in some instances zoo-keeper doesn't shutdown cleanly and hangs
//on to file handles so that the registry isn't purged:
registry.removeRegistryData(REMOTING_URI_PATH, true);
registry.addRegistryObject(REMOTING_URI_PATH, false, new String("rmiviajms:" + rmiServer.getServiceUri()));
log.info("Registered RMI control server at " + REMOTING_URI_PATH + "=rmiviajms:" + rmiServer.getServiceUri());
registry.removeRegistryData(EVENTING_URI_PATH, true);
registry.addRegistryObject(EVENTING_URI_PATH, false, new String("eventviajms:" + rmiServer.getServiceUri()));
log.info("Registered event server at " + EVENTING_URI_PATH + "=eventviajms:" + rmiServer.getServiceUri());
registry.removeRegistryData(REPOSITORY_URI_PATH, true);
registry.addRegistryObject(REPOSITORY_URI_PATH, false, repositoryUri);
log.info("Registered repository uri at " + REPOSITORY_URI_PATH + "=" + repositoryUri);
} catch (Exception e) {
log.error(e.getMessage(), e);
destroy();
throw new Exception("Error registering control server", e);
}
}
public void destroy() throws Exception {
if (Thread.currentThread() != shutdownHook) {
Runtime.getRuntime().removeShutdownHook(shutdownHook);
}
if (registry != null) {
registry.destroy();
registry = null;
}
log.info("Shutting down registry server");
if (registryServer != null) {
try {
registryServer.destroy();
} finally {
registryServer = null;
}
}
log.info("Shutting down rmi server");
if (rmiServer != null) {
try {
rmiServer.destroy();
} finally {
rmiServer = null;
}
}
synchronized (this) {
notifyAll();
}
}
public void join() throws InterruptedException {
synchronized (this) {
wait();
}
}
public void setRepositoryUri(String repositoryProvider) {
this.repositoryUri = repositoryProvider;
}
public String getRepositoryUri() {
return repositoryUri;
}
public String getJmsUri() {
return jmsUri;
}
public void setJmsUri(String jmsProvider) {
this.jmsUri = jmsProvider;
}
public String getRegistryUri() {
return registryUri;
}
public void setRegistryUri(String registryProvider) {
this.registryUri = registryProvider;
}
public void setDirectory(String directory) {
this.directory = directory;
}
public String getDirectory() {
return directory;
}
}
| true | true | public void start() throws Exception {
shutdownHook = new Thread("MeshKeeper Control Server Shutdown Hook") {
public void run() {
log.debug("Executing Shutdown Hook for " + ControlServer.this);
try {
ControlServer.this.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
};
//Start the jms server:
log.info("Creating JMS Server at " + jmsUri);
final String SLASH = File.separator;
try {
rmiServer = SERVICE_FACTORY.create(jmsUri);
rmiServer.setDirectory(directory + SLASH + "jms");
rmiServer.start();
log.info("JMS Server started: " + rmiServer.getName());
} catch (Exception e) {
log.error(e);
destroy();
throw new Exception("Error starting JMS Server", e);
}
//Start the registry server:
log.info("Creating Registry Server at " + registryUri);
try {
registryServer = SERVICE_FACTORY.create(registryUri);
registryServer.setDirectory(directory + SLASH + "registry");
registryServer.start();
log.info("Registry Server started: " + registryServer.getName() + " uri: " + registryServer.getServiceUri());
} catch (Exception e) {
log.error("Error starting regisry server", e);
destroy();
throw new Exception("Error starting Registry Server", e);
}
if (repositoryUri == null) {
// Just default it to a local directory.. Only really useful in the local test case.
repositoryUri = new File(directory + SLASH + "repository").toURI().toString();
}
//Connect to the registry and publish service connection info:
try {
registry = new RegistryFactory().create("zk:" + registryUri);
//Register the control services:
//(note that we delete these first since
//in some instances zoo-keeper doesn't shutdown cleanly and hangs
//on to file handles so that the registry isn't purged:
registry.removeRegistryData(REMOTING_URI_PATH, true);
registry.addRegistryObject(REMOTING_URI_PATH, false, new String("rmiviajms:" + rmiServer.getServiceUri()));
log.info("Registered RMI control server at " + REMOTING_URI_PATH + "=rmiviajms:" + rmiServer.getServiceUri());
registry.removeRegistryData(EVENTING_URI_PATH, true);
registry.addRegistryObject(EVENTING_URI_PATH, false, new String("eventviajms:" + rmiServer.getServiceUri()));
log.info("Registered event server at " + EVENTING_URI_PATH + "=eventviajms:" + rmiServer.getServiceUri());
registry.removeRegistryData(REPOSITORY_URI_PATH, true);
registry.addRegistryObject(REPOSITORY_URI_PATH, false, repositoryUri);
log.info("Registered repository uri at " + REPOSITORY_URI_PATH + "=" + repositoryUri);
} catch (Exception e) {
log.error(e.getMessage(), e);
destroy();
throw new Exception("Error registering control server", e);
}
}
| public void start() throws Exception {
shutdownHook = new Thread("MeshKeeper Control Server Shutdown Hook") {
public void run() {
log.debug("Executing Shutdown Hook for " + ControlServer.this);
try {
ControlServer.this.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
};
//Start the jms server:
log.info("Creating JMS Server at " + jmsUri);
final String SLASH = File.separator;
try {
rmiServer = SERVICE_FACTORY.create(jmsUri);
rmiServer.setDirectory(directory + SLASH + "jms");
rmiServer.start();
log.info("JMS Server started: " + rmiServer.getName());
} catch (Exception e) {
log.error(e);
destroy();
throw new Exception("Error starting JMS Server", e);
}
//Start the registry server:
log.info("Creating Registry Server at " + registryUri);
try {
registryServer = SERVICE_FACTORY.create(registryUri);
registryServer.setDirectory(directory + SLASH + "registry");
registryServer.start();
log.info("Registry Server started: " + registryServer.getName() + " uri: " + registryServer.getServiceUri());
} catch (Exception e) {
log.error("Error starting regisry server", e);
destroy();
throw new Exception("Error starting Registry Server", e);
}
if (repositoryUri == null) {
// Just default it to a local directory.. Only really useful in the local test case.
repositoryUri = new File(directory + SLASH + "repository").toURI().toString();
}
//Connect to the registry and publish service connection info:
try {
log.info("Connecting to registry server at " + registryUri);
registry = new RegistryFactory().create(registryServer.getServiceUri());
//Register the control services:
//(note that we delete these first since
//in some instances zoo-keeper doesn't shutdown cleanly and hangs
//on to file handles so that the registry isn't purged:
registry.removeRegistryData(REMOTING_URI_PATH, true);
registry.addRegistryObject(REMOTING_URI_PATH, false, new String("rmiviajms:" + rmiServer.getServiceUri()));
log.info("Registered RMI control server at " + REMOTING_URI_PATH + "=rmiviajms:" + rmiServer.getServiceUri());
registry.removeRegistryData(EVENTING_URI_PATH, true);
registry.addRegistryObject(EVENTING_URI_PATH, false, new String("eventviajms:" + rmiServer.getServiceUri()));
log.info("Registered event server at " + EVENTING_URI_PATH + "=eventviajms:" + rmiServer.getServiceUri());
registry.removeRegistryData(REPOSITORY_URI_PATH, true);
registry.addRegistryObject(REPOSITORY_URI_PATH, false, repositoryUri);
log.info("Registered repository uri at " + REPOSITORY_URI_PATH + "=" + repositoryUri);
} catch (Exception e) {
log.error(e.getMessage(), e);
destroy();
throw new Exception("Error registering control server", e);
}
}
|
diff --git a/src/org/openid4java/discovery/xrds/XrdsParserImpl.java b/src/org/openid4java/discovery/xrds/XrdsParserImpl.java
index b39a48c..1be41fb 100644
--- a/src/org/openid4java/discovery/xrds/XrdsParserImpl.java
+++ b/src/org/openid4java/discovery/xrds/XrdsParserImpl.java
@@ -1,208 +1,206 @@
package org.openid4java.discovery.xrds;
import org.openid4java.discovery.Discovery;
import org.openid4java.discovery.DiscoveryException;
import org.openid4java.OpenIDException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.xml.parsers.*;
import java.util.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
/**
* @author jbufu
*/
public class XrdsParserImpl implements XrdsParser
{
private static final Log _log = LogFactory.getLog(XrdsParserImpl.class);
private static final boolean DEBUG = _log.isDebugEnabled();
private static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
private static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
private static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
private static final String XRDS_SCHEMA = "xrds.xsd";
private static final String XRD_SCHEMA = "xrd.xsd";
private static final String XRD_NS = "xri://$xrd*($v*2.0)";
private static final String XRD_ELEM_XRD = "XRD";
private static final String XRD_ELEM_TYPE = "Type";
private static final String XRD_ELEM_URI = "URI";
private static final String XRD_ELEM_LOCALID = "LocalID";
private static final String XRD_ELEM_CANONICALID = "CanonicalID";
private static final String XRD_ATTR_PRIORITY = "priority";
public List parseXrds(String input, Set targetTypes) throws DiscoveryException
{
if (DEBUG)
_log.debug("Parsing XRDS input for service types: " + Arrays.toString(targetTypes.toArray()));
Document document = parseXmlInput(input);
NodeList XRDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_XRD);
Node lastXRD;
if (XRDs.getLength() < 1 || (lastXRD = XRDs.item(XRDs.getLength() - 1)) == null)
throw new DiscoveryException("No XRD elements found.");
// get the canonical ID, if any (needed for XRIs)
String canonicalId = null;
Node canonicalIdNode;
NodeList canonicalIDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_CANONICALID);
for (int i = 0; i < canonicalIDs.getLength(); i++) {
canonicalIdNode = canonicalIDs.item(i);
if (canonicalIdNode.getParentNode() != lastXRD) continue;
if (canonicalId != null)
throw new DiscoveryException("More than one Canonical ID found.");
canonicalId = canonicalIdNode.getFirstChild() != null && canonicalIdNode.getFirstChild().getNodeType() == Node.TEXT_NODE ?
canonicalIdNode.getFirstChild().getNodeValue() : null;
}
// extract the services that match the specified target types
NodeList types = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_TYPE);
Map serviceTypes = new HashMap();
Node typeNode, serviceNode;
for (int i = 0; i < types.getLength(); i++) {
typeNode = types.item(i);
String type = typeNode != null && typeNode.getFirstChild() != null && typeNode.getFirstChild().getNodeType() == Node.TEXT_NODE ?
typeNode.getFirstChild().getNodeValue() : null;
if (type == null || !targetTypes.contains(type)) continue;
serviceNode = typeNode.getParentNode();
if (serviceNode.getParentNode() != lastXRD) continue;
addServiceType(serviceTypes, serviceNode, type);
}
if (DEBUG)
_log.debug("Found " + serviceTypes.size() + " services for the requested types.");
// extract local IDs
NodeList localIDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_LOCALID);
Map serviceLocalIDs = new HashMap();
Node localIdNode;
for (int i = 0; i < localIDs.getLength(); i++) {
localIdNode = localIDs.item(i);
if (localIdNode == null || !serviceTypes.containsKey(localIdNode.getParentNode())) continue;
String localId = localIdNode.getFirstChild() != null && localIdNode.getFirstChild().getNodeType() == Node.TEXT_NODE ?
localIdNode.getFirstChild().getNodeValue() : null;
serviceLocalIDs.put(localIdNode.getParentNode(), localId);
}
// build XrdsServiceEndpoints for all URIs in the found services
List result = new ArrayList();
NodeList uris = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_URI);
Node uriNode;
for (int i = 0; i < uris.getLength(); i++) {
uriNode = uris.item(i);
if (uriNode == null || !serviceTypes.containsKey(uriNode.getParentNode())) continue;
String uri = uriNode.getFirstChild() != null && uriNode.getFirstChild().getNodeType() == Node.TEXT_NODE ?
uriNode.getFirstChild().getNodeValue() : null;
serviceNode = uriNode.getParentNode();
Set typeSet = (Set) serviceTypes.get(serviceNode);
- localIdNode = (Node) serviceLocalIDs.get(serviceNode);
- String localId = localIdNode != null && localIdNode.getFirstChild() != null && localIdNode.getFirstChild().getNodeType() == Node.TEXT_NODE ?
- localIdNode.getFirstChild().getNodeValue() : null;
+ String localId = (String) serviceLocalIDs.get(serviceNode);
XrdsServiceEndpoint endpoint = new XrdsServiceEndpoint(uri, typeSet, getPriority(serviceNode), getPriority(uriNode), localId, canonicalId);
if (DEBUG)
_log.debug("Discovered endpoint: \n" + endpoint);
result.add(endpoint);
}
Collections.sort(result);
return result;
}
private int getPriority(Node node)
{
if (node.hasAttributes())
{
Node priority = node.getAttributes().getNamedItem(XRD_ATTR_PRIORITY);
if (priority != null)
return Integer.parseInt(priority.getNodeValue());
else
return XrdsServiceEndpoint.LOWEST_PRIORITY;
}
return 0;
}
private Document parseXmlInput(String input) throws DiscoveryException
{
if (input == null)
throw new DiscoveryException("Cannot read XML message",
OpenIDException.XRDS_DOWNLOAD_ERROR);
if (DEBUG)
_log.debug("Parsing XRDS input: " + input);
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(true);
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
dbf.setAttribute(JAXP_SCHEMA_SOURCE, new Object[] {
Discovery.class.getResourceAsStream(XRD_SCHEMA),
Discovery.class.getResourceAsStream(XRDS_SCHEMA),
});
DocumentBuilder builder = dbf.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
public void error(SAXParseException exception) throws SAXException {
throw exception;
}
public void fatalError(SAXParseException exception) throws SAXException {
throw exception;
}
public void warning(SAXParseException exception) throws SAXException {
throw exception;
}
});
return builder.parse(new ByteArrayInputStream(input.getBytes()));
}
catch (ParserConfigurationException e)
{
throw new DiscoveryException("Parser configuration error",
OpenIDException.XRDS_PARSING_ERROR, e);
}
catch (SAXException e)
{
throw new DiscoveryException("Error parsing XML document",
OpenIDException.XRDS_PARSING_ERROR, e);
}
catch (IOException e)
{
throw new DiscoveryException("Error reading XRDS document",
OpenIDException.XRDS_DOWNLOAD_ERROR, e);
}
}
private void addServiceType(Map serviceTypes, Node serviceNode, String type)
{
Set types = (Set) serviceTypes.get(serviceNode);
if (types == null)
{
types = new HashSet();
serviceTypes.put(serviceNode, types);
}
types.add(type);
}
}
| true | true | public List parseXrds(String input, Set targetTypes) throws DiscoveryException
{
if (DEBUG)
_log.debug("Parsing XRDS input for service types: " + Arrays.toString(targetTypes.toArray()));
Document document = parseXmlInput(input);
NodeList XRDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_XRD);
Node lastXRD;
if (XRDs.getLength() < 1 || (lastXRD = XRDs.item(XRDs.getLength() - 1)) == null)
throw new DiscoveryException("No XRD elements found.");
// get the canonical ID, if any (needed for XRIs)
String canonicalId = null;
Node canonicalIdNode;
NodeList canonicalIDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_CANONICALID);
for (int i = 0; i < canonicalIDs.getLength(); i++) {
canonicalIdNode = canonicalIDs.item(i);
if (canonicalIdNode.getParentNode() != lastXRD) continue;
if (canonicalId != null)
throw new DiscoveryException("More than one Canonical ID found.");
canonicalId = canonicalIdNode.getFirstChild() != null && canonicalIdNode.getFirstChild().getNodeType() == Node.TEXT_NODE ?
canonicalIdNode.getFirstChild().getNodeValue() : null;
}
// extract the services that match the specified target types
NodeList types = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_TYPE);
Map serviceTypes = new HashMap();
Node typeNode, serviceNode;
for (int i = 0; i < types.getLength(); i++) {
typeNode = types.item(i);
String type = typeNode != null && typeNode.getFirstChild() != null && typeNode.getFirstChild().getNodeType() == Node.TEXT_NODE ?
typeNode.getFirstChild().getNodeValue() : null;
if (type == null || !targetTypes.contains(type)) continue;
serviceNode = typeNode.getParentNode();
if (serviceNode.getParentNode() != lastXRD) continue;
addServiceType(serviceTypes, serviceNode, type);
}
if (DEBUG)
_log.debug("Found " + serviceTypes.size() + " services for the requested types.");
// extract local IDs
NodeList localIDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_LOCALID);
Map serviceLocalIDs = new HashMap();
Node localIdNode;
for (int i = 0; i < localIDs.getLength(); i++) {
localIdNode = localIDs.item(i);
if (localIdNode == null || !serviceTypes.containsKey(localIdNode.getParentNode())) continue;
String localId = localIdNode.getFirstChild() != null && localIdNode.getFirstChild().getNodeType() == Node.TEXT_NODE ?
localIdNode.getFirstChild().getNodeValue() : null;
serviceLocalIDs.put(localIdNode.getParentNode(), localId);
}
// build XrdsServiceEndpoints for all URIs in the found services
List result = new ArrayList();
NodeList uris = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_URI);
Node uriNode;
for (int i = 0; i < uris.getLength(); i++) {
uriNode = uris.item(i);
if (uriNode == null || !serviceTypes.containsKey(uriNode.getParentNode())) continue;
String uri = uriNode.getFirstChild() != null && uriNode.getFirstChild().getNodeType() == Node.TEXT_NODE ?
uriNode.getFirstChild().getNodeValue() : null;
serviceNode = uriNode.getParentNode();
Set typeSet = (Set) serviceTypes.get(serviceNode);
localIdNode = (Node) serviceLocalIDs.get(serviceNode);
String localId = localIdNode != null && localIdNode.getFirstChild() != null && localIdNode.getFirstChild().getNodeType() == Node.TEXT_NODE ?
localIdNode.getFirstChild().getNodeValue() : null;
XrdsServiceEndpoint endpoint = new XrdsServiceEndpoint(uri, typeSet, getPriority(serviceNode), getPriority(uriNode), localId, canonicalId);
if (DEBUG)
_log.debug("Discovered endpoint: \n" + endpoint);
result.add(endpoint);
}
Collections.sort(result);
return result;
}
| public List parseXrds(String input, Set targetTypes) throws DiscoveryException
{
if (DEBUG)
_log.debug("Parsing XRDS input for service types: " + Arrays.toString(targetTypes.toArray()));
Document document = parseXmlInput(input);
NodeList XRDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_XRD);
Node lastXRD;
if (XRDs.getLength() < 1 || (lastXRD = XRDs.item(XRDs.getLength() - 1)) == null)
throw new DiscoveryException("No XRD elements found.");
// get the canonical ID, if any (needed for XRIs)
String canonicalId = null;
Node canonicalIdNode;
NodeList canonicalIDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_CANONICALID);
for (int i = 0; i < canonicalIDs.getLength(); i++) {
canonicalIdNode = canonicalIDs.item(i);
if (canonicalIdNode.getParentNode() != lastXRD) continue;
if (canonicalId != null)
throw new DiscoveryException("More than one Canonical ID found.");
canonicalId = canonicalIdNode.getFirstChild() != null && canonicalIdNode.getFirstChild().getNodeType() == Node.TEXT_NODE ?
canonicalIdNode.getFirstChild().getNodeValue() : null;
}
// extract the services that match the specified target types
NodeList types = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_TYPE);
Map serviceTypes = new HashMap();
Node typeNode, serviceNode;
for (int i = 0; i < types.getLength(); i++) {
typeNode = types.item(i);
String type = typeNode != null && typeNode.getFirstChild() != null && typeNode.getFirstChild().getNodeType() == Node.TEXT_NODE ?
typeNode.getFirstChild().getNodeValue() : null;
if (type == null || !targetTypes.contains(type)) continue;
serviceNode = typeNode.getParentNode();
if (serviceNode.getParentNode() != lastXRD) continue;
addServiceType(serviceTypes, serviceNode, type);
}
if (DEBUG)
_log.debug("Found " + serviceTypes.size() + " services for the requested types.");
// extract local IDs
NodeList localIDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_LOCALID);
Map serviceLocalIDs = new HashMap();
Node localIdNode;
for (int i = 0; i < localIDs.getLength(); i++) {
localIdNode = localIDs.item(i);
if (localIdNode == null || !serviceTypes.containsKey(localIdNode.getParentNode())) continue;
String localId = localIdNode.getFirstChild() != null && localIdNode.getFirstChild().getNodeType() == Node.TEXT_NODE ?
localIdNode.getFirstChild().getNodeValue() : null;
serviceLocalIDs.put(localIdNode.getParentNode(), localId);
}
// build XrdsServiceEndpoints for all URIs in the found services
List result = new ArrayList();
NodeList uris = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_URI);
Node uriNode;
for (int i = 0; i < uris.getLength(); i++) {
uriNode = uris.item(i);
if (uriNode == null || !serviceTypes.containsKey(uriNode.getParentNode())) continue;
String uri = uriNode.getFirstChild() != null && uriNode.getFirstChild().getNodeType() == Node.TEXT_NODE ?
uriNode.getFirstChild().getNodeValue() : null;
serviceNode = uriNode.getParentNode();
Set typeSet = (Set) serviceTypes.get(serviceNode);
String localId = (String) serviceLocalIDs.get(serviceNode);
XrdsServiceEndpoint endpoint = new XrdsServiceEndpoint(uri, typeSet, getPriority(serviceNode), getPriority(uriNode), localId, canonicalId);
if (DEBUG)
_log.debug("Discovered endpoint: \n" + endpoint);
result.add(endpoint);
}
Collections.sort(result);
return result;
}
|
diff --git a/bundles/net.i2cat.luminis.ROADM.repository/src/main/java/net/i2cat/luminis/ROADM/repository/ROADMBootstrapper.java b/bundles/net.i2cat.luminis.ROADM.repository/src/main/java/net/i2cat/luminis/ROADM/repository/ROADMBootstrapper.java
index 181f07a65..6dc734872 100644
--- a/bundles/net.i2cat.luminis.ROADM.repository/src/main/java/net/i2cat/luminis/ROADM/repository/ROADMBootstrapper.java
+++ b/bundles/net.i2cat.luminis.ROADM.repository/src/main/java/net/i2cat/luminis/ROADM/repository/ROADMBootstrapper.java
@@ -1,66 +1,68 @@
package net.i2cat.luminis.ROADM.repository;
import net.i2cat.mantychore.model.ManagedElement;
import net.i2cat.mantychore.model.opticalSwitch.dwdm.proteus.ProteusOpticalSwitch;
import net.i2cat.nexus.resources.IResource;
import net.i2cat.nexus.resources.IResourceBootstrapper;
import net.i2cat.nexus.resources.ResourceException;
import net.i2cat.nexus.resources.capability.AbstractCapability;
import net.i2cat.nexus.resources.capability.ICapability;
import net.i2cat.nexus.resources.command.Response;
import net.i2cat.nexus.resources.command.Response.Status;
import net.i2cat.nexus.resources.queue.QueueConstants;
import net.i2cat.nexus.resources.queue.QueueResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ROADMBootstrapper implements IResourceBootstrapper {
Log log = LogFactory.getLog(ROADMBootstrapper.class);
private ManagedElement oldModel;
@Override
public void bootstrap(IResource resource) throws ResourceException {
log.info("Loading bootstrap to start resource..");
oldModel = resource.getModel();
resource.setModel(new ProteusOpticalSwitch()); // TODO LUMINIS WORK WITH OPTICAL SWITCHES OR WITH PROTEUS OPTICAL SWITCHES
// set name in model
// FIXME do this in profile.initModel
((ProteusOpticalSwitch) resource.getModel()).setName(resource.getResourceDescriptor().getInformation().getName());
log.debug("Executing capabilities startup...");
ICapability queueCapab = null;
for (ICapability capab : resource.getCapabilities()) {
if (capab instanceof AbstractCapability) {
if (capab.getCapabilityInformation().getType().equalsIgnoreCase("queue")) {
queueCapab = capab;
} else {
Response response = ((AbstractCapability) capab).sendRefreshActions();
if (!response.getStatus().equals(Status.OK)) {
- throw new ResourceException();
+ throw new ResourceException(
+ "Failed to send refreshActions of " + capab.getCapabilityInformation().getType() + " capability. " + response
+ .getErrors().toString());
}
}
}
}
QueueResponse response = (QueueResponse) queueCapab.sendMessage(QueueConstants.EXECUTE, resource.getModel());
if (!response.isOk()) {
// TODO IMPROVE ERROR REPORTING
throw new ResourceException("Error during capabilities startup. Failed to execute startUp actions.");
}
if (resource.getProfile() != null) {
log.debug("Executing initModel from profile...");
resource.getProfile().initModel(resource.getModel());
}
}
@Override
public void revertBootstrap(IResource resource) throws ResourceException {
resource.setModel(oldModel);
}
}
| true | true | public void bootstrap(IResource resource) throws ResourceException {
log.info("Loading bootstrap to start resource..");
oldModel = resource.getModel();
resource.setModel(new ProteusOpticalSwitch()); // TODO LUMINIS WORK WITH OPTICAL SWITCHES OR WITH PROTEUS OPTICAL SWITCHES
// set name in model
// FIXME do this in profile.initModel
((ProteusOpticalSwitch) resource.getModel()).setName(resource.getResourceDescriptor().getInformation().getName());
log.debug("Executing capabilities startup...");
ICapability queueCapab = null;
for (ICapability capab : resource.getCapabilities()) {
if (capab instanceof AbstractCapability) {
if (capab.getCapabilityInformation().getType().equalsIgnoreCase("queue")) {
queueCapab = capab;
} else {
Response response = ((AbstractCapability) capab).sendRefreshActions();
if (!response.getStatus().equals(Status.OK)) {
throw new ResourceException();
}
}
}
}
QueueResponse response = (QueueResponse) queueCapab.sendMessage(QueueConstants.EXECUTE, resource.getModel());
if (!response.isOk()) {
// TODO IMPROVE ERROR REPORTING
throw new ResourceException("Error during capabilities startup. Failed to execute startUp actions.");
}
if (resource.getProfile() != null) {
log.debug("Executing initModel from profile...");
resource.getProfile().initModel(resource.getModel());
}
}
| public void bootstrap(IResource resource) throws ResourceException {
log.info("Loading bootstrap to start resource..");
oldModel = resource.getModel();
resource.setModel(new ProteusOpticalSwitch()); // TODO LUMINIS WORK WITH OPTICAL SWITCHES OR WITH PROTEUS OPTICAL SWITCHES
// set name in model
// FIXME do this in profile.initModel
((ProteusOpticalSwitch) resource.getModel()).setName(resource.getResourceDescriptor().getInformation().getName());
log.debug("Executing capabilities startup...");
ICapability queueCapab = null;
for (ICapability capab : resource.getCapabilities()) {
if (capab instanceof AbstractCapability) {
if (capab.getCapabilityInformation().getType().equalsIgnoreCase("queue")) {
queueCapab = capab;
} else {
Response response = ((AbstractCapability) capab).sendRefreshActions();
if (!response.getStatus().equals(Status.OK)) {
throw new ResourceException(
"Failed to send refreshActions of " + capab.getCapabilityInformation().getType() + " capability. " + response
.getErrors().toString());
}
}
}
}
QueueResponse response = (QueueResponse) queueCapab.sendMessage(QueueConstants.EXECUTE, resource.getModel());
if (!response.isOk()) {
// TODO IMPROVE ERROR REPORTING
throw new ResourceException("Error during capabilities startup. Failed to execute startUp actions.");
}
if (resource.getProfile() != null) {
log.debug("Executing initModel from profile...");
resource.getProfile().initModel(resource.getModel());
}
}
|
diff --git a/test/unit/org/apache/cassandra/cli/CliTest.java b/test/unit/org/apache/cassandra/cli/CliTest.java
index b6b08ac3..d1339644 100644
--- a/test/unit/org/apache/cassandra/cli/CliTest.java
+++ b/test/unit/org/apache/cassandra/cli/CliTest.java
@@ -1,210 +1,210 @@
/**
* 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.cassandra.cli;
import org.apache.cassandra.CleanupHelper;
import org.apache.cassandra.config.ConfigurationException;
import org.apache.cassandra.service.EmbeddedCassandraService;
import org.apache.thrift.transport.TTransportException;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CliTest extends CleanupHelper
{
// please add new statements here so they could be auto-runned by this test.
private String[] statements = {
"use TestKeySpace;",
"create column family CF1 with comparator=UTF8Type and column_metadata=[{ column_name:world, validation_class:IntegerType, index_type:0, index_name:IdxName }, { column_name:world2, validation_class:LongType, index_type:KEYS, index_name:LongIdxName}];",
"set CF1[hello][world] = 123848374878933948398384;",
"get CF1[hello][world];",
"set CF1[hello][world2] = 15;",
"get CF1 where world2 = long(15);",
"get cF1 where world2 = long(15);",
"get Cf1 where world2 = long(15);",
"set CF1['hello'][time_spent_uuid] = timeuuid(a8098c1a-f86e-11da-bd1a-00112444be1e);",
"create column family CF2 with comparator=IntegerType;",
"set CF2['key'][98349387493847748398334] = 'some text';",
"get CF2['key'][98349387493847748398334];",
"set CF2['key'][98349387493] = 'some text other';",
"get CF2['key'][98349387493];",
"create column family CF3 with comparator=UTF8Type and column_metadata=[{column_name:'big world', validation_class:LongType}];",
"set CF3['hello']['big world'] = 3748;",
"get CF3['hello']['big world'];",
"list CF3;",
"list CF3[:];",
"list CF3[h:];",
"list CF3 limit 10;",
"list CF3[h:] limit 10;",
"create column family CF4 with comparator=IntegerType and column_metadata=[{column_name:9999, validation_class:LongType}];",
"set CF4['hello'][9999] = 1234;",
"get CF4['hello'][9999];",
"get CF4['hello'][9999] as Long;",
"get CF4['hello'][9999] as Bytes;",
"set CF4['hello'][9999] = Long(1234);",
"get CF4['hello'][9999];",
"get CF4['hello'][9999] as Long;",
"del CF4['hello'][9999];",
"get CF4['hello'][9999];",
"create column family SCF1 with column_type=Super and comparator=IntegerType and subcomparator=LongType and column_metadata=[{column_name:9999, validation_class:LongType}];",
"set SCF1['hello'][1][9999] = 1234;",
"get SCF1['hello'][1][9999];",
"get SCF1['hello'][1][9999] as Long;",
"get SCF1['hello'][1][9999] as Bytes;",
"set SCF1['hello'][1][9999] = Long(1234);",
"get SCF1['hello'][1][9999];",
"get SCF1['hello'][1][9999] as Long;",
"del SCF1['hello'][1][9999];",
"get SCF1['hello'][1][9999];",
"set SCF1['hello'][1][9999] = Long(1234);",
"del SCF1['hello'][9999];",
"get SCF1['hello'][1][9999];",
"truncate CF1;",
"update keyspace TestKeySpace with placement_strategy='org.apache.cassandra.locator.LocalStrategy';",
"update keyspace TestKeySpace with replication_factor=1 and strategy_options=[{DC1:3, DC2:4, DC5:1}];",
"assume CF1 comparator as utf8;",
"assume CF1 sub_comparator as integer;",
"assume CF1 validator as lexicaluuid;",
"assume CF1 keys as timeuuid;",
"create column family CF7;",
"set CF7[1][timeuuid()] = utf8(test1);",
"set CF7[2][lexicaluuid()] = utf8('hello world!');",
"set CF7[3][lexicaluuid(550e8400-e29b-41d4-a716-446655440000)] = utf8(test2);",
"set CF7[key2][timeuuid()] = utf8(test3);",
"assume CF7 comparator as lexicaluuid;",
"assume CF7 keys as utf8;",
"list CF7;",
"get CF7[3];",
"get CF7[3][lexicaluuid(550e8400-e29b-41d4-a716-446655440000)];",
"get sCf1['hello'][1][9999];",
"set sCf1['hello'][1][9999] = 938;",
"set sCf1['hello'][1][9999] = 938 with ttl = 30;",
"set sCf1['hello'][1][9999] = 938 with ttl = 560;",
"list sCf1;",
"del SCF1['hello'][1][9999];",
"assume sCf1 comparator as utf8;",
"create column family CF8;",
"drop column family cF8;",
"create keyspace TESTIN;",
"drop keyspace tesTIN;",
"create column family myCF with column_type='Super' and comparator='UTF8Type' AND subcomparator='UTF8Type';",
"create column family Countries with comparator=UTF8Type and column_metadata=[ {column_name: name, validation_class: UTF8Type} ];",
"set Countries[1][name] = USA;",
"get Countries[1][name];",
"set myCF['key']['scName']['firstname'] = 'John';",
"get myCF['key']['scName']",
"use TestKEYSpace;",
"describe cluster;",
"help describe cluster;",
"show cluster name",
"show api version",
"help help",
"help connect",
"help use",
"help describe KEYSPACE",
"HELP exit",
"help QUIT",
"help show cluster name",
"help show keyspaces",
"help show api version",
"help create keyspace",
"HELP update KEYSPACE",
"HELP CREATE column FAMILY",
"HELP UPDATE COLUMN family",
"HELP drop keyspace",
"help drop column family",
"HELP GET",
"HELP set",
"HELP DEL",
"HELP count",
"HELP list",
"HELP TRUNCATE",
"help assume",
"HELP",
"?"
};
@Test
public void testCli() throws IOException, TTransportException, ConfigurationException
{
new EmbeddedCassandraService().start();
// new error/output streams for CliSessionState
ByteArrayOutputStream errStream = new ByteArrayOutputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// checking if we can connect to the running cassandra node on localhost
CliMain.connect("127.0.0.1", 9170);
// setting new output stream
CliMain.sessionState.setOut(new PrintStream(outStream));
CliMain.sessionState.setErr(new PrintStream(errStream));
// re-creating keyspace for tests
// dropping in case it exists e.g. could be left from previous run
CliMain.processStatement("drop keyspace TestKeySpace;");
CliMain.processStatement("create keyspace TestKeySpace;");
for (String statement : statements)
{
errStream.reset();
// System.out.println("Executing statement: " + statement);
CliMain.processStatement(statement);
String result = outStream.toString();
// System.out.println("Result:\n" + result);
assertEquals(errStream.toString() + " processing " + statement, "", errStream.toString());
if (statement.startsWith("drop ") || statement.startsWith("create ") || statement.startsWith("update "))
{
assert Pattern.compile("(.{8})-(.{4})-(.{4})-(.{4})-(.{12}).*", Pattern.DOTALL).matcher(result).matches() : result;
}
else if (statement.startsWith("set "))
{
- assertEquals(result, "Value inserted.\n");
+ assertEquals(result, "Value inserted." + System.getProperty("line.separator"));
}
else if (statement.startsWith("get "))
{
if (statement.contains("where"))
{
- assertTrue(result.startsWith("-------------------\nRowKey:"));
+ assertTrue(result.startsWith("-------------------" + System.getProperty("line.separator") + "RowKey:"));
}
else
{
assertTrue(result.startsWith("=> (column=") || result.startsWith("Value was not found"));
}
}
else if (statement.startsWith("truncate "))
{
assertTrue(result.contains(" truncated."));
}
else if (statement.startsWith("assume "))
{
assertTrue(result.contains("successfully."));
}
outStream.reset(); // reset stream so we have only output from next statement all the time
errStream.reset(); // no errors to the end user.
}
}
}
| false | true | public void testCli() throws IOException, TTransportException, ConfigurationException
{
new EmbeddedCassandraService().start();
// new error/output streams for CliSessionState
ByteArrayOutputStream errStream = new ByteArrayOutputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// checking if we can connect to the running cassandra node on localhost
CliMain.connect("127.0.0.1", 9170);
// setting new output stream
CliMain.sessionState.setOut(new PrintStream(outStream));
CliMain.sessionState.setErr(new PrintStream(errStream));
// re-creating keyspace for tests
// dropping in case it exists e.g. could be left from previous run
CliMain.processStatement("drop keyspace TestKeySpace;");
CliMain.processStatement("create keyspace TestKeySpace;");
for (String statement : statements)
{
errStream.reset();
// System.out.println("Executing statement: " + statement);
CliMain.processStatement(statement);
String result = outStream.toString();
// System.out.println("Result:\n" + result);
assertEquals(errStream.toString() + " processing " + statement, "", errStream.toString());
if (statement.startsWith("drop ") || statement.startsWith("create ") || statement.startsWith("update "))
{
assert Pattern.compile("(.{8})-(.{4})-(.{4})-(.{4})-(.{12}).*", Pattern.DOTALL).matcher(result).matches() : result;
}
else if (statement.startsWith("set "))
{
assertEquals(result, "Value inserted.\n");
}
else if (statement.startsWith("get "))
{
if (statement.contains("where"))
{
assertTrue(result.startsWith("-------------------\nRowKey:"));
}
else
{
assertTrue(result.startsWith("=> (column=") || result.startsWith("Value was not found"));
}
}
else if (statement.startsWith("truncate "))
{
assertTrue(result.contains(" truncated."));
}
else if (statement.startsWith("assume "))
{
assertTrue(result.contains("successfully."));
}
outStream.reset(); // reset stream so we have only output from next statement all the time
errStream.reset(); // no errors to the end user.
}
}
| public void testCli() throws IOException, TTransportException, ConfigurationException
{
new EmbeddedCassandraService().start();
// new error/output streams for CliSessionState
ByteArrayOutputStream errStream = new ByteArrayOutputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// checking if we can connect to the running cassandra node on localhost
CliMain.connect("127.0.0.1", 9170);
// setting new output stream
CliMain.sessionState.setOut(new PrintStream(outStream));
CliMain.sessionState.setErr(new PrintStream(errStream));
// re-creating keyspace for tests
// dropping in case it exists e.g. could be left from previous run
CliMain.processStatement("drop keyspace TestKeySpace;");
CliMain.processStatement("create keyspace TestKeySpace;");
for (String statement : statements)
{
errStream.reset();
// System.out.println("Executing statement: " + statement);
CliMain.processStatement(statement);
String result = outStream.toString();
// System.out.println("Result:\n" + result);
assertEquals(errStream.toString() + " processing " + statement, "", errStream.toString());
if (statement.startsWith("drop ") || statement.startsWith("create ") || statement.startsWith("update "))
{
assert Pattern.compile("(.{8})-(.{4})-(.{4})-(.{4})-(.{12}).*", Pattern.DOTALL).matcher(result).matches() : result;
}
else if (statement.startsWith("set "))
{
assertEquals(result, "Value inserted." + System.getProperty("line.separator"));
}
else if (statement.startsWith("get "))
{
if (statement.contains("where"))
{
assertTrue(result.startsWith("-------------------" + System.getProperty("line.separator") + "RowKey:"));
}
else
{
assertTrue(result.startsWith("=> (column=") || result.startsWith("Value was not found"));
}
}
else if (statement.startsWith("truncate "))
{
assertTrue(result.contains(" truncated."));
}
else if (statement.startsWith("assume "))
{
assertTrue(result.contains("successfully."));
}
outStream.reset(); // reset stream so we have only output from next statement all the time
errStream.reset(); // no errors to the end user.
}
}
|
diff --git a/common/logisticspipes/renderer/LogisticsHUDRenderer.java b/common/logisticspipes/renderer/LogisticsHUDRenderer.java
index bde32e8a..0138693c 100644
--- a/common/logisticspipes/renderer/LogisticsHUDRenderer.java
+++ b/common/logisticspipes/renderer/LogisticsHUDRenderer.java
@@ -1,505 +1,506 @@
package logisticspipes.renderer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.LinkedList;
import java.util.List;
import logisticspipes.api.IHUDArmor;
import logisticspipes.config.Configs;
import logisticspipes.hud.HUDConfig;
import logisticspipes.interfaces.IHeadUpDisplayBlockRendererProvider;
import logisticspipes.interfaces.IHeadUpDisplayRendererProvider;
import logisticspipes.pipes.basic.CoreRoutedPipe;
import logisticspipes.proxy.MainProxy;
import logisticspipes.proxy.SimpleServiceLocator;
import logisticspipes.routing.IRouter;
import logisticspipes.routing.LaserData;
import logisticspipes.routing.PipeRoutingConnectionType;
import logisticspipes.utils.MathVector;
import logisticspipes.utils.Pair;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.client.GuiIngameForge;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.client.FMLClientHandler;
public class LogisticsHUDRenderer {
private LinkedList<IHeadUpDisplayRendererProvider> list = new LinkedList<IHeadUpDisplayRendererProvider>();
private double lastXPos = 0;
private double lastYPos = 0;
private double lastZPos = 0;
private ArrayList<IHeadUpDisplayBlockRendererProvider> providers = new ArrayList<IHeadUpDisplayBlockRendererProvider>();
private List<LaserData> lasers = new ArrayList<LaserData>();
private static LogisticsHUDRenderer renderer = null;
public void add(IHeadUpDisplayBlockRendererProvider provider) {
IHeadUpDisplayBlockRendererProvider toRemove = null;
for(IHeadUpDisplayBlockRendererProvider listedProvider:providers) {
if(listedProvider.getX() == provider.getX() && listedProvider.getY() == provider.getY() && listedProvider.getZ() == provider.getZ()) {
toRemove = listedProvider;
break;
}
}
if(toRemove != null) {
providers.remove(toRemove);
}
providers.add(provider);
}
public void remove(IHeadUpDisplayBlockRendererProvider provider) {
providers.remove(provider);
}
public void clear() {
providers.clear();
instance().clearList(false);
}
private void clearList(boolean flag) {
if(flag) {
for(IHeadUpDisplayRendererProvider renderer:list) {
renderer.stopWatching();
}
}
list.clear();
}
private void refreshList(double x,double y,double z) {
ArrayList<Pair<Double,IHeadUpDisplayRendererProvider>> newList = new ArrayList<Pair<Double,IHeadUpDisplayRendererProvider>>();
for(IRouter router:SimpleServiceLocator.routerManager.getRouters()) {
if(router == null)
continue;
CoreRoutedPipe pipe = router.getPipe();
if(!(pipe instanceof IHeadUpDisplayRendererProvider)) continue;
if(MainProxy.getDimensionForWorld(pipe.worldObj) == MainProxy.getDimensionForWorld(FMLClientHandler.instance().getClient().theWorld)) {
double dis = Math.hypot(pipe.xCoord - x + 0.5,Math.hypot(pipe.yCoord - y + 0.5, pipe.zCoord - z + 0.5));
if(dis < Configs.LOGISTICS_HUD_RENDER_DISTANCE && dis > 0.75) {
newList.add(new Pair<Double,IHeadUpDisplayRendererProvider>(dis,(IHeadUpDisplayRendererProvider)pipe));
if(!list.contains(pipe)) {
((IHeadUpDisplayRendererProvider)pipe).startWatching();
}
}
}
}
List<IHeadUpDisplayBlockRendererProvider> remove = new ArrayList<IHeadUpDisplayBlockRendererProvider>();
for(IHeadUpDisplayBlockRendererProvider provider:providers) {
if(MainProxy.getDimensionForWorld(provider.getWorld()) == MainProxy.getDimensionForWorld(FMLClientHandler.instance().getClient().theWorld)) {
double dis = Math.hypot(provider.getX() - x + 0.5,Math.hypot(provider.getY() - y + 0.5, provider.getZ() - z + 0.5));
if(dis < Configs.LOGISTICS_HUD_RENDER_DISTANCE && dis > 0.75 && !provider.isInvalid() && provider.isExistent()) {
newList.add(new Pair<Double,IHeadUpDisplayRendererProvider>(dis,provider));
if(!list.contains(provider)) {
provider.startWatching();
}
} else if(provider.isInvalid() || !provider.isExistent()) {
remove.add(provider);
}
}
}
for(IHeadUpDisplayBlockRendererProvider provider:remove) {
providers.remove(provider);
}
if(newList.size() < 1) {
clearList(false);
return;
}
Collections.sort(newList, new Comparator<Pair<Double, IHeadUpDisplayRendererProvider>>() {
@Override
public int compare(
Pair<Double, IHeadUpDisplayRendererProvider> o1,
Pair<Double, IHeadUpDisplayRendererProvider> o2) {
if (o1.getValue1() < o2.getValue1()) {
return -1;
} else if (o1.getValue1() > o2.getValue1()) {
return 1;
} else {
return 0;
}
}
});
for(IHeadUpDisplayRendererProvider part:list) {
boolean contains = false;
for(Pair<Double,IHeadUpDisplayRendererProvider> inpart:newList) {
if(inpart.getValue2().equals(part)) {
contains = true;
break;
}
}
if(!contains) {
part.stopWatching();
}
}
clearList(false);
for (Pair<Double, IHeadUpDisplayRendererProvider> part : newList) {
list.addLast(part.getValue2());
}
}
private boolean playerWearsHUD() {
return FMLClientHandler.instance().getClient().thePlayer != null && FMLClientHandler.instance().getClient().thePlayer.inventory != null && FMLClientHandler.instance().getClient().thePlayer.inventory.armorInventory != null && FMLClientHandler.instance().getClient().thePlayer.inventory.armorInventory[3] != null && FMLClientHandler.instance().getClient().thePlayer.inventory.armorInventory[3].getItem() instanceof IHUDArmor && ((IHUDArmor)FMLClientHandler.instance().getClient().thePlayer.inventory.armorInventory[3].getItem()).isEnabled(FMLClientHandler.instance().getClient().thePlayer.inventory.armorInventory[3]);
}
private boolean displayCross = false;
public void renderPlayerDisplay(long renderTicks) {
if(!displayRenderer()) return;
Minecraft mc = FMLClientHandler.instance().getClient();
if(displayCross) {
ScaledResolution res = new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight);
int width = res.getScaledWidth();
int height = res.getScaledHeight();
if (GuiIngameForge.renderCrosshairs && mc.ingameGUI != null) {
mc.renderEngine.bindTexture("/gui/icons.png");
GL11.glColor4d(0.0D, 0.0D, 0.0D, 1.0D);
GL11.glDisable(GL11.GL_BLEND);
mc.ingameGUI.drawTexturedModalRect(width / 2 - 7, height / 2 - 7, 0, 0, 16, 16);
}
}
}
public void renderWorldRelative(long renderTicks, float partialTick) {
if(!displayRenderer()) return;
Minecraft mc = FMLClientHandler.instance().getClient();
EntityPlayer player = mc.thePlayer;
if(list.size() == 0 || Math.hypot(lastXPos - player.posX,Math.hypot(lastYPos - player.posY, lastZPos - player.posZ)) > 0.5 || (renderTicks % 10 == 0 && (lastXPos != player.posX || lastYPos != player.posY + player.getEyeHeight() || lastZPos != player.posZ)) || renderTicks % 600 == 0) {
refreshList(player.posX,player.posY,player.posZ);
lastXPos = player.posX;
lastYPos = player.posY + player.getEyeHeight();
lastZPos = player.posZ;
}
boolean cursorHandled = false;
displayCross = false;
HUDConfig config = new HUDConfig(FMLClientHandler.instance().getClient().thePlayer.inventory.armorInventory[3]);
IHeadUpDisplayRendererProvider thisIsLast = null;
for(IHeadUpDisplayRendererProvider renderer:list) {
if(renderer.getRenderer() == null) continue;
if(renderer.getRenderer().display(config)) {
GL11.glPushMatrix();
if(!cursorHandled) {
double x = renderer.getX() + 0.5 - player.posX;
double y = renderer.getY() + 0.5 - player.posY;
double z = renderer.getZ() + 0.5 - player.posZ;
if(Math.hypot(x,Math.hypot(y, z)) < 0.75 || (renderer instanceof IHeadUpDisplayBlockRendererProvider && (((IHeadUpDisplayBlockRendererProvider)renderer).isInvalid() || !((IHeadUpDisplayBlockRendererProvider)renderer).isExistent()))) {
refreshList(player.posX,player.posY,player.posZ);
GL11.glPopMatrix();
break;
}
int[] pos = getCursor(renderer);
if(pos.length == 2) {
if(renderer.getRenderer().cursorOnWindow(pos[0], pos[1])) {
renderer.getRenderer().handleCursor(pos[0], pos[1]);
if(FMLClientHandler.instance().getClient().thePlayer.isSneaking()) {
thisIsLast = renderer;
displayCross = true;
}
cursorHandled = true;
}
}
}
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
if(thisIsLast != renderer) {
displayOneView(renderer, config, partialTick);
}
GL11.glPopMatrix();
}
}
if(thisIsLast != null) {
GL11.glPushMatrix();
GL11.glDisable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_DEPTH_TEST);
displayOneView(thisIsLast, config, partialTick);
GL11.glPopMatrix();
}
//Render Laser
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
//GL11.glEnable(GL11.GL_LIGHTING);
for(LaserData data: lasers) {
GL11.glPushMatrix();
double x = data.getPosX() + 0.5 - player.prevPosX - ((player.posX - player.prevPosX) * partialTick);
double y = data.getPosY() + 0.5 - player.prevPosY - ((player.posY - player.prevPosY) * partialTick);
double z = data.getPosZ() + 0.5 - player.prevPosZ - ((player.posZ - player.prevPosZ) * partialTick);
GL11.glTranslatef((float)x, (float)y, (float)z);
switch(data.getDir()) {
case NORTH:
GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F);
break;
case SOUTH:
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
break;
case EAST:
break;
case WEST:
GL11.glRotatef(180.0F, 0.0F, 1.0F, 0.0F);
break;
case UP:
GL11.glRotatef(90.0F, 0.0F, 0.0F, 1.0F);
break;
case DOWN:
GL11.glRotatef(-90.0F, 0.0F, 0.0F, 1.0F);
break;
default:
break;
}
GL11.glScalef(0.01F, 0.01F, 0.01F);
Tessellator tessellator = Tessellator.instance;
for(float i = 0; i < 6 * data.getLength(); i++) {
setColor(i, data.getConnectionType());
float shift = 100f * i / 6f;
float start = 0.0f;
if(data.isStartPipe() && i == 0) {
start = -6.0f;
}
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , 3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, 3.0f);
tessellator.addVertex(19.7f + shift , 3.0f, 3.0f);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , -3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, -3.0f);
tessellator.addVertex(19.7f + shift , -3.0f, -3.0f);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , 3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, 3.0f);
tessellator.addVertex(19.7f + shift , -3.0f, 3.0f);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , -3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, -3.0f);
tessellator.addVertex(19.7f + shift , 3.0f, -3.0f);
tessellator.draw();
}
if(data.isStartPipe()) {
setColor(0, data.getConnectionType());
tessellator.startDrawingQuads();
tessellator.addVertex(-3.0f, 3.0f, 3.0f);
tessellator.addVertex(-3.0f, 3.0f, -3.0f);
tessellator.addVertex(-3.0f, -3.0f, -3.0f);
tessellator.addVertex(-3.0f, -3.0f, 3.0f);
tessellator.draw();
}
if(data.isFinalPipe()) {
setColor(6 * data.getLength() - 1, data.getConnectionType());
tessellator.startDrawingQuads();
tessellator.addVertex(100.0f * data.getLength() + 3f, 3.0f, -3.0f);
tessellator.addVertex(100.0f * data.getLength() + 3f, 3.0f, 3.0f);
tessellator.addVertex(100.0f * data.getLength() + 3f, -3.0f, 3.0f);
tessellator.addVertex(100.0f * data.getLength() + 3f, -3.0f, -3.0f);
tessellator.draw();
}
GL11.glPopMatrix();
}
+ GL11.glEnable(GL11.GL_TEXTURE_2D);
}
private void setColor(float i, EnumSet<PipeRoutingConnectionType> flags) {
GL11.glColor4f(1.0f, 1.0f, 1.0f, 0.5f);
if(!flags.isEmpty()) {
int k=0;
for(int j=0;j<PipeRoutingConnectionType.values.length;j++) {
PipeRoutingConnectionType type = PipeRoutingConnectionType.values[j];
if(flags.contains(type)) {
k++;
}
if(k - 1 == (int) i % flags.size()) {
setColor(type);
}
}
}
}
private void setColor(PipeRoutingConnectionType type) {
switch (type) {
case canRouteTo:
GL11.glColor4f(1.0f, 1.0f, 0.0f, 0.5f);
break;
case canRequestFrom:
GL11.glColor4f(0.0f, 1.0f, 0.0f, 0.5f);
break;
case canPowerFrom:
GL11.glColor4f(0.0f, 0.0f, 1.0f, 0.5f);
break;
default:
}
}
private void displayOneView(IHeadUpDisplayRendererProvider renderer, HUDConfig config, float partialTick) {
Minecraft mc = FMLClientHandler.instance().getClient();
EntityPlayer player = mc.thePlayer;
double x = renderer.getX() + 0.5 - player.prevPosX - ((player.posX - player.prevPosX) * partialTick);
double y = renderer.getY() + 0.5 - player.prevPosY - ((player.posY - player.prevPosY) * partialTick);
double z = renderer.getZ() + 0.5 - player.prevPosZ - ((player.posZ - player.prevPosZ) * partialTick);
GL11.glTranslatef((float)x, (float)y, (float)z);
GL11.glRotatef(90.0F, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(getAngle(z,x) + 90, 0.0F, 0.0F, 1.0F);
GL11.glRotatef((-1)*getAngle(Math.hypot(x,z),y) + 180, 1.0F, 0.0F, 0.0F);
GL11.glTranslatef(0.0F, 0.0F, -0.4F);
GL11.glScalef(0.01F, 0.01F, 1F);
renderer.getRenderer().renderHeadUpDisplay(Math.hypot(x,Math.hypot(y, z)), false, mc, config);
}
private float getAngle(double x, double y) {
return (float) (Math.atan2(x,y) * 360 / (2 * Math.PI));
}
public double up(double input) {
input %= 360.0D;
while(input < 0 && !Double.isNaN(input) && !Double.isInfinite(input)) {
input += 360;
}
return input;
}
private int[] getCursor(IHeadUpDisplayRendererProvider renderer) {
Minecraft mc = FMLClientHandler.instance().getClient();
EntityPlayer player = mc.thePlayer;
MathVector playerView = MathVector.getFromAngles((270 - player.rotationYaw) / 360 * -2 * Math.PI, (player.rotationPitch) / 360 * -2 * Math.PI);
MathVector playerPos = new MathVector();
playerPos.X = player.posX;
playerPos.Y = player.posY;
playerPos.Z = player.posZ;
MathVector panelPos = new MathVector();
panelPos.X = renderer.getX() + 0.5;
panelPos.Y = renderer.getY() + 0.5;
panelPos.Z = renderer.getZ() + 0.5;
MathVector panelView = new MathVector();
panelView.X = playerPos.X - panelPos.X;
panelView.Y = playerPos.Y - panelPos.Y;
panelView.Z = playerPos.Z - panelPos.Z;
panelPos.add(panelView, 0.44D);
double d = panelPos.X * panelView.X + panelPos.Y * panelView.Y + panelPos.Z * panelView.Z;
double c = panelView.X * playerPos.X + panelView.Y * playerPos.Y + panelView.Z * playerPos.Z;
double b = panelView.X * playerView.X + panelView.Y * playerView.Y + panelView.Z * playerView.Z;
double a = (d - c) / b;
MathVector viewPos = new MathVector();
viewPos.X = playerPos.X + a * playerView.X - panelPos.X;
viewPos.Y = playerPos.Y + a * playerView.Y - panelPos.Y;
viewPos.Z = playerPos.Z + a * playerView.Z - panelPos.Z;
MathVector panelScalVector1 = new MathVector();
if(panelView.Y == 0) {
panelScalVector1.X = 0;
panelScalVector1.Y = 1;
panelScalVector1.Z = 0;
} else {
panelScalVector1 = panelView.getOrtogonal(-panelView.X, null, -panelView.Z).makeVectorLength(1.0D);
}
MathVector panelScalVector2 = new MathVector();
if(panelView.Z == 0) {
panelScalVector2.X = 0;
panelScalVector2.Y = 0;
panelScalVector2.Z = 1;
} else {
panelScalVector2 = panelView.getOrtogonal(1.0D, 0.0D, null).makeVectorLength(1.0D);
}
if(panelScalVector1.Y == 0) {
return new int[]{};
}
double cursorY = -viewPos.Y / panelScalVector1.Y;
MathVector restViewPos = viewPos.clone();
restViewPos.X += cursorY*panelScalVector1.X;
restViewPos.Y = 0;
restViewPos.Z += cursorY*panelScalVector1.Z;
double cursorX;
if(panelScalVector2.X == 0) {
cursorX = restViewPos.Z / panelScalVector2.Z;
} else {
cursorX = restViewPos.X / panelScalVector2.X;
}
cursorX *= 50 / 0.47D;
cursorY *= 50 / 0.47D;
if(panelView.Z < 0) {
cursorX *= -1;
}
if(panelView.Y < 0) {
cursorY *= -1;
}
return new int[]{(int) cursorX, (int)cursorY};
}
public boolean displayRenderer() {
if(!displayHUD()) {
if(list.size() != 0) {
clearList(true);
}
}
return displayHUD();
}
private boolean displayHUD() {
return playerWearsHUD() && FMLClientHandler.instance().getClient().currentScreen == null && FMLClientHandler.instance().getClient().gameSettings.thirdPersonView == 0 && !FMLClientHandler.instance().getClient().gameSettings.hideGUI;
}
public void resetLasers() {
lasers.clear();
}
public void setLasers(List<LaserData> newLasers) {
lasers.clear();
lasers.addAll(newLasers);
}
public boolean hasLasers() {
return !lasers.isEmpty();
}
public static LogisticsHUDRenderer instance() {
if(renderer == null) {
renderer = new LogisticsHUDRenderer();
}
return renderer;
}
}
| true | true | public void renderWorldRelative(long renderTicks, float partialTick) {
if(!displayRenderer()) return;
Minecraft mc = FMLClientHandler.instance().getClient();
EntityPlayer player = mc.thePlayer;
if(list.size() == 0 || Math.hypot(lastXPos - player.posX,Math.hypot(lastYPos - player.posY, lastZPos - player.posZ)) > 0.5 || (renderTicks % 10 == 0 && (lastXPos != player.posX || lastYPos != player.posY + player.getEyeHeight() || lastZPos != player.posZ)) || renderTicks % 600 == 0) {
refreshList(player.posX,player.posY,player.posZ);
lastXPos = player.posX;
lastYPos = player.posY + player.getEyeHeight();
lastZPos = player.posZ;
}
boolean cursorHandled = false;
displayCross = false;
HUDConfig config = new HUDConfig(FMLClientHandler.instance().getClient().thePlayer.inventory.armorInventory[3]);
IHeadUpDisplayRendererProvider thisIsLast = null;
for(IHeadUpDisplayRendererProvider renderer:list) {
if(renderer.getRenderer() == null) continue;
if(renderer.getRenderer().display(config)) {
GL11.glPushMatrix();
if(!cursorHandled) {
double x = renderer.getX() + 0.5 - player.posX;
double y = renderer.getY() + 0.5 - player.posY;
double z = renderer.getZ() + 0.5 - player.posZ;
if(Math.hypot(x,Math.hypot(y, z)) < 0.75 || (renderer instanceof IHeadUpDisplayBlockRendererProvider && (((IHeadUpDisplayBlockRendererProvider)renderer).isInvalid() || !((IHeadUpDisplayBlockRendererProvider)renderer).isExistent()))) {
refreshList(player.posX,player.posY,player.posZ);
GL11.glPopMatrix();
break;
}
int[] pos = getCursor(renderer);
if(pos.length == 2) {
if(renderer.getRenderer().cursorOnWindow(pos[0], pos[1])) {
renderer.getRenderer().handleCursor(pos[0], pos[1]);
if(FMLClientHandler.instance().getClient().thePlayer.isSneaking()) {
thisIsLast = renderer;
displayCross = true;
}
cursorHandled = true;
}
}
}
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
if(thisIsLast != renderer) {
displayOneView(renderer, config, partialTick);
}
GL11.glPopMatrix();
}
}
if(thisIsLast != null) {
GL11.glPushMatrix();
GL11.glDisable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_DEPTH_TEST);
displayOneView(thisIsLast, config, partialTick);
GL11.glPopMatrix();
}
//Render Laser
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
//GL11.glEnable(GL11.GL_LIGHTING);
for(LaserData data: lasers) {
GL11.glPushMatrix();
double x = data.getPosX() + 0.5 - player.prevPosX - ((player.posX - player.prevPosX) * partialTick);
double y = data.getPosY() + 0.5 - player.prevPosY - ((player.posY - player.prevPosY) * partialTick);
double z = data.getPosZ() + 0.5 - player.prevPosZ - ((player.posZ - player.prevPosZ) * partialTick);
GL11.glTranslatef((float)x, (float)y, (float)z);
switch(data.getDir()) {
case NORTH:
GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F);
break;
case SOUTH:
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
break;
case EAST:
break;
case WEST:
GL11.glRotatef(180.0F, 0.0F, 1.0F, 0.0F);
break;
case UP:
GL11.glRotatef(90.0F, 0.0F, 0.0F, 1.0F);
break;
case DOWN:
GL11.glRotatef(-90.0F, 0.0F, 0.0F, 1.0F);
break;
default:
break;
}
GL11.glScalef(0.01F, 0.01F, 0.01F);
Tessellator tessellator = Tessellator.instance;
for(float i = 0; i < 6 * data.getLength(); i++) {
setColor(i, data.getConnectionType());
float shift = 100f * i / 6f;
float start = 0.0f;
if(data.isStartPipe() && i == 0) {
start = -6.0f;
}
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , 3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, 3.0f);
tessellator.addVertex(19.7f + shift , 3.0f, 3.0f);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , -3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, -3.0f);
tessellator.addVertex(19.7f + shift , -3.0f, -3.0f);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , 3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, 3.0f);
tessellator.addVertex(19.7f + shift , -3.0f, 3.0f);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , -3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, -3.0f);
tessellator.addVertex(19.7f + shift , 3.0f, -3.0f);
tessellator.draw();
}
if(data.isStartPipe()) {
setColor(0, data.getConnectionType());
tessellator.startDrawingQuads();
tessellator.addVertex(-3.0f, 3.0f, 3.0f);
tessellator.addVertex(-3.0f, 3.0f, -3.0f);
tessellator.addVertex(-3.0f, -3.0f, -3.0f);
tessellator.addVertex(-3.0f, -3.0f, 3.0f);
tessellator.draw();
}
if(data.isFinalPipe()) {
setColor(6 * data.getLength() - 1, data.getConnectionType());
tessellator.startDrawingQuads();
tessellator.addVertex(100.0f * data.getLength() + 3f, 3.0f, -3.0f);
tessellator.addVertex(100.0f * data.getLength() + 3f, 3.0f, 3.0f);
tessellator.addVertex(100.0f * data.getLength() + 3f, -3.0f, 3.0f);
tessellator.addVertex(100.0f * data.getLength() + 3f, -3.0f, -3.0f);
tessellator.draw();
}
GL11.glPopMatrix();
}
}
| public void renderWorldRelative(long renderTicks, float partialTick) {
if(!displayRenderer()) return;
Minecraft mc = FMLClientHandler.instance().getClient();
EntityPlayer player = mc.thePlayer;
if(list.size() == 0 || Math.hypot(lastXPos - player.posX,Math.hypot(lastYPos - player.posY, lastZPos - player.posZ)) > 0.5 || (renderTicks % 10 == 0 && (lastXPos != player.posX || lastYPos != player.posY + player.getEyeHeight() || lastZPos != player.posZ)) || renderTicks % 600 == 0) {
refreshList(player.posX,player.posY,player.posZ);
lastXPos = player.posX;
lastYPos = player.posY + player.getEyeHeight();
lastZPos = player.posZ;
}
boolean cursorHandled = false;
displayCross = false;
HUDConfig config = new HUDConfig(FMLClientHandler.instance().getClient().thePlayer.inventory.armorInventory[3]);
IHeadUpDisplayRendererProvider thisIsLast = null;
for(IHeadUpDisplayRendererProvider renderer:list) {
if(renderer.getRenderer() == null) continue;
if(renderer.getRenderer().display(config)) {
GL11.glPushMatrix();
if(!cursorHandled) {
double x = renderer.getX() + 0.5 - player.posX;
double y = renderer.getY() + 0.5 - player.posY;
double z = renderer.getZ() + 0.5 - player.posZ;
if(Math.hypot(x,Math.hypot(y, z)) < 0.75 || (renderer instanceof IHeadUpDisplayBlockRendererProvider && (((IHeadUpDisplayBlockRendererProvider)renderer).isInvalid() || !((IHeadUpDisplayBlockRendererProvider)renderer).isExistent()))) {
refreshList(player.posX,player.posY,player.posZ);
GL11.glPopMatrix();
break;
}
int[] pos = getCursor(renderer);
if(pos.length == 2) {
if(renderer.getRenderer().cursorOnWindow(pos[0], pos[1])) {
renderer.getRenderer().handleCursor(pos[0], pos[1]);
if(FMLClientHandler.instance().getClient().thePlayer.isSneaking()) {
thisIsLast = renderer;
displayCross = true;
}
cursorHandled = true;
}
}
}
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
if(thisIsLast != renderer) {
displayOneView(renderer, config, partialTick);
}
GL11.glPopMatrix();
}
}
if(thisIsLast != null) {
GL11.glPushMatrix();
GL11.glDisable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_DEPTH_TEST);
displayOneView(thisIsLast, config, partialTick);
GL11.glPopMatrix();
}
//Render Laser
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
//GL11.glEnable(GL11.GL_LIGHTING);
for(LaserData data: lasers) {
GL11.glPushMatrix();
double x = data.getPosX() + 0.5 - player.prevPosX - ((player.posX - player.prevPosX) * partialTick);
double y = data.getPosY() + 0.5 - player.prevPosY - ((player.posY - player.prevPosY) * partialTick);
double z = data.getPosZ() + 0.5 - player.prevPosZ - ((player.posZ - player.prevPosZ) * partialTick);
GL11.glTranslatef((float)x, (float)y, (float)z);
switch(data.getDir()) {
case NORTH:
GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F);
break;
case SOUTH:
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
break;
case EAST:
break;
case WEST:
GL11.glRotatef(180.0F, 0.0F, 1.0F, 0.0F);
break;
case UP:
GL11.glRotatef(90.0F, 0.0F, 0.0F, 1.0F);
break;
case DOWN:
GL11.glRotatef(-90.0F, 0.0F, 0.0F, 1.0F);
break;
default:
break;
}
GL11.glScalef(0.01F, 0.01F, 0.01F);
Tessellator tessellator = Tessellator.instance;
for(float i = 0; i < 6 * data.getLength(); i++) {
setColor(i, data.getConnectionType());
float shift = 100f * i / 6f;
float start = 0.0f;
if(data.isStartPipe() && i == 0) {
start = -6.0f;
}
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , 3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, 3.0f);
tessellator.addVertex(19.7f + shift , 3.0f, 3.0f);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , -3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, -3.0f);
tessellator.addVertex(19.7f + shift , -3.0f, -3.0f);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , 3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, 3.0f);
tessellator.addVertex(19.7f + shift , -3.0f, 3.0f);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , -3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, -3.0f);
tessellator.addVertex(19.7f + shift , 3.0f, -3.0f);
tessellator.draw();
}
if(data.isStartPipe()) {
setColor(0, data.getConnectionType());
tessellator.startDrawingQuads();
tessellator.addVertex(-3.0f, 3.0f, 3.0f);
tessellator.addVertex(-3.0f, 3.0f, -3.0f);
tessellator.addVertex(-3.0f, -3.0f, -3.0f);
tessellator.addVertex(-3.0f, -3.0f, 3.0f);
tessellator.draw();
}
if(data.isFinalPipe()) {
setColor(6 * data.getLength() - 1, data.getConnectionType());
tessellator.startDrawingQuads();
tessellator.addVertex(100.0f * data.getLength() + 3f, 3.0f, -3.0f);
tessellator.addVertex(100.0f * data.getLength() + 3f, 3.0f, 3.0f);
tessellator.addVertex(100.0f * data.getLength() + 3f, -3.0f, 3.0f);
tessellator.addVertex(100.0f * data.getLength() + 3f, -3.0f, -3.0f);
tessellator.draw();
}
GL11.glPopMatrix();
}
GL11.glEnable(GL11.GL_TEXTURE_2D);
}
|
diff --git a/src/org/remus/PipelineStatusView.java b/src/org/remus/PipelineStatusView.java
index 6913716..9298f10 100644
--- a/src/org/remus/PipelineStatusView.java
+++ b/src/org/remus/PipelineStatusView.java
@@ -1,70 +1,70 @@
package org.remus;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import org.mpstore.KeyValuePair;
import org.mpstore.Serializer;
import org.remus.serverNodes.BaseNode;
import org.remus.work.RemusApplet;
public class PipelineStatusView implements BaseNode {
RemusPipeline pipeline;
public PipelineStatusView(RemusPipeline pipeline) {
this.pipeline = pipeline;
}
@Override
public void doDelete(Map params) {
// TODO Auto-generated method stub
}
@Override
public void doGet(String name, Map params, String workerID,
Serializer serial, OutputStream os) throws FileNotFoundException {
if ( name.length() == 0 ) {
for ( RemusApplet applet : pipeline.getMembers() ) {
- for ( KeyValuePair kv : applet.getDataStore().listKeyPairs(applet.getPath() + "/@status", RemusInstance.STATIC_INSTANCE_STR) ) {
+ for ( KeyValuePair kv : applet.getDataStore().listKeyPairs(applet.getPath() + "/@instance", RemusInstance.STATIC_INSTANCE_STR) ) {
Map out = new HashMap();
- out.put( kv.getKey(), kv.getValue() );
+ out.put( kv.getKey() + "/" + applet.getID(), kv.getValue() );
try {
os.write( serial.dumps( out ).getBytes() );
os.write("\n".getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
@Override
public void doPut(String name, String workerID, Serializer serial,
InputStream is, OutputStream os) {
// TODO Auto-generated method stub
}
@Override
public void doSubmit(String name, String workerID, Serializer serial,
InputStream is, OutputStream os) {
// TODO Auto-generated method stub
}
@Override
public BaseNode getChild(String name) {
// TODO Auto-generated method stub
return null;
}
}
| false | true | public void doGet(String name, Map params, String workerID,
Serializer serial, OutputStream os) throws FileNotFoundException {
if ( name.length() == 0 ) {
for ( RemusApplet applet : pipeline.getMembers() ) {
for ( KeyValuePair kv : applet.getDataStore().listKeyPairs(applet.getPath() + "/@status", RemusInstance.STATIC_INSTANCE_STR) ) {
Map out = new HashMap();
out.put( kv.getKey(), kv.getValue() );
try {
os.write( serial.dumps( out ).getBytes() );
os.write("\n".getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
| public void doGet(String name, Map params, String workerID,
Serializer serial, OutputStream os) throws FileNotFoundException {
if ( name.length() == 0 ) {
for ( RemusApplet applet : pipeline.getMembers() ) {
for ( KeyValuePair kv : applet.getDataStore().listKeyPairs(applet.getPath() + "/@instance", RemusInstance.STATIC_INSTANCE_STR) ) {
Map out = new HashMap();
out.put( kv.getKey() + "/" + applet.getID(), kv.getValue() );
try {
os.write( serial.dumps( out ).getBytes() );
os.write("\n".getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
|
diff --git a/SpagoBIProject/src/it/eng/spagobi/commons/presentation/tags/ScriptWizardTag.java b/SpagoBIProject/src/it/eng/spagobi/commons/presentation/tags/ScriptWizardTag.java
index 97a70f088..819d45c88 100644
--- a/SpagoBIProject/src/it/eng/spagobi/commons/presentation/tags/ScriptWizardTag.java
+++ b/SpagoBIProject/src/it/eng/spagobi/commons/presentation/tags/ScriptWizardTag.java
@@ -1,273 +1,273 @@
/* SpagoBI, the Open Source Business Intelligence suite
* Copyright (C) 2012 Engineering Ingegneria Informatica S.p.A. - SpagoBI Competency Center
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0, without the "Incompatible With Secondary Licenses" notice.
* If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package it.eng.spagobi.commons.presentation.tags;
import it.eng.spago.base.Constants;
import it.eng.spago.base.RequestContainer;
import it.eng.spago.base.ResponseContainer;
import it.eng.spago.base.SessionContainer;
import it.eng.spago.error.EMFInternalError;
import it.eng.spago.security.IEngUserProfile;
import it.eng.spago.tracing.TracerSingleton;
import it.eng.spagobi.commons.bo.Domain;
import it.eng.spagobi.commons.constants.SpagoBIConstants;
import it.eng.spagobi.commons.dao.DAOFactory;
import it.eng.spagobi.commons.utilities.ChannelUtilities;
import it.eng.spagobi.commons.utilities.messages.IMessageBuilder;
import it.eng.spagobi.commons.utilities.messages.MessageBuilderFactory;
import it.eng.spagobi.commons.utilities.urls.IUrlBuilder;
import it.eng.spagobi.commons.utilities.urls.UrlBuilderFactory;
import it.eng.spagobi.tools.dataset.constants.DataSetConstants;
import it.eng.spagobi.utilities.scripting.ScriptUtilities;
import it.eng.spagobi.utilities.themes.ThemesManager;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import org.apache.commons.lang.StringEscapeUtils;
/**
* Presentation tag for Script details.
*/
public class ScriptWizardTag extends CommonWizardLovTag {
private HttpServletRequest httpRequest = null;
protected RequestContainer requestContainer = null;
protected ResponseContainer responseContainer = null;
protected IUrlBuilder urlBuilder = null;
protected IMessageBuilder msgBuilder = null;
private String script;
private String languageScript;
protected String currTheme="";
String readonly = "readonly" ;
boolean isreadonly = true ;
String disabled = "disabled" ;
/* (non-Javadoc)
* @see javax.servlet.jsp.tagext.TagSupport#doStartTag()
*/
public int doStartTag() throws JspException {
httpRequest = (HttpServletRequest) pageContext.getRequest();
requestContainer = ChannelUtilities.getRequestContainer(httpRequest);
responseContainer = ChannelUtilities.getResponseContainer(httpRequest);
urlBuilder = UrlBuilderFactory.getUrlBuilder();
msgBuilder = MessageBuilderFactory.getMessageBuilder();
currTheme=ThemesManager.getCurrentTheme(requestContainer);
if(currTheme==null)currTheme=ThemesManager.getDefaultTheme();
TracerSingleton.log(SpagoBIConstants.NAME_MODULE, TracerSingleton.DEBUG,
"ScriptWizardTag::doStartTag:: invocato");
RequestContainer aRequestContainer = RequestContainer.getRequestContainer();
SessionContainer aSessionContainer = aRequestContainer.getSessionContainer();
SessionContainer permanentSession = aSessionContainer.getPermanentContainer();
IEngUserProfile userProfile = (IEngUserProfile)permanentSession.getAttribute(IEngUserProfile.ENG_USER_PROFILE);
boolean isable = false;
try {
isable = userProfile.isAbleToExecuteAction(SpagoBIConstants.LOVS_MANAGEMENT);
} catch (EMFInternalError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (isable){
isreadonly = false;
readonly = "";
disabled = "";
}
StringBuffer output = new StringBuffer();
String lanuageScriptLabel = msgBuilder.getMessage("SBISet.ListDataSet.languageScript", "messages", httpRequest);
String scriptLabel = msgBuilder.getMessage("SBIDev.scriptWiz.scriptLbl", "messages", httpRequest);
output.append("<table width='100%' cellspacing='0' border='0'>\n");
output.append(" <tr>\n");
output.append(" <td class='titlebar_level_2_text_section' style='vertical-align:middle;'>\n");
output.append(" "+ msgBuilder.getMessage("SBIDev.scriptWiz.wizardTitle", "messages", httpRequest) +"\n");
output.append(" </td>\n");
output.append(" <td class='titlebar_level_2_empty_section'> </td>\n");
output.append(" <td class='titlebar_level_2_button_section'>\n");
output.append(" <a style='text-decoration:none;' href='javascript:opencloseScriptWizardInfo()'> \n");
output.append(" <img width='22px' height='22px'\n");
output.append(" src='" + urlBuilder.getResourceLinkByTheme(httpRequest, "/img/info22.jpg",currTheme)+"'\n");
output.append(" name='info'\n");
output.append(" alt='"+msgBuilder.getMessage("SBIDev.scriptWiz.showSintax", "messages", httpRequest)+"'\n");
output.append(" title='"+msgBuilder.getMessage("SBIDev.scriptWiz.showSintax", "messages", httpRequest)+"'/>\n");
output.append(" </a>\n");
output.append(" </td>\n");
String urlImgProfAttr = urlBuilder.getResourceLinkByTheme(httpRequest, "/img/profileAttributes22.jpg",currTheme);
output.append(generateProfAttrTitleSection(urlImgProfAttr));
output.append(" </tr>\n");
output.append("</table>\n");
output.append("<br/>\n");
output.append("<div class='div_detail_area_forms_lov'>\n");
//LANGUAGE SCRIPT COMBO
output.append(" <div class='div_detail_label_lov'>\n");
output.append(" <span class='portlet-form-field-label'>\n");
output.append(lanuageScriptLabel);
output.append(" </span>\n");
output.append(" </div>\n");
output.append(" <div class='div_detail_form'>\n");
output.append(" <select style='width:180px;' class='portlet-form-input-field' name='LANGUAGESCRIPT' id='LANGUAGESCRIPT' >\n");
- String selected="";
try {
List scriptLanguageList = DAOFactory.getDomainDAO().loadListDomainsByType(DataSetConstants.SCRIPT_TYPE);
if(scriptLanguageList != null){
for(int i=0; i< scriptLanguageList.size(); i++){
Domain domain = (Domain)scriptLanguageList.get(i);
String name = domain.getValueName();
name = StringEscapeUtils.escapeHtml(name);
String value = domain.getValueCd();
value = StringEscapeUtils.escapeHtml(value);
+ String selected="";
if(languageScript.equalsIgnoreCase(value)){
selected="selected='selected'";
}
output.append("<option value='"+value+"' label='"+value+"' "+selected+">");
output.append(name);
output.append("</option>");
}
}
} catch (Throwable e) {
e.printStackTrace();
}
/*
Map engineNames=ScriptUtilities.getEngineFactoriesNames();
for(Iterator it=engineNames.keySet().iterator();it.hasNext();){
String engName=(String)it.next();
String alias=(String)engineNames.get(engName);
alias = StringEscapeUtils.escapeHtml(alias);
selected="";
if(languageScript.equalsIgnoreCase(alias)){
selected="selected='selected'";
}
String aliasName=ScriptUtilities.bindAliasEngine(alias);
output.append("<option value='"+alias+"' label='"+alias+"' "+selected+">");
output.append(aliasName);
output.append("</option>");
}
*/
output.append("</select>");
output.append("</div>");
// FINE LANGUAGE SCRIPT
output.append(" <div class='div_detail_label_lov'>\n");
output.append(" <span class='portlet-form-field-label'>\n");
output.append(scriptLabel);
output.append(" </span>\n");
output.append(" </div>\n");
output.append(" <div style='height:110px;' class='div_detail_form'>\n");
output.append(" <textarea style='height:100px;' "+disabled+" class='portlet-text-area-field' name='SCRIPT' onchange='setLovProviderModified(true);' cols='50'>" + script + "</textarea>\n");
output.append(" </div>\n");
output.append(" <div class='div_detail_label_lov'>\n");
output.append(" \n");
output.append(" </div>\n");
// fine DETAIL AREA FORMS
output.append("</div>\n");
output.append("<script>\n");
output.append(" var infowizardscriptopen = false;\n");
output.append(" var winSWT = null;\n");
output.append(" function opencloseScriptWizardInfo() {\n");
output.append(" if(!infowizardscriptopen){\n");
output.append(" infowizardscriptopen = true;");
output.append(" openScriptWizardInfo();\n");
output.append(" }\n");
output.append(" }\n");
output.append(" function openScriptWizardInfo(){\n");
output.append(" if(winSWT==null) {\n");
output.append(" winSWT = new Window('winSWTInfo', {className: \"alphacube\", title:\""+msgBuilder.getMessage("SBIDev.scriptWiz.showSintax", "messages", httpRequest)+"\",width:680, height:150, destroyOnClose: false});\n");
output.append(" winSWT.setContent('scriptwizardinfodiv', true, false);\n");
output.append(" winSWT.showCenter(false);\n");
output.append(" winSWT.setLocation(40,50);\n");
output.append(" } else {\n");
output.append(" winSWT.showCenter(false);\n");
output.append(" }\n");
output.append(" }\n");
output.append(" observerSWT = { onClose: function(eventName, win) {\n");
output.append(" if (win == winSWT) {\n");
output.append(" infowizardscriptopen = false;");
output.append(" }\n");
output.append(" }\n");
output.append(" }\n");
output.append(" Windows.addObserver(observerSWT);\n");
output.append("</script>\n");
output.append("<div id='scriptwizardinfodiv' style='display:none;'>\n");
output.append(msgBuilder.getMessageTextFromResource("it/eng/spagobi/commons/presentation/tags/info/scriptwizardinfo", httpRequest));
output.append("</div>\n");
try {
pageContext.getOut().print(output.toString());
}
catch (Exception ex) {
TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.CRITICAL, "ScriptWizardTag::doStartTag::", ex);
throw new JspException(ex.getMessage());
}
return SKIP_BODY;
}
/* (non-Javadoc)
* @see javax.servlet.jsp.tagext.TagSupport#doEndTag()
*/
public int doEndTag() throws JspException {
TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.DEBUG, "ScriptWizardTag::doEndTag:: invocato");
return super.doEndTag();
}
/**
* Gets the script.
*
* @return the script
*/
public String getScript() {
return script;
}
/**
* Sets the script.
*
* @param script the new script
*/
public void setScript(String script) {
this.script = script;
}
public String getLanguageScript() {
return languageScript;
}
public void setLanguageScript(String languageScript) {
this.languageScript = languageScript;
}
}
| false | true | public int doStartTag() throws JspException {
httpRequest = (HttpServletRequest) pageContext.getRequest();
requestContainer = ChannelUtilities.getRequestContainer(httpRequest);
responseContainer = ChannelUtilities.getResponseContainer(httpRequest);
urlBuilder = UrlBuilderFactory.getUrlBuilder();
msgBuilder = MessageBuilderFactory.getMessageBuilder();
currTheme=ThemesManager.getCurrentTheme(requestContainer);
if(currTheme==null)currTheme=ThemesManager.getDefaultTheme();
TracerSingleton.log(SpagoBIConstants.NAME_MODULE, TracerSingleton.DEBUG,
"ScriptWizardTag::doStartTag:: invocato");
RequestContainer aRequestContainer = RequestContainer.getRequestContainer();
SessionContainer aSessionContainer = aRequestContainer.getSessionContainer();
SessionContainer permanentSession = aSessionContainer.getPermanentContainer();
IEngUserProfile userProfile = (IEngUserProfile)permanentSession.getAttribute(IEngUserProfile.ENG_USER_PROFILE);
boolean isable = false;
try {
isable = userProfile.isAbleToExecuteAction(SpagoBIConstants.LOVS_MANAGEMENT);
} catch (EMFInternalError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (isable){
isreadonly = false;
readonly = "";
disabled = "";
}
StringBuffer output = new StringBuffer();
String lanuageScriptLabel = msgBuilder.getMessage("SBISet.ListDataSet.languageScript", "messages", httpRequest);
String scriptLabel = msgBuilder.getMessage("SBIDev.scriptWiz.scriptLbl", "messages", httpRequest);
output.append("<table width='100%' cellspacing='0' border='0'>\n");
output.append(" <tr>\n");
output.append(" <td class='titlebar_level_2_text_section' style='vertical-align:middle;'>\n");
output.append(" "+ msgBuilder.getMessage("SBIDev.scriptWiz.wizardTitle", "messages", httpRequest) +"\n");
output.append(" </td>\n");
output.append(" <td class='titlebar_level_2_empty_section'> </td>\n");
output.append(" <td class='titlebar_level_2_button_section'>\n");
output.append(" <a style='text-decoration:none;' href='javascript:opencloseScriptWizardInfo()'> \n");
output.append(" <img width='22px' height='22px'\n");
output.append(" src='" + urlBuilder.getResourceLinkByTheme(httpRequest, "/img/info22.jpg",currTheme)+"'\n");
output.append(" name='info'\n");
output.append(" alt='"+msgBuilder.getMessage("SBIDev.scriptWiz.showSintax", "messages", httpRequest)+"'\n");
output.append(" title='"+msgBuilder.getMessage("SBIDev.scriptWiz.showSintax", "messages", httpRequest)+"'/>\n");
output.append(" </a>\n");
output.append(" </td>\n");
String urlImgProfAttr = urlBuilder.getResourceLinkByTheme(httpRequest, "/img/profileAttributes22.jpg",currTheme);
output.append(generateProfAttrTitleSection(urlImgProfAttr));
output.append(" </tr>\n");
output.append("</table>\n");
output.append("<br/>\n");
output.append("<div class='div_detail_area_forms_lov'>\n");
//LANGUAGE SCRIPT COMBO
output.append(" <div class='div_detail_label_lov'>\n");
output.append(" <span class='portlet-form-field-label'>\n");
output.append(lanuageScriptLabel);
output.append(" </span>\n");
output.append(" </div>\n");
output.append(" <div class='div_detail_form'>\n");
output.append(" <select style='width:180px;' class='portlet-form-input-field' name='LANGUAGESCRIPT' id='LANGUAGESCRIPT' >\n");
String selected="";
try {
List scriptLanguageList = DAOFactory.getDomainDAO().loadListDomainsByType(DataSetConstants.SCRIPT_TYPE);
if(scriptLanguageList != null){
for(int i=0; i< scriptLanguageList.size(); i++){
Domain domain = (Domain)scriptLanguageList.get(i);
String name = domain.getValueName();
name = StringEscapeUtils.escapeHtml(name);
String value = domain.getValueCd();
value = StringEscapeUtils.escapeHtml(value);
if(languageScript.equalsIgnoreCase(value)){
selected="selected='selected'";
}
output.append("<option value='"+value+"' label='"+value+"' "+selected+">");
output.append(name);
output.append("</option>");
}
}
} catch (Throwable e) {
e.printStackTrace();
}
/*
Map engineNames=ScriptUtilities.getEngineFactoriesNames();
for(Iterator it=engineNames.keySet().iterator();it.hasNext();){
String engName=(String)it.next();
String alias=(String)engineNames.get(engName);
alias = StringEscapeUtils.escapeHtml(alias);
selected="";
if(languageScript.equalsIgnoreCase(alias)){
selected="selected='selected'";
}
String aliasName=ScriptUtilities.bindAliasEngine(alias);
output.append("<option value='"+alias+"' label='"+alias+"' "+selected+">");
output.append(aliasName);
output.append("</option>");
}
*/
output.append("</select>");
output.append("</div>");
// FINE LANGUAGE SCRIPT
output.append(" <div class='div_detail_label_lov'>\n");
output.append(" <span class='portlet-form-field-label'>\n");
output.append(scriptLabel);
output.append(" </span>\n");
output.append(" </div>\n");
output.append(" <div style='height:110px;' class='div_detail_form'>\n");
output.append(" <textarea style='height:100px;' "+disabled+" class='portlet-text-area-field' name='SCRIPT' onchange='setLovProviderModified(true);' cols='50'>" + script + "</textarea>\n");
output.append(" </div>\n");
output.append(" <div class='div_detail_label_lov'>\n");
output.append(" \n");
output.append(" </div>\n");
// fine DETAIL AREA FORMS
output.append("</div>\n");
output.append("<script>\n");
output.append(" var infowizardscriptopen = false;\n");
output.append(" var winSWT = null;\n");
output.append(" function opencloseScriptWizardInfo() {\n");
output.append(" if(!infowizardscriptopen){\n");
output.append(" infowizardscriptopen = true;");
output.append(" openScriptWizardInfo();\n");
output.append(" }\n");
output.append(" }\n");
output.append(" function openScriptWizardInfo(){\n");
output.append(" if(winSWT==null) {\n");
output.append(" winSWT = new Window('winSWTInfo', {className: \"alphacube\", title:\""+msgBuilder.getMessage("SBIDev.scriptWiz.showSintax", "messages", httpRequest)+"\",width:680, height:150, destroyOnClose: false});\n");
output.append(" winSWT.setContent('scriptwizardinfodiv', true, false);\n");
output.append(" winSWT.showCenter(false);\n");
output.append(" winSWT.setLocation(40,50);\n");
output.append(" } else {\n");
output.append(" winSWT.showCenter(false);\n");
output.append(" }\n");
output.append(" }\n");
output.append(" observerSWT = { onClose: function(eventName, win) {\n");
output.append(" if (win == winSWT) {\n");
output.append(" infowizardscriptopen = false;");
output.append(" }\n");
output.append(" }\n");
output.append(" }\n");
output.append(" Windows.addObserver(observerSWT);\n");
output.append("</script>\n");
output.append("<div id='scriptwizardinfodiv' style='display:none;'>\n");
output.append(msgBuilder.getMessageTextFromResource("it/eng/spagobi/commons/presentation/tags/info/scriptwizardinfo", httpRequest));
output.append("</div>\n");
try {
pageContext.getOut().print(output.toString());
}
catch (Exception ex) {
TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.CRITICAL, "ScriptWizardTag::doStartTag::", ex);
throw new JspException(ex.getMessage());
}
return SKIP_BODY;
}
| public int doStartTag() throws JspException {
httpRequest = (HttpServletRequest) pageContext.getRequest();
requestContainer = ChannelUtilities.getRequestContainer(httpRequest);
responseContainer = ChannelUtilities.getResponseContainer(httpRequest);
urlBuilder = UrlBuilderFactory.getUrlBuilder();
msgBuilder = MessageBuilderFactory.getMessageBuilder();
currTheme=ThemesManager.getCurrentTheme(requestContainer);
if(currTheme==null)currTheme=ThemesManager.getDefaultTheme();
TracerSingleton.log(SpagoBIConstants.NAME_MODULE, TracerSingleton.DEBUG,
"ScriptWizardTag::doStartTag:: invocato");
RequestContainer aRequestContainer = RequestContainer.getRequestContainer();
SessionContainer aSessionContainer = aRequestContainer.getSessionContainer();
SessionContainer permanentSession = aSessionContainer.getPermanentContainer();
IEngUserProfile userProfile = (IEngUserProfile)permanentSession.getAttribute(IEngUserProfile.ENG_USER_PROFILE);
boolean isable = false;
try {
isable = userProfile.isAbleToExecuteAction(SpagoBIConstants.LOVS_MANAGEMENT);
} catch (EMFInternalError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (isable){
isreadonly = false;
readonly = "";
disabled = "";
}
StringBuffer output = new StringBuffer();
String lanuageScriptLabel = msgBuilder.getMessage("SBISet.ListDataSet.languageScript", "messages", httpRequest);
String scriptLabel = msgBuilder.getMessage("SBIDev.scriptWiz.scriptLbl", "messages", httpRequest);
output.append("<table width='100%' cellspacing='0' border='0'>\n");
output.append(" <tr>\n");
output.append(" <td class='titlebar_level_2_text_section' style='vertical-align:middle;'>\n");
output.append(" "+ msgBuilder.getMessage("SBIDev.scriptWiz.wizardTitle", "messages", httpRequest) +"\n");
output.append(" </td>\n");
output.append(" <td class='titlebar_level_2_empty_section'> </td>\n");
output.append(" <td class='titlebar_level_2_button_section'>\n");
output.append(" <a style='text-decoration:none;' href='javascript:opencloseScriptWizardInfo()'> \n");
output.append(" <img width='22px' height='22px'\n");
output.append(" src='" + urlBuilder.getResourceLinkByTheme(httpRequest, "/img/info22.jpg",currTheme)+"'\n");
output.append(" name='info'\n");
output.append(" alt='"+msgBuilder.getMessage("SBIDev.scriptWiz.showSintax", "messages", httpRequest)+"'\n");
output.append(" title='"+msgBuilder.getMessage("SBIDev.scriptWiz.showSintax", "messages", httpRequest)+"'/>\n");
output.append(" </a>\n");
output.append(" </td>\n");
String urlImgProfAttr = urlBuilder.getResourceLinkByTheme(httpRequest, "/img/profileAttributes22.jpg",currTheme);
output.append(generateProfAttrTitleSection(urlImgProfAttr));
output.append(" </tr>\n");
output.append("</table>\n");
output.append("<br/>\n");
output.append("<div class='div_detail_area_forms_lov'>\n");
//LANGUAGE SCRIPT COMBO
output.append(" <div class='div_detail_label_lov'>\n");
output.append(" <span class='portlet-form-field-label'>\n");
output.append(lanuageScriptLabel);
output.append(" </span>\n");
output.append(" </div>\n");
output.append(" <div class='div_detail_form'>\n");
output.append(" <select style='width:180px;' class='portlet-form-input-field' name='LANGUAGESCRIPT' id='LANGUAGESCRIPT' >\n");
try {
List scriptLanguageList = DAOFactory.getDomainDAO().loadListDomainsByType(DataSetConstants.SCRIPT_TYPE);
if(scriptLanguageList != null){
for(int i=0; i< scriptLanguageList.size(); i++){
Domain domain = (Domain)scriptLanguageList.get(i);
String name = domain.getValueName();
name = StringEscapeUtils.escapeHtml(name);
String value = domain.getValueCd();
value = StringEscapeUtils.escapeHtml(value);
String selected="";
if(languageScript.equalsIgnoreCase(value)){
selected="selected='selected'";
}
output.append("<option value='"+value+"' label='"+value+"' "+selected+">");
output.append(name);
output.append("</option>");
}
}
} catch (Throwable e) {
e.printStackTrace();
}
/*
Map engineNames=ScriptUtilities.getEngineFactoriesNames();
for(Iterator it=engineNames.keySet().iterator();it.hasNext();){
String engName=(String)it.next();
String alias=(String)engineNames.get(engName);
alias = StringEscapeUtils.escapeHtml(alias);
selected="";
if(languageScript.equalsIgnoreCase(alias)){
selected="selected='selected'";
}
String aliasName=ScriptUtilities.bindAliasEngine(alias);
output.append("<option value='"+alias+"' label='"+alias+"' "+selected+">");
output.append(aliasName);
output.append("</option>");
}
*/
output.append("</select>");
output.append("</div>");
// FINE LANGUAGE SCRIPT
output.append(" <div class='div_detail_label_lov'>\n");
output.append(" <span class='portlet-form-field-label'>\n");
output.append(scriptLabel);
output.append(" </span>\n");
output.append(" </div>\n");
output.append(" <div style='height:110px;' class='div_detail_form'>\n");
output.append(" <textarea style='height:100px;' "+disabled+" class='portlet-text-area-field' name='SCRIPT' onchange='setLovProviderModified(true);' cols='50'>" + script + "</textarea>\n");
output.append(" </div>\n");
output.append(" <div class='div_detail_label_lov'>\n");
output.append(" \n");
output.append(" </div>\n");
// fine DETAIL AREA FORMS
output.append("</div>\n");
output.append("<script>\n");
output.append(" var infowizardscriptopen = false;\n");
output.append(" var winSWT = null;\n");
output.append(" function opencloseScriptWizardInfo() {\n");
output.append(" if(!infowizardscriptopen){\n");
output.append(" infowizardscriptopen = true;");
output.append(" openScriptWizardInfo();\n");
output.append(" }\n");
output.append(" }\n");
output.append(" function openScriptWizardInfo(){\n");
output.append(" if(winSWT==null) {\n");
output.append(" winSWT = new Window('winSWTInfo', {className: \"alphacube\", title:\""+msgBuilder.getMessage("SBIDev.scriptWiz.showSintax", "messages", httpRequest)+"\",width:680, height:150, destroyOnClose: false});\n");
output.append(" winSWT.setContent('scriptwizardinfodiv', true, false);\n");
output.append(" winSWT.showCenter(false);\n");
output.append(" winSWT.setLocation(40,50);\n");
output.append(" } else {\n");
output.append(" winSWT.showCenter(false);\n");
output.append(" }\n");
output.append(" }\n");
output.append(" observerSWT = { onClose: function(eventName, win) {\n");
output.append(" if (win == winSWT) {\n");
output.append(" infowizardscriptopen = false;");
output.append(" }\n");
output.append(" }\n");
output.append(" }\n");
output.append(" Windows.addObserver(observerSWT);\n");
output.append("</script>\n");
output.append("<div id='scriptwizardinfodiv' style='display:none;'>\n");
output.append(msgBuilder.getMessageTextFromResource("it/eng/spagobi/commons/presentation/tags/info/scriptwizardinfo", httpRequest));
output.append("</div>\n");
try {
pageContext.getOut().print(output.toString());
}
catch (Exception ex) {
TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.CRITICAL, "ScriptWizardTag::doStartTag::", ex);
throw new JspException(ex.getMessage());
}
return SKIP_BODY;
}
|
diff --git a/app/models/Chapter.java b/app/models/Chapter.java
index c511dea4..45b6a262 100644
--- a/app/models/Chapter.java
+++ b/app/models/Chapter.java
@@ -1,181 +1,181 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package models;
import controllers.DoSearch;
import helpers.Helpers;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import javax.persistence.*;
import javax.persistence.Entity;
import play.db.jpa.GenericModel;
import play.data.validation.Required;
import org.w3c.dom.*;
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import play.db.jpa.JPABase;
import play.modules.search.Field;
import play.modules.search.Indexed;
/**
*
*
* Root-texts are dividet into Chapters
* Starts counting from 0
* Keeps a version of text to index as well as precompiled html
*
*
*/
@Indexed
@Entity
public class Chapter extends GenericModel {
@Id
@SequenceGenerator(name = "chapter_id_seq_gen", sequenceName = "chapter_id_seq")
@GeneratedValue(generator = "chapter_id_seq_gen")
public long id;
@Lob
public String name;
@Lob
public String html;
@Field
@Lob
public String htmlAsText;
@Required
@ManyToOne
public Asset asset;
public int num;
public Chapter(String name, int num, Asset asset, String html) {
this.name = name;
this.num = num;
this.asset = asset;
this.html = html;
}
/**
* Override of save function in JPA
* Currently all div-tags with empty class-defs are deleted
*
*/
@Override
public <T extends JPABase> T save() {
this.htmlAsText = Helpers.stripHtml(html);
// remove empty div's
html = html.replaceAll("<div class='[^']+'/>", "").replaceAll("<div class=\"[^\"]+\"/>", "");
return super.save();
}
/**
* Create text-teaser where lookfor is highlightet
*
* @return teser as html
*/
public String getTeaser(String lookfor) {
return DoSearch.createTeaser(htmlAsText, lookfor);
}
/**
* When a new Asset is imported all old chapters connected to this assed are deleted
*/
private static void deleteOldChapters(Asset asset) {
// System.out.println("**** Chapters on this asset: " + TextReference.find("asset", asset).fetch().size());
for (Object o : Chapter.all().fetch()) {
Chapter c = (Chapter) o;
System.out.println("Chapter id: " + c.asset);
}
Query query = TextReference.em().createQuery("delete from Chapter c where c.asset = :asset");
query.setParameter("asset", asset);
int deleted = query.executeUpdate();
System.out.println("Deleted " + deleted + " old chapters");
System.out.println("Asset id: " + asset.id);
}
/**
* Helper function only: Translates a html-dom-tree to a String
*
* @return html-string without xml-declaration
*/
private static String nodeToString(Node node) {
StringWriter sw = new StringWriter();
try {
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.transform(new DOMSource(node), new StreamResult(sw));
} catch (TransformerException te) {
System.out.println("nodeToString Transformer Exception");
}
return sw.toString();
}
/**
* Divide a xml-file into chapters, chapters are divided by div-tags, attribute name is name of chapter
* Fixme: use xpath selector. Should work with current library which should be the latest
*
*/
public static void createChaptersFromAsset(Asset asset) {
System.out.println("Creating chapters from asset: " + asset.fileName + " , id: " + asset.id);
deleteOldChapters(asset);
try {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
InputStream in = new ByteArrayInputStream(asset.html.getBytes("UTF-8"));
Document doc = builder.parse(in);
XPath xpath = XPathFactory.newInstance().newXPath();
// xpath does not seem to work, picking up every top-level divs?! Check later if probs.
XPathExpression expr = xpath.compile("//div[@class='frontChapter']|//div[@class='chapter']|//div[@class='kolofonBlad']|//div[@class='titlePage' and not(ancestor::div[@class='frontChapter'])]");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
System.out.println("Number of chapters: " + nodes.getLength());
// System.out.println("Txt-content: " + asset.html);
if (nodes.getLength() > 0) {
// System.out.println("xhtml: " + asset.html);
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
- System.out.println("Chapter node: " + Helpers.nodeToString(node));
- System.out.println("---------------------------------------------------");
+ // System.out.println("Chapter node: " + Helpers.nodeToString(node));
+ // System.out.println("---------------------------------------------------");
String name = "- Afsnit - " + (i + 0);
if (i == 0) name = "Kolofon";
if (node.getAttributes().getNamedItem("name") != null) {
name = node.getAttributes().getNamedItem("name").getNodeValue();
System.out.println("Chapter id found: " + name);
}
if (node.getAttributes().getNamedItem("rend") != null) {
name = node.getAttributes().getNamedItem("rend").getNodeValue();
System.out.println("Chapter id found: " + name);
}
Chapter chapter = new Chapter(name, i, asset, nodeToString(node));
chapter.save();
// System.out.println("Chapter: " + i + nodeToString(node));
}
} else {
System.out.println("No chapters found, using hole file as chapter 1");
Chapter chapter = new Chapter("Afsnit 1", 0, asset, nodeToString(doc.getDocumentElement()));
chapter.save();
}
System.out.println("Total chapters: " + Chapter.count());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true | true | public static void createChaptersFromAsset(Asset asset) {
System.out.println("Creating chapters from asset: " + asset.fileName + " , id: " + asset.id);
deleteOldChapters(asset);
try {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
InputStream in = new ByteArrayInputStream(asset.html.getBytes("UTF-8"));
Document doc = builder.parse(in);
XPath xpath = XPathFactory.newInstance().newXPath();
// xpath does not seem to work, picking up every top-level divs?! Check later if probs.
XPathExpression expr = xpath.compile("//div[@class='frontChapter']|//div[@class='chapter']|//div[@class='kolofonBlad']|//div[@class='titlePage' and not(ancestor::div[@class='frontChapter'])]");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
System.out.println("Number of chapters: " + nodes.getLength());
// System.out.println("Txt-content: " + asset.html);
if (nodes.getLength() > 0) {
// System.out.println("xhtml: " + asset.html);
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
System.out.println("Chapter node: " + Helpers.nodeToString(node));
System.out.println("---------------------------------------------------");
String name = "- Afsnit - " + (i + 0);
if (i == 0) name = "Kolofon";
if (node.getAttributes().getNamedItem("name") != null) {
name = node.getAttributes().getNamedItem("name").getNodeValue();
System.out.println("Chapter id found: " + name);
}
if (node.getAttributes().getNamedItem("rend") != null) {
name = node.getAttributes().getNamedItem("rend").getNodeValue();
System.out.println("Chapter id found: " + name);
}
Chapter chapter = new Chapter(name, i, asset, nodeToString(node));
chapter.save();
// System.out.println("Chapter: " + i + nodeToString(node));
}
} else {
System.out.println("No chapters found, using hole file as chapter 1");
Chapter chapter = new Chapter("Afsnit 1", 0, asset, nodeToString(doc.getDocumentElement()));
chapter.save();
}
System.out.println("Total chapters: " + Chapter.count());
} catch (Exception e) {
e.printStackTrace();
}
}
| public static void createChaptersFromAsset(Asset asset) {
System.out.println("Creating chapters from asset: " + asset.fileName + " , id: " + asset.id);
deleteOldChapters(asset);
try {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
InputStream in = new ByteArrayInputStream(asset.html.getBytes("UTF-8"));
Document doc = builder.parse(in);
XPath xpath = XPathFactory.newInstance().newXPath();
// xpath does not seem to work, picking up every top-level divs?! Check later if probs.
XPathExpression expr = xpath.compile("//div[@class='frontChapter']|//div[@class='chapter']|//div[@class='kolofonBlad']|//div[@class='titlePage' and not(ancestor::div[@class='frontChapter'])]");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
System.out.println("Number of chapters: " + nodes.getLength());
// System.out.println("Txt-content: " + asset.html);
if (nodes.getLength() > 0) {
// System.out.println("xhtml: " + asset.html);
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
// System.out.println("Chapter node: " + Helpers.nodeToString(node));
// System.out.println("---------------------------------------------------");
String name = "- Afsnit - " + (i + 0);
if (i == 0) name = "Kolofon";
if (node.getAttributes().getNamedItem("name") != null) {
name = node.getAttributes().getNamedItem("name").getNodeValue();
System.out.println("Chapter id found: " + name);
}
if (node.getAttributes().getNamedItem("rend") != null) {
name = node.getAttributes().getNamedItem("rend").getNodeValue();
System.out.println("Chapter id found: " + name);
}
Chapter chapter = new Chapter(name, i, asset, nodeToString(node));
chapter.save();
// System.out.println("Chapter: " + i + nodeToString(node));
}
} else {
System.out.println("No chapters found, using hole file as chapter 1");
Chapter chapter = new Chapter("Afsnit 1", 0, asset, nodeToString(doc.getDocumentElement()));
chapter.save();
}
System.out.println("Total chapters: " + Chapter.count());
} catch (Exception e) {
e.printStackTrace();
}
}
|
diff --git a/src/net/tweakcraft/tweakcart/util/BlockUtil.java b/src/net/tweakcraft/tweakcart/util/BlockUtil.java
index 11fd9da..b564ed3 100644
--- a/src/net/tweakcraft/tweakcart/util/BlockUtil.java
+++ b/src/net/tweakcraft/tweakcart/util/BlockUtil.java
@@ -1,78 +1,78 @@
/*
* Copyright (c) 2012.
*
* 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 net.tweakcraft.tweakcart.util;
import net.tweakcraft.tweakcart.model.Direction;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Sign;
import java.util.HashSet;
import java.util.Set;
/**
* Created by IntelliJ IDEA.
*
* @author Edoxile
*/
public class BlockUtil {
public static Set<Sign> getSignLocationAround(Block toBlock, Direction cartDriveDirection) {
Set<Sign> signList = new HashSet<Sign>();
if(isSign(toBlock.getRelative(BlockFace.UP)))
signList.add((Sign)toBlock.getRelative(BlockFace.UP).getState());
switch (cartDriveDirection) {
case NORTH:
case SOUTH:
if(isSign(toBlock.getRelative(BlockFace.WEST)))
signList.add((Sign)toBlock.getRelative(BlockFace.WEST).getState());
if(isSign(toBlock.getRelative(BlockFace.WEST).getRelative(BlockFace.DOWN)))
signList.add((Sign)toBlock.getRelative(BlockFace.WEST).getRelative(BlockFace.DOWN).getState());
if(isSign(toBlock.getRelative(BlockFace.EAST)))
signList.add((Sign)toBlock.getRelative(BlockFace.EAST).getState());
if(isSign(toBlock.getRelative(BlockFace.EAST).getRelative(BlockFace.DOWN)))
- signList.add((Sign)toBlock.getRelative(BlockFace.WEST).getRelative(BlockFace.DOWN).getState());
+ signList.add((Sign)toBlock.getRelative(BlockFace.EAST).getRelative(BlockFace.DOWN).getState());
break;
case EAST:
case WEST:
if(isSign(toBlock.getRelative(BlockFace.NORTH)))
signList.add((Sign)toBlock.getRelative(BlockFace.NORTH).getState());
if(isSign(toBlock.getRelative(BlockFace.NORTH).getRelative(BlockFace.DOWN)))
signList.add((Sign)toBlock.getRelative(BlockFace.NORTH).getRelative(BlockFace.DOWN).getState());
if(isSign(toBlock.getRelative(BlockFace.SOUTH)))
signList.add((Sign)toBlock.getRelative(BlockFace.SOUTH).getState());
if(isSign(toBlock.getRelative(BlockFace.SOUTH).getRelative(BlockFace.DOWN)))
signList.add((Sign)toBlock.getRelative(BlockFace.SOUTH).getRelative(BlockFace.DOWN).getState());
break;
}
return signList;
}
public static boolean isRailBlock(Block b) {
return b.getTypeId() == Material.POWERED_RAIL.getId() || b.getTypeId() == Material.DETECTOR_RAIL.getId() || b.getTypeId() == Material.RAILS.getId();
}
public static boolean isSign(Block b) {
return b.getTypeId() == Material.SIGN_POST.getId() || b.getTypeId() == Material.WALL_SIGN.getId();
}
}
| true | true | public static Set<Sign> getSignLocationAround(Block toBlock, Direction cartDriveDirection) {
Set<Sign> signList = new HashSet<Sign>();
if(isSign(toBlock.getRelative(BlockFace.UP)))
signList.add((Sign)toBlock.getRelative(BlockFace.UP).getState());
switch (cartDriveDirection) {
case NORTH:
case SOUTH:
if(isSign(toBlock.getRelative(BlockFace.WEST)))
signList.add((Sign)toBlock.getRelative(BlockFace.WEST).getState());
if(isSign(toBlock.getRelative(BlockFace.WEST).getRelative(BlockFace.DOWN)))
signList.add((Sign)toBlock.getRelative(BlockFace.WEST).getRelative(BlockFace.DOWN).getState());
if(isSign(toBlock.getRelative(BlockFace.EAST)))
signList.add((Sign)toBlock.getRelative(BlockFace.EAST).getState());
if(isSign(toBlock.getRelative(BlockFace.EAST).getRelative(BlockFace.DOWN)))
signList.add((Sign)toBlock.getRelative(BlockFace.WEST).getRelative(BlockFace.DOWN).getState());
break;
case EAST:
case WEST:
if(isSign(toBlock.getRelative(BlockFace.NORTH)))
signList.add((Sign)toBlock.getRelative(BlockFace.NORTH).getState());
if(isSign(toBlock.getRelative(BlockFace.NORTH).getRelative(BlockFace.DOWN)))
signList.add((Sign)toBlock.getRelative(BlockFace.NORTH).getRelative(BlockFace.DOWN).getState());
if(isSign(toBlock.getRelative(BlockFace.SOUTH)))
signList.add((Sign)toBlock.getRelative(BlockFace.SOUTH).getState());
if(isSign(toBlock.getRelative(BlockFace.SOUTH).getRelative(BlockFace.DOWN)))
signList.add((Sign)toBlock.getRelative(BlockFace.SOUTH).getRelative(BlockFace.DOWN).getState());
break;
}
return signList;
}
| public static Set<Sign> getSignLocationAround(Block toBlock, Direction cartDriveDirection) {
Set<Sign> signList = new HashSet<Sign>();
if(isSign(toBlock.getRelative(BlockFace.UP)))
signList.add((Sign)toBlock.getRelative(BlockFace.UP).getState());
switch (cartDriveDirection) {
case NORTH:
case SOUTH:
if(isSign(toBlock.getRelative(BlockFace.WEST)))
signList.add((Sign)toBlock.getRelative(BlockFace.WEST).getState());
if(isSign(toBlock.getRelative(BlockFace.WEST).getRelative(BlockFace.DOWN)))
signList.add((Sign)toBlock.getRelative(BlockFace.WEST).getRelative(BlockFace.DOWN).getState());
if(isSign(toBlock.getRelative(BlockFace.EAST)))
signList.add((Sign)toBlock.getRelative(BlockFace.EAST).getState());
if(isSign(toBlock.getRelative(BlockFace.EAST).getRelative(BlockFace.DOWN)))
signList.add((Sign)toBlock.getRelative(BlockFace.EAST).getRelative(BlockFace.DOWN).getState());
break;
case EAST:
case WEST:
if(isSign(toBlock.getRelative(BlockFace.NORTH)))
signList.add((Sign)toBlock.getRelative(BlockFace.NORTH).getState());
if(isSign(toBlock.getRelative(BlockFace.NORTH).getRelative(BlockFace.DOWN)))
signList.add((Sign)toBlock.getRelative(BlockFace.NORTH).getRelative(BlockFace.DOWN).getState());
if(isSign(toBlock.getRelative(BlockFace.SOUTH)))
signList.add((Sign)toBlock.getRelative(BlockFace.SOUTH).getState());
if(isSign(toBlock.getRelative(BlockFace.SOUTH).getRelative(BlockFace.DOWN)))
signList.add((Sign)toBlock.getRelative(BlockFace.SOUTH).getRelative(BlockFace.DOWN).getState());
break;
}
return signList;
}
|
diff --git a/g3/TeamMegamindMapper.java b/g3/TeamMegamindMapper.java
index 534e4db..8939705 100644
--- a/g3/TeamMegamindMapper.java
+++ b/g3/TeamMegamindMapper.java
@@ -1,98 +1,97 @@
package mapthatset.g3;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import mapthatset.sim.*;
public class TeamMegamindMapper extends Mapper {
int intMappingLength;
String strID = "MegamindMapper";
int round; // index to keep track of how many games played
private ArrayList< Integer > getNewMapping() {
ArrayList< Integer > alNewMapping = new ArrayList< Integer >();
Random rdmGenerator = new Random();
int randomChoice = rdmGenerator.nextInt(3); //creates a random choice of 0, 1 or 2
//int randomChoice = 2;
switch(randomChoice) {
case 0:
System.out.print("All unique map\n");
for ( int intIndex = 0; intIndex < intMappingLength; intIndex ++ ) {
alNewMapping.add( intIndex+1 );
- alNewMapping.add( rdmGenerator.nextInt( intMappingLength ) + 1 );
}
Collections.shuffle(alNewMapping);
System.out.println( "The mapping is: " + alNewMapping );
break;
case 1:
System.out.print("Majority Duplicates\n");
//choose a number that will become the duplicate
int duplicateNumber = rdmGenerator.nextInt(intMappingLength) + 1;
System.out.print("duplicate number is: " + duplicateNumber + "\n");
int amountOfDuplicates;
//need to make sure the amount of duplicates is more than half
if(intMappingLength == 2)
amountOfDuplicates = 2;
else {
amountOfDuplicates = rdmGenerator.nextInt((int) Math.ceil(intMappingLength)) + 1;
}
for ( int intIndex = 0; intIndex < intMappingLength; intIndex ++ ) {
if(amountOfDuplicates >= 0) { //add the amount of duplicates first
alNewMapping.add(duplicateNumber);
amountOfDuplicates--;
continue;
}
alNewMapping.add( rdmGenerator.nextInt( intMappingLength ) + 1 );
}
//randomize final map before sending it for security reasons
Collections.shuffle(alNewMapping);
System.out.println( "The mapping is: " + alNewMapping );
break;
case 2:
System.out.print("All keys map to two elements\n");
// choose the two numbers to map everything to
int firstNumber = rdmGenerator.nextInt(intMappingLength) + 1;
int secondNumber = rdmGenerator.nextInt(intMappingLength) + 1;
// pick random number between n/4 and 3n/4
int split = rdmGenerator.nextInt(intMappingLength/2) + intMappingLength/4;
// this number is the frequency of 'firstNumber' in the mapping
// firstNumber occurs split times, second number occurs n-split times
for ( int intIndex = 0; intIndex < split; intIndex ++ ) {
alNewMapping.add( firstNumber );
}
for ( int intIndex = split; intIndex < intMappingLength; intIndex ++ ) {
alNewMapping.add( secondNumber );
}
Collections.shuffle(alNewMapping);
System.out.println( "The mapping is: " + alNewMapping );
break;
}
return alNewMapping;
}
@Override
public void updateGuesserAction(GuesserAction gsaGA) {
// dumb mapper do nothing here
}
@Override
public ArrayList<Integer> startNewMapping(int intMappingLength) {
// TODO Auto-generated method stub
this.intMappingLength = intMappingLength;
return getNewMapping();
}
@Override
public String getID() {
// TODO Auto-generated method stub
return strID;
}
}
| true | true | private ArrayList< Integer > getNewMapping() {
ArrayList< Integer > alNewMapping = new ArrayList< Integer >();
Random rdmGenerator = new Random();
int randomChoice = rdmGenerator.nextInt(3); //creates a random choice of 0, 1 or 2
//int randomChoice = 2;
switch(randomChoice) {
case 0:
System.out.print("All unique map\n");
for ( int intIndex = 0; intIndex < intMappingLength; intIndex ++ ) {
alNewMapping.add( intIndex+1 );
alNewMapping.add( rdmGenerator.nextInt( intMappingLength ) + 1 );
}
Collections.shuffle(alNewMapping);
System.out.println( "The mapping is: " + alNewMapping );
break;
case 1:
System.out.print("Majority Duplicates\n");
//choose a number that will become the duplicate
int duplicateNumber = rdmGenerator.nextInt(intMappingLength) + 1;
System.out.print("duplicate number is: " + duplicateNumber + "\n");
int amountOfDuplicates;
//need to make sure the amount of duplicates is more than half
if(intMappingLength == 2)
amountOfDuplicates = 2;
else {
amountOfDuplicates = rdmGenerator.nextInt((int) Math.ceil(intMappingLength)) + 1;
}
for ( int intIndex = 0; intIndex < intMappingLength; intIndex ++ ) {
if(amountOfDuplicates >= 0) { //add the amount of duplicates first
alNewMapping.add(duplicateNumber);
amountOfDuplicates--;
continue;
}
alNewMapping.add( rdmGenerator.nextInt( intMappingLength ) + 1 );
}
//randomize final map before sending it for security reasons
Collections.shuffle(alNewMapping);
System.out.println( "The mapping is: " + alNewMapping );
break;
case 2:
System.out.print("All keys map to two elements\n");
// choose the two numbers to map everything to
int firstNumber = rdmGenerator.nextInt(intMappingLength) + 1;
int secondNumber = rdmGenerator.nextInt(intMappingLength) + 1;
// pick random number between n/4 and 3n/4
int split = rdmGenerator.nextInt(intMappingLength/2) + intMappingLength/4;
// this number is the frequency of 'firstNumber' in the mapping
// firstNumber occurs split times, second number occurs n-split times
for ( int intIndex = 0; intIndex < split; intIndex ++ ) {
alNewMapping.add( firstNumber );
}
for ( int intIndex = split; intIndex < intMappingLength; intIndex ++ ) {
alNewMapping.add( secondNumber );
}
Collections.shuffle(alNewMapping);
System.out.println( "The mapping is: " + alNewMapping );
break;
}
return alNewMapping;
}
| private ArrayList< Integer > getNewMapping() {
ArrayList< Integer > alNewMapping = new ArrayList< Integer >();
Random rdmGenerator = new Random();
int randomChoice = rdmGenerator.nextInt(3); //creates a random choice of 0, 1 or 2
//int randomChoice = 2;
switch(randomChoice) {
case 0:
System.out.print("All unique map\n");
for ( int intIndex = 0; intIndex < intMappingLength; intIndex ++ ) {
alNewMapping.add( intIndex+1 );
}
Collections.shuffle(alNewMapping);
System.out.println( "The mapping is: " + alNewMapping );
break;
case 1:
System.out.print("Majority Duplicates\n");
//choose a number that will become the duplicate
int duplicateNumber = rdmGenerator.nextInt(intMappingLength) + 1;
System.out.print("duplicate number is: " + duplicateNumber + "\n");
int amountOfDuplicates;
//need to make sure the amount of duplicates is more than half
if(intMappingLength == 2)
amountOfDuplicates = 2;
else {
amountOfDuplicates = rdmGenerator.nextInt((int) Math.ceil(intMappingLength)) + 1;
}
for ( int intIndex = 0; intIndex < intMappingLength; intIndex ++ ) {
if(amountOfDuplicates >= 0) { //add the amount of duplicates first
alNewMapping.add(duplicateNumber);
amountOfDuplicates--;
continue;
}
alNewMapping.add( rdmGenerator.nextInt( intMappingLength ) + 1 );
}
//randomize final map before sending it for security reasons
Collections.shuffle(alNewMapping);
System.out.println( "The mapping is: " + alNewMapping );
break;
case 2:
System.out.print("All keys map to two elements\n");
// choose the two numbers to map everything to
int firstNumber = rdmGenerator.nextInt(intMappingLength) + 1;
int secondNumber = rdmGenerator.nextInt(intMappingLength) + 1;
// pick random number between n/4 and 3n/4
int split = rdmGenerator.nextInt(intMappingLength/2) + intMappingLength/4;
// this number is the frequency of 'firstNumber' in the mapping
// firstNumber occurs split times, second number occurs n-split times
for ( int intIndex = 0; intIndex < split; intIndex ++ ) {
alNewMapping.add( firstNumber );
}
for ( int intIndex = split; intIndex < intMappingLength; intIndex ++ ) {
alNewMapping.add( secondNumber );
}
Collections.shuffle(alNewMapping);
System.out.println( "The mapping is: " + alNewMapping );
break;
}
return alNewMapping;
}
|
diff --git a/src/com/matburt/mobileorg/Services/TimeclockService.java b/src/com/matburt/mobileorg/Services/TimeclockService.java
index b451748..c9dd180 100644
--- a/src/com/matburt/mobileorg/Services/TimeclockService.java
+++ b/src/com/matburt/mobileorg/Services/TimeclockService.java
@@ -1,240 +1,240 @@
package com.matburt.mobileorg.Services;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.widget.RemoteViews;
import com.matburt.mobileorg.R;
import com.matburt.mobileorg.OrgData.MobileOrgApplication;
import com.matburt.mobileorg.OrgData.OrgNode;
import com.matburt.mobileorg.util.OrgNodeNotFoundException;
public class TimeclockService extends Service {
public static final String NODE_ID = "node_id";
public static final String TIMECLOCK_UPDATE = "timeclock_update";
public static final String TIMECLOCK_TIMEOUT = "timeclock_timeout";
private final int notificationID = 1337;
private NotificationManager mNM;
private AlarmManager alarmManager;
private Notification notification;
private long node_id;
private OrgNode node;
private int estimatedMinute = -1;
private int estimatedHour = -1;
private MobileOrgApplication appInst;
private static TimeclockService sInstance;
private long startTime;
private PendingIntent updateIntent;
private PendingIntent timeoutIntent;
private boolean hasTimedOut = false;
public static TimeclockService getInstance() {
return sInstance;
}
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
this.mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
this.alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
this.appInst = (MobileOrgApplication) getApplication();
}
@Override
public void onDestroy() {
cancelNotification();
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getStringExtra("action");
Log.d("MobileOrg", "Called onStartCommand() with :" + action);
if(action == null) {
this.node_id = intent.getLongExtra(NODE_ID, -1);
try {
this.node = new OrgNode(node_id, getContentResolver());
} catch (OrgNodeNotFoundException e) {}
this.startTime = System.currentTimeMillis();
getEstimated();
showNotification(node_id);
setUpdateAlarm();
setTimeoutAlarm(this.estimatedHour, this.estimatedMinute);
}
else if(action.equals(TIMECLOCK_UPDATE))
updateTime();
else if(action.equals(TIMECLOCK_TIMEOUT)){
doTimeout();
}
return 0;
}
private void getEstimated() {
String estimated = node.getOrgNodePayload().getProperty("Effort").trim();
if (TextUtils.isEmpty(estimated) == false) {
String[] split = estimated.split(":");
try {
if (split.length == 1)
this.estimatedMinute = Integer.parseInt(split[0]);
else if (split.length == 2) {
this.estimatedHour = Integer.parseInt(split[0]);
this.estimatedMinute = Integer.parseInt(split[1]);
}
} catch (NumberFormatException e) {
}
}
}
private void showNotification(long node_id) {
PendingIntent contentIntent = PendingIntent.getActivity(this, 1,
new Intent(this, TimeclockDialog.class), 0);
Builder builder = new NotificationCompat.Builder(this);
- builder.setSmallIcon(R.drawable.icon);
+ builder.setSmallIcon(R.drawable.timeclock_icon);
builder.setContentTitle(node.name);
builder.setContentIntent(contentIntent);
builder.setOngoing(true);
this.notification = builder.getNotification();
notification.contentView = new RemoteViews(this.getPackageName(),
R.layout.timeclock_notification);
notification.contentView.setImageViewResource(R.id.timeclock_notification_icon,
- R.drawable.icon);
+ R.drawable.timeclock_icon);
notification.contentView.setTextViewText(R.id.timeclock_notification_text,
node.name);
updateTime();
mNM.notify(notificationID, notification);
}
private void setUpdateAlarm() {
Intent intent = new Intent(this, TimeclockService.class);
intent.putExtra("action", TIMECLOCK_UPDATE);
this.updateIntent = PendingIntent.getService(appInst, 1,
intent, 0);
alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis()
+ DateUtils.MINUTE_IN_MILLIS, DateUtils.MINUTE_IN_MILLIS, updateIntent);
}
private void setTimeoutAlarm(int hour, int minute) {
if(hour <= 0 && minute <= 0)
return;
long time = (hour * DateUtils.HOUR_IN_MILLIS)
+ (minute * DateUtils.MINUTE_IN_MILLIS);
Intent intent = new Intent(this, TimeclockService.class);
intent.putExtra("action", TIMECLOCK_TIMEOUT);
this.timeoutIntent = PendingIntent.getService(appInst, 2,
intent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ time, timeoutIntent);
}
private void unsetAlarms() {
if(this.updateIntent != null) {
alarmManager.cancel(this.updateIntent);
this.updateIntent = null;
}
if(this.timeoutIntent != null) {
alarmManager.cancel(this.timeoutIntent);
this.timeoutIntent = null;
}
}
private void doTimeout() {
if(notification == null)
return;
notification.defaults = Notification.DEFAULT_ALL;
mNM.notify(notificationID, notification);
notification.defaults = 0;
this.hasTimedOut = true;
updateTime();
}
private void updateTime() {
SpannableStringBuilder itemText = new SpannableStringBuilder(getElapsedTimeString());
if(this.hasTimedOut)
itemText.setSpan(new ForegroundColorSpan(Color.RED), 0,
itemText.length(), 0);
itemText.append(getEstimatedTimeString());
notification.contentView.setTextViewText(
R.id.timeclock_notification_time, itemText);
mNM.notify(notificationID, notification);
}
public String getElapsedTimeString() {
long difference = System.currentTimeMillis() - this.startTime;
if(difference >= 0) {
String elapsed = String.format("%d:%02d",
(int) ((difference / (1000 * 60 * 60)) % 24),
(int) ((difference / (1000 * 60)) % 60));
return elapsed;
}
else
return "0:00";
}
private String getEstimatedTimeString() {
if (this.estimatedHour <= 0 && this.estimatedMinute <= 0)
return "";
else
return "/"
+ String.format("%d:%02d", this.estimatedHour,
this.estimatedMinute);
}
public long getStartTime() {
return this.startTime;
}
public long getEndTime() {
return System.currentTimeMillis();
}
public long getNodeID() {
return this.node_id;
}
public void cancelNotification() {
unsetAlarms();
mNM.cancel(notificationID);
this.stopSelf();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
| false | true | private void showNotification(long node_id) {
PendingIntent contentIntent = PendingIntent.getActivity(this, 1,
new Intent(this, TimeclockDialog.class), 0);
Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.icon);
builder.setContentTitle(node.name);
builder.setContentIntent(contentIntent);
builder.setOngoing(true);
this.notification = builder.getNotification();
notification.contentView = new RemoteViews(this.getPackageName(),
R.layout.timeclock_notification);
notification.contentView.setImageViewResource(R.id.timeclock_notification_icon,
R.drawable.icon);
notification.contentView.setTextViewText(R.id.timeclock_notification_text,
node.name);
updateTime();
mNM.notify(notificationID, notification);
}
| private void showNotification(long node_id) {
PendingIntent contentIntent = PendingIntent.getActivity(this, 1,
new Intent(this, TimeclockDialog.class), 0);
Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.timeclock_icon);
builder.setContentTitle(node.name);
builder.setContentIntent(contentIntent);
builder.setOngoing(true);
this.notification = builder.getNotification();
notification.contentView = new RemoteViews(this.getPackageName(),
R.layout.timeclock_notification);
notification.contentView.setImageViewResource(R.id.timeclock_notification_icon,
R.drawable.timeclock_icon);
notification.contentView.setTextViewText(R.id.timeclock_notification_text,
node.name);
updateTime();
mNM.notify(notificationID, notification);
}
|
diff --git a/src/main/java/com/yasminapp/client/Base2K.java b/src/main/java/com/yasminapp/client/Base2K.java
index 8f1a148..71ebae8 100644
--- a/src/main/java/com/yasminapp/client/Base2K.java
+++ b/src/main/java/com/yasminapp/client/Base2K.java
@@ -1,97 +1,97 @@
package com.yasminapp.client;
public class Base2K {
// See http://twuuenc.atxconsulting.com/index.htm
private static final char[] ALPHABET;
static {
ALPHABET = concat(
range((char) 0x20, (char) 0x7E),
range((char) 0xA1, (char) 0xFF),
range((char) 0x100, (char) 0x17F),
range((char) 0x180, (char) 0x24F),
range((char) 0x250, (char) 0x2AE),
range((char) 0x2B0, (char) 0x2FE),
range((char) 0x390, (char) 0x3CE),
range((char) 0x3D0, (char) 0x3FF),
range((char) 0x400, (char) 0x4FF),
range((char) 0x1401, (char) 0x1676),
range((char) 0x2580, (char) 0x259F),
range((char) 0x25A0, (char) 0x25FF),
range((char) 0x2701, (char) 0x27BE),
range((char) 0x27C0, (char) 0x27EB),
range((char) 0x27F0, (char) 0x27FF));
}
public static String encode(byte[] buf) {
StringBuilder sb = new StringBuilder();
int value;
int chunks = buf.length / 11;
int offset = 0;
// process whole 11-byte chunks
// MSB-first
for (int i=0; i < chunks; i++) {
// 8/3
- value = ((buf[offset] & 0xff << 3)) | ((buf[offset+1] & 0xe0) >>> 5);
+ value = ((buf[offset] & 0xff) << 3) | ((buf[offset+1] & 0xe0) >>> 5);
sb.append(ALPHABET[value]);
offset++;
// 5/6
value = ((buf[offset] & 0x1f) << 6) | ((buf[offset+1] & 0xfd) >>> 2);
sb.append(ALPHABET[value]);
offset++;
// 2/8/1
value = ((buf[offset] & 0x03) << 9) | ((buf[offset+1] & 0xff) << 1) | ((buf[offset+2] & 0x80) >>> 7);
sb.append(ALPHABET[value]);
offset += 2;
// 7/4
value = ((buf[offset] & 0x7f) << 4) | ((buf[offset+1] & 0xf0) >>> 4);
sb.append(ALPHABET[value]);
offset++;
// 4/7
value = ((buf[offset] & 0x0f) << 7) | ((buf[offset+1] & 0xfe) >>> 1);
sb.append(ALPHABET[value]);
offset++;
// 1/8/2
value = ((buf[offset] & 0x01) << 10) | ((buf[offset+1] & 0xff) << 2) | ((buf[offset+2] & 0xc0) >>> 6);
sb.append(ALPHABET[value]);
offset += 2;
// 6/5
value = ((buf[offset] & 0x3f) << 5) | ((buf[offset+1] & 0xf8) >>> 3);
sb.append(ALPHABET[value]);
offset++;
// 3/8
value = ((buf[offset] & 0x07) << 8) | ((buf[offset+1] & 0xff) >>> 3);
sb.append(ALPHABET[value]);
offset++;
}
// TODO process remainder bytes (buf.length % 11)
return sb.toString();
}
public static byte[] decode(String s) {
throw new RuntimeException("Not Yet Implemented");
}
private static char[] range(char start, char stop) {
char[] result = new char[stop - start];
for (char ch = start, i = 0; ch < stop; ch++, i++)
result[i] = ch;
return result;
}
private static char[] concat(char[]... lst) {
int totalLength = 0;
for (char[] arr : lst) {
totalLength += arr.length;
}
char[] result = new char[totalLength];
int offset = 0;
for (char[] arr : lst) {
System.arraycopy(arr, 0, result, offset, arr.length);
offset += arr.length;
}
return result;
}
}
| true | true | public static String encode(byte[] buf) {
StringBuilder sb = new StringBuilder();
int value;
int chunks = buf.length / 11;
int offset = 0;
// process whole 11-byte chunks
// MSB-first
for (int i=0; i < chunks; i++) {
// 8/3
value = ((buf[offset] & 0xff << 3)) | ((buf[offset+1] & 0xe0) >>> 5);
sb.append(ALPHABET[value]);
offset++;
// 5/6
value = ((buf[offset] & 0x1f) << 6) | ((buf[offset+1] & 0xfd) >>> 2);
sb.append(ALPHABET[value]);
offset++;
// 2/8/1
value = ((buf[offset] & 0x03) << 9) | ((buf[offset+1] & 0xff) << 1) | ((buf[offset+2] & 0x80) >>> 7);
sb.append(ALPHABET[value]);
offset += 2;
// 7/4
value = ((buf[offset] & 0x7f) << 4) | ((buf[offset+1] & 0xf0) >>> 4);
sb.append(ALPHABET[value]);
offset++;
// 4/7
value = ((buf[offset] & 0x0f) << 7) | ((buf[offset+1] & 0xfe) >>> 1);
sb.append(ALPHABET[value]);
offset++;
// 1/8/2
value = ((buf[offset] & 0x01) << 10) | ((buf[offset+1] & 0xff) << 2) | ((buf[offset+2] & 0xc0) >>> 6);
sb.append(ALPHABET[value]);
offset += 2;
// 6/5
value = ((buf[offset] & 0x3f) << 5) | ((buf[offset+1] & 0xf8) >>> 3);
sb.append(ALPHABET[value]);
offset++;
// 3/8
value = ((buf[offset] & 0x07) << 8) | ((buf[offset+1] & 0xff) >>> 3);
sb.append(ALPHABET[value]);
offset++;
}
// TODO process remainder bytes (buf.length % 11)
return sb.toString();
}
| public static String encode(byte[] buf) {
StringBuilder sb = new StringBuilder();
int value;
int chunks = buf.length / 11;
int offset = 0;
// process whole 11-byte chunks
// MSB-first
for (int i=0; i < chunks; i++) {
// 8/3
value = ((buf[offset] & 0xff) << 3) | ((buf[offset+1] & 0xe0) >>> 5);
sb.append(ALPHABET[value]);
offset++;
// 5/6
value = ((buf[offset] & 0x1f) << 6) | ((buf[offset+1] & 0xfd) >>> 2);
sb.append(ALPHABET[value]);
offset++;
// 2/8/1
value = ((buf[offset] & 0x03) << 9) | ((buf[offset+1] & 0xff) << 1) | ((buf[offset+2] & 0x80) >>> 7);
sb.append(ALPHABET[value]);
offset += 2;
// 7/4
value = ((buf[offset] & 0x7f) << 4) | ((buf[offset+1] & 0xf0) >>> 4);
sb.append(ALPHABET[value]);
offset++;
// 4/7
value = ((buf[offset] & 0x0f) << 7) | ((buf[offset+1] & 0xfe) >>> 1);
sb.append(ALPHABET[value]);
offset++;
// 1/8/2
value = ((buf[offset] & 0x01) << 10) | ((buf[offset+1] & 0xff) << 2) | ((buf[offset+2] & 0xc0) >>> 6);
sb.append(ALPHABET[value]);
offset += 2;
// 6/5
value = ((buf[offset] & 0x3f) << 5) | ((buf[offset+1] & 0xf8) >>> 3);
sb.append(ALPHABET[value]);
offset++;
// 3/8
value = ((buf[offset] & 0x07) << 8) | ((buf[offset+1] & 0xff) >>> 3);
sb.append(ALPHABET[value]);
offset++;
}
// TODO process remainder bytes (buf.length % 11)
return sb.toString();
}
|
diff --git a/annotateservices/src/org/idiginfo/sciverse/services/SciVerseAnnotation.java b/annotateservices/src/org/idiginfo/sciverse/services/SciVerseAnnotation.java
index 265ca66..595ba50 100644
--- a/annotateservices/src/org/idiginfo/sciverse/services/SciVerseAnnotation.java
+++ b/annotateservices/src/org/idiginfo/sciverse/services/SciVerseAnnotation.java
@@ -1,236 +1,237 @@
package org.idiginfo.sciverse.services;
import org.idiginfo.annotate.services.AnnotateNote;
import org.idiginfo.annotationmodel.Annotation;
public class SciVerseAnnotation implements Annotation{
@Override
public String getPageurl() {
+ // temp
// TODO Auto-generated method stub
return null;
}
@Override
public void setPageurl(String pageurl) {
// TODO Auto-generated method stub
}
@Override
public String getType() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setType(String type) {
// TODO Auto-generated method stub
}
@Override
public String getPagetitle() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setPagetitle(String pagetitle) {
// TODO Auto-generated method stub
}
@Override
public String getContext() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setContext(String context) {
// TODO Auto-generated method stub
}
@Override
public String getSubject() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setSubject(String subject) {
// TODO Auto-generated method stub
}
@Override
public String getNotetext() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setNotetext(String notetext) {
// TODO Auto-generated method stub
}
@Override
public String getAuthor() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setAuthor(String author) {
// TODO Auto-generated method stub
}
@Override
public String getSigned() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setSigned(String signed) {
// TODO Auto-generated method stub
}
@Override
public String getDate() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setDate(String date) {
// TODO Auto-generated method stub
}
@Override
public String getTags() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setTags(String tags) {
// TODO Auto-generated method stub
}
@Override
public String getMatch() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setMatch(String match) {
// TODO Auto-generated method stub
}
@Override
public String getNum() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setNum(String num) {
// TODO Auto-generated method stub
}
@Override
public String getGid() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setGid(String gid) {
// TODO Auto-generated method stub
}
@Override
public String getColor() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setColor(String color) {
// TODO Auto-generated method stub
}
@Override
public String getMark() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setMark(String mark) {
// TODO Auto-generated method stub
}
@Override
public String getState() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setState(String state) {
// TODO Auto-generated method stub
}
@Override
public String getFinalTags() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setFinalTags(String finalTags) {
// TODO Auto-generated method stub
}
@Override
public AnnotateNote[] getReplies() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setReplies(AnnotateNote[] replies) {
// TODO Auto-generated method stub
}
@Override
public String getFullPageUrl() {
// TODO Auto-generated method stub
return null;
}
@Override
public Integer getPagenum() {
// TODO Auto-generated method stub
return null;
}
}
| true | true | public String getPageurl() {
// TODO Auto-generated method stub
return null;
}
| public String getPageurl() {
// temp
// TODO Auto-generated method stub
return null;
}
|
diff --git a/araqne-logdb/src/main/java/org/araqne/logdb/query/parser/ExpressionParser.java b/araqne-logdb/src/main/java/org/araqne/logdb/query/parser/ExpressionParser.java
index ca57dd4f..a99955b9 100644
--- a/araqne-logdb/src/main/java/org/araqne/logdb/query/parser/ExpressionParser.java
+++ b/araqne-logdb/src/main/java/org/araqne/logdb/query/parser/ExpressionParser.java
@@ -1,400 +1,402 @@
/*
* Copyright 2013 Future Systems
*
* 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.araqne.logdb.query.parser;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import org.araqne.logdb.LogQueryParseException;
import org.araqne.logdb.query.expr.Expression;
public class ExpressionParser {
public static Expression parse(String s, OpEmitterFactory of, FuncEmitterFactory ff, TermEmitterFactory tf) {
if (s == null)
throw new IllegalArgumentException("expression string should not be null");
s = s.replaceAll("\t", " ");
List<Term> terms = tokenize(s);
List<Term> output = convertToPostfix(terms);
Stack<Expression> exprStack = new Stack<Expression>();
for (Term term : output) {
if (term instanceof OpTerm) {
OpTerm op = (OpTerm) term;
of.emit(exprStack, op);
} else if (term instanceof TokenTerm) {
// parse token expression (variable or numeric constant)
TokenTerm t = (TokenTerm) term;
tf.emit(exprStack, t);
} else {
// parse function expression
FuncTerm f = (FuncTerm) term;
ff.emit(exprStack, f);
}
}
return exprStack.pop();
}
private static OpEmitterFactory evalOEF = new EvalOpEmitterFactory();
private static FuncEmitterFactory evalFEF = new EvalFuncEmitterFactory();
private static TermEmitterFactory evalTEF = new EvalTermEmitterFactory();
public static Expression parse(String s) {
return parse(s, evalOEF, evalFEF, evalTEF);
}
private static List<Term> convertToPostfix(List<Term> tokens) {
Stack<Term> opStack = new Stack<Term>();
List<Term> output = new ArrayList<Term>();
int i = 0;
int len = tokens.size();
while (i < len) {
Term token = tokens.get(i);
if (isDelimiter(token)) {
// need to pop operator and write to output?
while (needPop(token, opStack, output)) {
Term last = opStack.pop();
output.add(last);
}
if (token instanceof OpTerm || token instanceof FuncTerm) {
opStack.add(token);
} else if (((TokenTerm) token).getText().equals("(")) {
opStack.add(token);
} else if (((TokenTerm) token).getText().equals(")")) {
boolean foundMatchParens = false;
while (!opStack.isEmpty()) {
Term last = opStack.pop();
if (last instanceof TokenTerm && ((TokenTerm) last).getText().equals("(")) {
foundMatchParens = true;
break;
} else {
output.add(last);
}
}
if (!foundMatchParens)
throw new LogQueryParseException("parens-mismatch", -1);
- Term last = opStack.pop();
- if (last instanceof FuncTerm) {
- output.add(last);
- } else {
- opStack.push(last);
+ if (!opStack.empty()) {
+ Term last = opStack.pop();
+ if (last instanceof FuncTerm) {
+ output.add(last);
+ } else {
+ opStack.push(last);
+ }
}
}
} else {
output.add(token);
}
i++;
}
// last operator flush
while (!opStack.isEmpty()) {
Term op = opStack.pop();
output.add(op);
}
return output;
}
private static boolean needPop(Term token, Stack<Term> opStack, List<Term> output) {
if (!(token instanceof OpTerm))
return false;
OpTerm currentOp = (OpTerm) token;
int precedence = currentOp.precedence;
boolean leftAssoc = currentOp.leftAssoc;
OpTerm lastOp = null;
if (!opStack.isEmpty()) {
Term t = opStack.peek();
if (!(t instanceof OpTerm)) {
return false;
}
lastOp = (OpTerm) t;
} else {
return false;
}
if (leftAssoc && precedence <= lastOp.precedence)
return true;
if (precedence < lastOp.precedence)
return true;
return false;
}
private static boolean isOperator(String token) {
if (token == null)
return false;
return isDelimiter(token);
}
public static List<Term> tokenize(String s) {
return tokenize(s, 0, s.length() - 1);
}
private static List<Term> tokenize(String s, int begin, int end) {
List<Term> tokens = new ArrayList<Term>();
String lastToken = null;
int next = begin;
while (true) {
ParseResult r = nextToken(s, next, end);
if (r == null)
break;
String token = (String) r.value;
if (token.isEmpty())
continue;
// read function call (including nested one)
if (token.equals("(") && lastToken != null && !isOperator(lastToken)) {
// remove last term and add function term instead
tokens.remove(tokens.size() - 1);
List<String> functionTokens = new ArrayList<String>();
functionTokens.add(lastToken);
tokens.add(new FuncTerm(functionTokens));
}
OpTerm op = OpTerm.parse(token);
// check if unary operator
if (op != null && op.symbol.equals("-")) {
Term lastTerm = null;
if (!tokens.isEmpty()) {
lastTerm = tokens.get(tokens.size() - 1);
}
if (lastToken == null || lastToken.equals("(") || lastTerm instanceof OpTerm) {
op = OpTerm.Neg;
}
}
if (op != null)
tokens.add(op);
else
tokens.add(new TokenTerm(token));
next = r.next;
lastToken = token;
}
return tokens;
}
private static ParseResult nextToken(String s, int begin, int end) {
if (begin > end)
return null;
// use r.next as a position here (need +1 for actual next)
ParseResult r = findNextDelimiter(s, begin, end);
if (r.next < begin) {
// no symbol operator and white space, return whole string
String token = s.substring(begin, end + 1).trim();
return new ParseResult(token, end + 1);
}
if (isAllWhitespaces(s, begin, r.next - 1)) {
// check if next token is quoted string
if (r.value.equals("\"")) {
int p = s.indexOf('"', r.next + 1);
if (p < 0) {
String quoted = s.substring(r.next);
return new ParseResult(quoted, s.length());
} else {
String quoted = s.substring(r.next, p + 1);
return new ParseResult(quoted, p + 1);
}
}
// check whitespace
String token = (String) r.value;
if (token.trim().isEmpty())
return nextToken(s, skipSpaces(s, begin), end);
// return operator
int len = token.length();
return new ParseResult(token, r.next + len);
} else {
// return term
String token = s.substring(begin, r.next).trim();
return new ParseResult(token, r.next);
}
}
private static boolean isAllWhitespaces(String s, int begin, int end) {
if (end < begin)
return true;
for (int i = begin; i <= end; i++)
if (s.charAt(i) != ' ' && s.charAt(i) != '\t')
return false;
return true;
}
private static ParseResult findNextDelimiter(String s, int begin, int end) {
// check parens, comma and operators
ParseResult r = new ParseResult(null, -1);
min(r, "\"", s.indexOf('"', begin), end);
min(r, "(", s.indexOf('(', begin), end);
min(r, ")", s.indexOf(')', begin), end);
min(r, ",", s.indexOf(',', begin), end);
for (OpTerm op : OpTerm.values()) {
// check alphabet keywords
if (op.isAlpha)
continue;
min(r, op.symbol, s.indexOf(op.symbol, begin), end);
}
// check white spaces
// tabs are removed by ExpressionParser.parse, so it processes space only.
min(r, " ", s.indexOf(' ', begin), end);
return r;
}
private static boolean isDelimiter(String s) {
String d = s.trim();
if (d.equals("(") || d.equals(")") || d.equals(","))
return true;
for (OpTerm op : OpTerm.values())
if (op.symbol.equals(s))
return true;
return false;
}
private static void min(ParseResult r, String symbol, int p, int end) {
if (p < 0)
return;
boolean change = p >= 0 && p <= end && (r.next == -1 || p < r.next);
if (change) {
r.value = symbol;
r.next = p;
}
}
private static boolean isDelimiter(Term t) {
if (t instanceof OpTerm || t instanceof FuncTerm)
return true;
if (t instanceof TokenTerm) {
String text = ((TokenTerm) t).getText();
return text.equals("(") || text.equals(")");
}
return false;
}
private static interface Term {
}
public static class TokenTerm implements Term {
private String text;
public TokenTerm(String text) {
this.text = text;
}
@Override
public String toString() {
return getText();
}
public String getText() {
return text;
}
}
public static enum OpTerm implements Term {
Add("+", 500), Sub("-", 500), Mul("*", 510), Div("/", 510), Neg("-", 520, false, true, false),
Gte(">=", 410), Lte("<=", 410), Gt(">", 410), Lt("<", 410), Eq("==", 400), Neq("!=", 400),
And("and", 310, true, false, true), Or("or", 300, true, false, true), Not("not", 320, false, true, true),
Comma(",", 200),
From("from", 100, true, false, true), union("union", 110, false, true, true),
;
OpTerm(String symbol, int precedence) {
this(symbol, precedence, true, false, false);
}
OpTerm(String symbol, int precedence, boolean leftAssoc, boolean unary, boolean isAlpha) {
this.symbol = symbol;
this.precedence = precedence;
this.leftAssoc = leftAssoc;
this.unary = unary;
this.isAlpha = isAlpha;
}
public String symbol;
public int precedence;
public boolean leftAssoc;
public boolean unary;
public boolean isAlpha;
public static OpTerm parse(String token) {
for (OpTerm t : values())
if (t.symbol.equals(token))
return t;
return null;
}
@Override
public String toString() {
return symbol;
}
}
public static class FuncTerm implements Term {
private List<String> tokens;
public FuncTerm(List<String> tokens) {
this.tokens = tokens;
}
@Override
public String toString() {
return "func term(" + tokens + ")";
}
public List<String> getTokens() {
return tokens;
}
}
public static int skipSpaces(String text, int position) {
int i = position;
while (i < text.length() && text.charAt(i) == ' ')
i++;
return i;
}
}
| true | true | private static List<Term> convertToPostfix(List<Term> tokens) {
Stack<Term> opStack = new Stack<Term>();
List<Term> output = new ArrayList<Term>();
int i = 0;
int len = tokens.size();
while (i < len) {
Term token = tokens.get(i);
if (isDelimiter(token)) {
// need to pop operator and write to output?
while (needPop(token, opStack, output)) {
Term last = opStack.pop();
output.add(last);
}
if (token instanceof OpTerm || token instanceof FuncTerm) {
opStack.add(token);
} else if (((TokenTerm) token).getText().equals("(")) {
opStack.add(token);
} else if (((TokenTerm) token).getText().equals(")")) {
boolean foundMatchParens = false;
while (!opStack.isEmpty()) {
Term last = opStack.pop();
if (last instanceof TokenTerm && ((TokenTerm) last).getText().equals("(")) {
foundMatchParens = true;
break;
} else {
output.add(last);
}
}
if (!foundMatchParens)
throw new LogQueryParseException("parens-mismatch", -1);
Term last = opStack.pop();
if (last instanceof FuncTerm) {
output.add(last);
} else {
opStack.push(last);
}
}
} else {
output.add(token);
}
i++;
}
// last operator flush
while (!opStack.isEmpty()) {
Term op = opStack.pop();
output.add(op);
}
return output;
}
| private static List<Term> convertToPostfix(List<Term> tokens) {
Stack<Term> opStack = new Stack<Term>();
List<Term> output = new ArrayList<Term>();
int i = 0;
int len = tokens.size();
while (i < len) {
Term token = tokens.get(i);
if (isDelimiter(token)) {
// need to pop operator and write to output?
while (needPop(token, opStack, output)) {
Term last = opStack.pop();
output.add(last);
}
if (token instanceof OpTerm || token instanceof FuncTerm) {
opStack.add(token);
} else if (((TokenTerm) token).getText().equals("(")) {
opStack.add(token);
} else if (((TokenTerm) token).getText().equals(")")) {
boolean foundMatchParens = false;
while (!opStack.isEmpty()) {
Term last = opStack.pop();
if (last instanceof TokenTerm && ((TokenTerm) last).getText().equals("(")) {
foundMatchParens = true;
break;
} else {
output.add(last);
}
}
if (!foundMatchParens)
throw new LogQueryParseException("parens-mismatch", -1);
if (!opStack.empty()) {
Term last = opStack.pop();
if (last instanceof FuncTerm) {
output.add(last);
} else {
opStack.push(last);
}
}
}
} else {
output.add(token);
}
i++;
}
// last operator flush
while (!opStack.isEmpty()) {
Term op = opStack.pop();
output.add(op);
}
return output;
}
|
diff --git a/pa1/src/to/richard/tsp/ElitismSurvivorSelection.java b/pa1/src/to/richard/tsp/ElitismSurvivorSelection.java
index 2a49463..ad9ea7e 100644
--- a/pa1/src/to/richard/tsp/ElitismSurvivorSelection.java
+++ b/pa1/src/to/richard/tsp/ElitismSurvivorSelection.java
@@ -1,59 +1,59 @@
package to.richard.tsp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Author: Richard To
* Date: 2/11/13
*/
/**
* Implementation of Elitism using Aged-based replacement.
*
* Replace fittest parent with worst offspring. If no worst offspring,
* don't do replacement.
*/
public class ElitismSurvivorSelection implements ISurvivorSelector {
private FitnessEvaluator _fitnessEvaluator;
private Comparator<Pair<Double, Genotype>> _comparator;
public ElitismSurvivorSelection(
FitnessEvaluator fitnessEvaluator, Comparator<Pair<Double, Genotype>> comparator) {
_fitnessEvaluator = fitnessEvaluator;
_comparator = comparator;
}
@Override
public List<Genotype> replace(List<Genotype> parents, List<Genotype> offspring) {
ArrayList<Pair<Double, Genotype>> fitnessParents = new ArrayList<Pair<Double, Genotype>>();
ArrayList<Pair<Double, Genotype>> fitnessOffspring = new ArrayList<Pair<Double, Genotype>>();
ArrayList<Genotype> nextGeneration = new ArrayList<Genotype>();
Pair<Double, Genotype> fittestGenotypePair;
for (Genotype genotype : parents) {
fitnessParents.add(_fitnessEvaluator.evaluateAsPair(genotype));
}
Collections.sort(fitnessParents, _comparator);
- for (Genotype genotype : parents) {
+ for (Genotype genotype : offspring) {
fitnessOffspring.add(_fitnessEvaluator.evaluateAsPair(genotype));
}
Collections.sort(fitnessOffspring, _comparator);
for (Pair<Double, Genotype> pair : fitnessOffspring) {
nextGeneration.add(pair.getSecondValue());
}
fittestGenotypePair = fitnessParents.get(fitnessParents.size() - 1);
- if (fittestGenotypePair.getFirstValue() > fitnessOffspring.get(0).getFirstValue()) {
+ if (_comparator.compare(fittestGenotypePair, fitnessOffspring.get(0)) > 0) {
nextGeneration.set(0, fittestGenotypePair.getSecondValue());
}
return nextGeneration;
}
}
| false | true | public List<Genotype> replace(List<Genotype> parents, List<Genotype> offspring) {
ArrayList<Pair<Double, Genotype>> fitnessParents = new ArrayList<Pair<Double, Genotype>>();
ArrayList<Pair<Double, Genotype>> fitnessOffspring = new ArrayList<Pair<Double, Genotype>>();
ArrayList<Genotype> nextGeneration = new ArrayList<Genotype>();
Pair<Double, Genotype> fittestGenotypePair;
for (Genotype genotype : parents) {
fitnessParents.add(_fitnessEvaluator.evaluateAsPair(genotype));
}
Collections.sort(fitnessParents, _comparator);
for (Genotype genotype : parents) {
fitnessOffspring.add(_fitnessEvaluator.evaluateAsPair(genotype));
}
Collections.sort(fitnessOffspring, _comparator);
for (Pair<Double, Genotype> pair : fitnessOffspring) {
nextGeneration.add(pair.getSecondValue());
}
fittestGenotypePair = fitnessParents.get(fitnessParents.size() - 1);
if (fittestGenotypePair.getFirstValue() > fitnessOffspring.get(0).getFirstValue()) {
nextGeneration.set(0, fittestGenotypePair.getSecondValue());
}
return nextGeneration;
}
| public List<Genotype> replace(List<Genotype> parents, List<Genotype> offspring) {
ArrayList<Pair<Double, Genotype>> fitnessParents = new ArrayList<Pair<Double, Genotype>>();
ArrayList<Pair<Double, Genotype>> fitnessOffspring = new ArrayList<Pair<Double, Genotype>>();
ArrayList<Genotype> nextGeneration = new ArrayList<Genotype>();
Pair<Double, Genotype> fittestGenotypePair;
for (Genotype genotype : parents) {
fitnessParents.add(_fitnessEvaluator.evaluateAsPair(genotype));
}
Collections.sort(fitnessParents, _comparator);
for (Genotype genotype : offspring) {
fitnessOffspring.add(_fitnessEvaluator.evaluateAsPair(genotype));
}
Collections.sort(fitnessOffspring, _comparator);
for (Pair<Double, Genotype> pair : fitnessOffspring) {
nextGeneration.add(pair.getSecondValue());
}
fittestGenotypePair = fitnessParents.get(fitnessParents.size() - 1);
if (_comparator.compare(fittestGenotypePair, fitnessOffspring.get(0)) > 0) {
nextGeneration.set(0, fittestGenotypePair.getSecondValue());
}
return nextGeneration;
}
|
diff --git a/hale/eu.esdihumboldt.hale.rcp.wizards.functions.core/src/eu/esdihumboldt/hale/rcp/wizards/functions/core/geometric/NetworkExpansionFunctionWizardPage.java b/hale/eu.esdihumboldt.hale.rcp.wizards.functions.core/src/eu/esdihumboldt/hale/rcp/wizards/functions/core/geometric/NetworkExpansionFunctionWizardPage.java
index a0c0d5724..12e173a5f 100644
--- a/hale/eu.esdihumboldt.hale.rcp.wizards.functions.core/src/eu/esdihumboldt/hale/rcp/wizards/functions/core/geometric/NetworkExpansionFunctionWizardPage.java
+++ b/hale/eu.esdihumboldt.hale.rcp.wizards.functions.core/src/eu/esdihumboldt/hale/rcp/wizards/functions/core/geometric/NetworkExpansionFunctionWizardPage.java
@@ -1,177 +1,180 @@
/*
* HUMBOLDT: A Framework for Data Harmonisation and Service Integration.
* EU Integrated Project #030962 01.10.2006 - 30.09.2010
*
* For more information on the project, please refer to the this web site:
* http://www.esdi-humboldt.eu
*
* LICENSE: For information on the license under which this program is
* available, please refer to http:/www.esdi-humboldt.eu/license.html#core
* (c) the HUMBOLDT Consortium, 2007 to 2010.
*/
package eu.esdihumboldt.hale.rcp.wizards.functions.core.geometric;
import java.util.Set;
import java.util.TreeSet;
import org.eclipse.jface.dialogs.IDialogPage;
import org.eclipse.jface.preference.FieldEditor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.PlatformUI;
import eu.esdihumboldt.hale.rcp.utils.definition.DefinitionLabelFactory;
import eu.esdihumboldt.hale.rcp.views.model.SchemaItem;
import eu.esdihumboldt.hale.rcp.wizards.functions.AbstractSingleCellWizardPage;
import eu.esdihumboldt.hale.rcp.wizards.functions.core.math.MathExpressionFieldEditor;
/**
* The WizardPage that contains the UI for the {@link NetworkExpansionFunctionWizard}.
*
* @author Thorsten Reitz
* @version $Id$
*/
public class NetworkExpansionFunctionWizardPage
extends AbstractSingleCellWizardPage {
private MathExpressionFieldEditor expressionEditor = null;
private String initialExpression = null;
/**
* Constructor
*
* @param pageName the page name
*/
protected NetworkExpansionFunctionWizardPage(String pageName) {
super(pageName);
setTitle(pageName);
}
/**
* @see IDialogPage#createControl(Composite)
*/
@Override
public void createControl(Composite parent) {
super.initializeDialogUnits(parent);
this.setPageComplete(this.isPageComplete());
Composite composite = new Composite(parent, SWT.NULL);
composite.setLayout(new GridLayout());
composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL
| GridData.HORIZONTAL_ALIGN_FILL));
composite.setSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
composite.setFont(parent.getFont());
this.createConfigurationGroup(composite);
setErrorMessage(null); // should not initially have error message
super.setControl(composite);
}
private void createConfigurationGroup(Composite parent) {
// define source group composite
Group configurationGroup = new Group(parent, SWT.NONE);
configurationGroup.setText("Define Network to Polygon Expansion");
configurationGroup.setLayout(new GridLayout());
GridData configurationAreaGD = new GridData(GridData.VERTICAL_ALIGN_FILL
| GridData.HORIZONTAL_ALIGN_FILL);
configurationAreaGD.grabExcessHorizontalSpace = true;
configurationGroup.setLayoutData(configurationAreaGD);
configurationGroup.setSize(configurationGroup.computeSize(SWT.DEFAULT, SWT.DEFAULT));
configurationGroup.setFont(parent.getFont());
final Composite configurationComposite = new Composite(configurationGroup, SWT.NONE);
configurationComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
GridLayout fileSelectionLayout = new GridLayout();
- fileSelectionLayout.numColumns = 2;
+ fileSelectionLayout.numColumns = 3;
fileSelectionLayout.makeColumnsEqualWidth = false;
fileSelectionLayout.marginWidth = 0;
fileSelectionLayout.marginHeight = 0;
configurationComposite.setLayout(fileSelectionLayout);
DefinitionLabelFactory dlf = (DefinitionLabelFactory) PlatformUI.getWorkbench().getService(DefinitionLabelFactory.class);
final Label inputAttributeLabel = new Label(configurationComposite, SWT.NONE);
inputAttributeLabel.setText("Source attribute:");
Control inputAttributeText = dlf.createLabel(configurationComposite, getParent().getSourceItem().getDefinition(), false);
- inputAttributeText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
+ inputAttributeText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
final Label outputAttributeLabel = new Label(configurationComposite, SWT.NONE);
outputAttributeLabel.setText("Target attribute:");
Control outputAttributeText = dlf.createLabel(configurationComposite, getParent().getTargetItem().getDefinition(), false);
- outputAttributeText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
+ outputAttributeText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
final Label expansionExpressionLabel = new Label(configurationComposite, SWT.NONE);
expansionExpressionLabel.setText("Expansion expression:");
// expression
Set<String> variables = new TreeSet<String>();
SchemaItem p = getParent().getSourceItem();
for (SchemaItem var : p.getParent().getChildren()) {
if (Number.class.isAssignableFrom(
var.getPropertyType().getBinding())
|| String.class.isAssignableFrom(
var.getPropertyType().getBinding())) {
variables.add(var.getName().getLocalPart());
}
}
this.expressionEditor = new MathExpressionFieldEditor(
"expression", "=", configurationComposite, variables);
if (this.initialExpression != null && !this.initialExpression.equals("")) {
this.expressionEditor.setStringValue(this.initialExpression);
}
else {
this.expressionEditor.setStringValue("50");
}
this.expressionEditor.setEmptyStringAllowed(false);
this.expressionEditor.setPage(this);
this.expressionEditor.setPropertyChangeListener(new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(FieldEditor.IS_VALID)) {
update();
}
}
});
+ // re-set the layout because the field editor breaks it and sets its own
+ configurationComposite.setLayout(fileSelectionLayout);
+ configurationComposite.layout(true, true);
}
private void update() {
setPageComplete(expressionEditor.isValid());
}
/**
* @see WizardPage#isPageComplete()
*/
@Override
public boolean isPageComplete() {
return this.expressionEditor != null
&& this.expressionEditor.getStringValue() != null;
}
/**
* @return the expansion expression
*/
public String getExpansion() {
return this.expressionEditor.getStringValue();
}
public void setInitialExpression(String value) {
this.initialExpression = value;
}
}
| false | true | private void createConfigurationGroup(Composite parent) {
// define source group composite
Group configurationGroup = new Group(parent, SWT.NONE);
configurationGroup.setText("Define Network to Polygon Expansion");
configurationGroup.setLayout(new GridLayout());
GridData configurationAreaGD = new GridData(GridData.VERTICAL_ALIGN_FILL
| GridData.HORIZONTAL_ALIGN_FILL);
configurationAreaGD.grabExcessHorizontalSpace = true;
configurationGroup.setLayoutData(configurationAreaGD);
configurationGroup.setSize(configurationGroup.computeSize(SWT.DEFAULT, SWT.DEFAULT));
configurationGroup.setFont(parent.getFont());
final Composite configurationComposite = new Composite(configurationGroup, SWT.NONE);
configurationComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
GridLayout fileSelectionLayout = new GridLayout();
fileSelectionLayout.numColumns = 2;
fileSelectionLayout.makeColumnsEqualWidth = false;
fileSelectionLayout.marginWidth = 0;
fileSelectionLayout.marginHeight = 0;
configurationComposite.setLayout(fileSelectionLayout);
DefinitionLabelFactory dlf = (DefinitionLabelFactory) PlatformUI.getWorkbench().getService(DefinitionLabelFactory.class);
final Label inputAttributeLabel = new Label(configurationComposite, SWT.NONE);
inputAttributeLabel.setText("Source attribute:");
Control inputAttributeText = dlf.createLabel(configurationComposite, getParent().getSourceItem().getDefinition(), false);
inputAttributeText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
final Label outputAttributeLabel = new Label(configurationComposite, SWT.NONE);
outputAttributeLabel.setText("Target attribute:");
Control outputAttributeText = dlf.createLabel(configurationComposite, getParent().getTargetItem().getDefinition(), false);
outputAttributeText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
final Label expansionExpressionLabel = new Label(configurationComposite, SWT.NONE);
expansionExpressionLabel.setText("Expansion expression:");
// expression
Set<String> variables = new TreeSet<String>();
SchemaItem p = getParent().getSourceItem();
for (SchemaItem var : p.getParent().getChildren()) {
if (Number.class.isAssignableFrom(
var.getPropertyType().getBinding())
|| String.class.isAssignableFrom(
var.getPropertyType().getBinding())) {
variables.add(var.getName().getLocalPart());
}
}
this.expressionEditor = new MathExpressionFieldEditor(
"expression", "=", configurationComposite, variables);
if (this.initialExpression != null && !this.initialExpression.equals("")) {
this.expressionEditor.setStringValue(this.initialExpression);
}
else {
this.expressionEditor.setStringValue("50");
}
this.expressionEditor.setEmptyStringAllowed(false);
this.expressionEditor.setPage(this);
this.expressionEditor.setPropertyChangeListener(new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(FieldEditor.IS_VALID)) {
update();
}
}
});
}
| private void createConfigurationGroup(Composite parent) {
// define source group composite
Group configurationGroup = new Group(parent, SWT.NONE);
configurationGroup.setText("Define Network to Polygon Expansion");
configurationGroup.setLayout(new GridLayout());
GridData configurationAreaGD = new GridData(GridData.VERTICAL_ALIGN_FILL
| GridData.HORIZONTAL_ALIGN_FILL);
configurationAreaGD.grabExcessHorizontalSpace = true;
configurationGroup.setLayoutData(configurationAreaGD);
configurationGroup.setSize(configurationGroup.computeSize(SWT.DEFAULT, SWT.DEFAULT));
configurationGroup.setFont(parent.getFont());
final Composite configurationComposite = new Composite(configurationGroup, SWT.NONE);
configurationComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
GridLayout fileSelectionLayout = new GridLayout();
fileSelectionLayout.numColumns = 3;
fileSelectionLayout.makeColumnsEqualWidth = false;
fileSelectionLayout.marginWidth = 0;
fileSelectionLayout.marginHeight = 0;
configurationComposite.setLayout(fileSelectionLayout);
DefinitionLabelFactory dlf = (DefinitionLabelFactory) PlatformUI.getWorkbench().getService(DefinitionLabelFactory.class);
final Label inputAttributeLabel = new Label(configurationComposite, SWT.NONE);
inputAttributeLabel.setText("Source attribute:");
Control inputAttributeText = dlf.createLabel(configurationComposite, getParent().getSourceItem().getDefinition(), false);
inputAttributeText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
final Label outputAttributeLabel = new Label(configurationComposite, SWT.NONE);
outputAttributeLabel.setText("Target attribute:");
Control outputAttributeText = dlf.createLabel(configurationComposite, getParent().getTargetItem().getDefinition(), false);
outputAttributeText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
final Label expansionExpressionLabel = new Label(configurationComposite, SWT.NONE);
expansionExpressionLabel.setText("Expansion expression:");
// expression
Set<String> variables = new TreeSet<String>();
SchemaItem p = getParent().getSourceItem();
for (SchemaItem var : p.getParent().getChildren()) {
if (Number.class.isAssignableFrom(
var.getPropertyType().getBinding())
|| String.class.isAssignableFrom(
var.getPropertyType().getBinding())) {
variables.add(var.getName().getLocalPart());
}
}
this.expressionEditor = new MathExpressionFieldEditor(
"expression", "=", configurationComposite, variables);
if (this.initialExpression != null && !this.initialExpression.equals("")) {
this.expressionEditor.setStringValue(this.initialExpression);
}
else {
this.expressionEditor.setStringValue("50");
}
this.expressionEditor.setEmptyStringAllowed(false);
this.expressionEditor.setPage(this);
this.expressionEditor.setPropertyChangeListener(new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(FieldEditor.IS_VALID)) {
update();
}
}
});
// re-set the layout because the field editor breaks it and sets its own
configurationComposite.setLayout(fileSelectionLayout);
configurationComposite.layout(true, true);
}
|
diff --git a/src/main/java/org/jboss/loom/tools/report/adapters/IConfigFragmentAdapter.java b/src/main/java/org/jboss/loom/tools/report/adapters/IConfigFragmentAdapter.java
index 296aeaf..ff472ee 100644
--- a/src/main/java/org/jboss/loom/tools/report/adapters/IConfigFragmentAdapter.java
+++ b/src/main/java/org/jboss/loom/tools/report/adapters/IConfigFragmentAdapter.java
@@ -1,24 +1,25 @@
package org.jboss.loom.tools.report.adapters;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.jboss.loom.spi.IConfigFragment;
import org.jboss.loom.tools.report.beans.ConfigFragmentReportBean;
/**
*
* @author Ondrej Zizka, ozizka at redhat.com
*/
public class IConfigFragmentAdapter extends XmlAdapter<ConfigFragmentReportBean, IConfigFragment> {
@Override
public ConfigFragmentReportBean marshal( IConfigFragment fragment ) throws Exception {
+ if( fragment == null ) return null;
return ConfigFragmentReportBean.from( fragment );
}
@Override
public IConfigFragment unmarshal( ConfigFragmentReportBean v ) throws Exception {
throw new UnsupportedOperationException( "Unmarshalling not supported." );
}
}// class
| true | true | public ConfigFragmentReportBean marshal( IConfigFragment fragment ) throws Exception {
return ConfigFragmentReportBean.from( fragment );
}
| public ConfigFragmentReportBean marshal( IConfigFragment fragment ) throws Exception {
if( fragment == null ) return null;
return ConfigFragmentReportBean.from( fragment );
}
|
diff --git a/LNReader/src/com/erakk/lnreader/task/LoadWacTask.java b/LNReader/src/com/erakk/lnreader/task/LoadWacTask.java
index 529437d..9a370c0 100644
--- a/LNReader/src/com/erakk/lnreader/task/LoadWacTask.java
+++ b/LNReader/src/com/erakk/lnreader/task/LoadWacTask.java
@@ -1,95 +1,95 @@
package com.erakk.lnreader.task;
import java.io.FileInputStream;
import android.os.AsyncTask;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.erakk.lnreader.callback.CallbackEventData;
import com.erakk.lnreader.callback.ICallbackEventData;
import com.erakk.lnreader.callback.ICallbackNotifier;
import com.erakk.lnreader.callback.IExtendedCallbackNotifier;
import com.erakk.lnreader.helper.Util;
import com.erakk.lnreader.helper.WebArchiveReader;
public class LoadWacTask extends AsyncTask<Void, ICallbackEventData, AsyncTaskResult<Boolean>> implements ICallbackNotifier {
private static final String TAG = LoadWacTask.class.toString();
private final WebView wv;
private final String wacName;
private final IExtendedCallbackNotifier<AsyncTaskResult<?>> owner;
private final WebArchiveReader wr;
private String source;
public LoadWacTask(IExtendedCallbackNotifier<AsyncTaskResult<?>> owner, WebView wv, String wacName, final WebViewClient client) {
this.wv = wv;
this.wacName = wacName;
this.owner = owner;
wr = new WebArchiveReader() {
@Override
protected void onFinished(WebView webView) {
webView.setWebViewClient(client);
Log.d(TAG, "WAC loaded");
}
};
}
@Override
protected void onPreExecute() {
// executed on UI thread.
owner.downloadListSetup(wacName, wacName, 0, false);
owner.onProgressCallback(new CallbackEventData("", source));
}
@Override
protected AsyncTaskResult<Boolean> doInBackground(Void... arg0) {
return new AsyncTaskResult<Boolean>(loadFromWac(this.wacName));
}
@Override
protected void onProgressUpdate(ICallbackEventData... values) {
owner.onProgressCallback(values[0]);
}
private boolean loadFromWac(String wacName) {
Log.d(TAG, "Loading from WAC: " + wacName);
publishProgress(new CallbackEventData("Loading from WAC: " + wacName, source));
try {
FileInputStream is;
is = new FileInputStream(wacName);
return wr.readWebArchive(is);
} catch (Exception e) {
Log.e(TAG, "Failed to load saved web archive: " + wacName + " Try to use 2nd method.", e);
try {
String rawData = Util.getStringFromFile(wacName);
wv.loadDataWithBaseURL(wacName, rawData, "application/x-webarchive-xml", "UTF-8", null);
} catch (Exception ex) {
- Log.e(TAG, "Failed to load saved web archive: " + wacName, e);
+ Log.e(TAG, "Failed to load saved web archive: " + wacName, ex);
}
}
return false;
}
@Override
protected void onPostExecute(AsyncTaskResult<Boolean> result) {
String message = null;
if (result.getResult()) {
wr.loadToWebView(wv);
message = "Load from: " + wacName;
}
else {
message = "Load WAC Failed";
}
owner.onCompleteCallback(new CallbackEventData(message, source), result);
owner.downloadListSetup(wacName, wacName, 2, result.getError() != null ? true : false);
}
@Override
public void onProgressCallback(ICallbackEventData message) {
publishProgress(message);
}
}
| true | true | private boolean loadFromWac(String wacName) {
Log.d(TAG, "Loading from WAC: " + wacName);
publishProgress(new CallbackEventData("Loading from WAC: " + wacName, source));
try {
FileInputStream is;
is = new FileInputStream(wacName);
return wr.readWebArchive(is);
} catch (Exception e) {
Log.e(TAG, "Failed to load saved web archive: " + wacName + " Try to use 2nd method.", e);
try {
String rawData = Util.getStringFromFile(wacName);
wv.loadDataWithBaseURL(wacName, rawData, "application/x-webarchive-xml", "UTF-8", null);
} catch (Exception ex) {
Log.e(TAG, "Failed to load saved web archive: " + wacName, e);
}
}
return false;
}
| private boolean loadFromWac(String wacName) {
Log.d(TAG, "Loading from WAC: " + wacName);
publishProgress(new CallbackEventData("Loading from WAC: " + wacName, source));
try {
FileInputStream is;
is = new FileInputStream(wacName);
return wr.readWebArchive(is);
} catch (Exception e) {
Log.e(TAG, "Failed to load saved web archive: " + wacName + " Try to use 2nd method.", e);
try {
String rawData = Util.getStringFromFile(wacName);
wv.loadDataWithBaseURL(wacName, rawData, "application/x-webarchive-xml", "UTF-8", null);
} catch (Exception ex) {
Log.e(TAG, "Failed to load saved web archive: " + wacName, ex);
}
}
return false;
}
|
diff --git a/src/com/tactfactory/mda/meta/ClassCompletor.java b/src/com/tactfactory/mda/meta/ClassCompletor.java
index e852f6f9..f210fe70 100644
--- a/src/com/tactfactory/mda/meta/ClassCompletor.java
+++ b/src/com/tactfactory/mda/meta/ClassCompletor.java
@@ -1,144 +1,144 @@
package com.tactfactory.mda.meta;
import java.util.ArrayList;
import java.util.HashMap;
import com.tactfactory.mda.ConsoleUtils;
/** The class ClassCompletor will complete all ClassMetadatas
* with the information it needs from the others ClassMetadatas*/
public class ClassCompletor {
//ArrayList<ClassMetadata> metas_array;
HashMap<String, ClassMetadata> metas = new HashMap<String, ClassMetadata>();
HashMap<String, ClassMetadata> newMetas = new HashMap<String, ClassMetadata>();
public ClassCompletor(HashMap<String, ClassMetadata> metas){
this.metas = metas;
}
public void execute(){
for(ClassMetadata cm : metas.values()){
updateRelations(cm);
}
for (ClassMetadata meta : newMetas.values()) {
this.metas.put(meta.name, meta);
}
}
/**
* Update all the relations in a class
* (actually sets the referenced columns for the target entities)
* @param cm The class owning the relations
*/
private void updateRelations(ClassMetadata cm){
for(FieldMetadata fm : cm.relations.values()){ // For each relation in the class
RelationMetadata rel = fm.relation;
String targetEntity = rel.entity_ref;
if(rel.field_ref.isEmpty()){
ClassMetadata cm_ref = this.metas.get(targetEntity);
ArrayList<FieldMetadata> ids = new ArrayList<FieldMetadata>(cm_ref.ids.values());
for(int i=0;i<ids.size();i++){
rel.field_ref.add(ids.get(i).name);
}
fm.columnDefinition = ids.get(0).type;
}
ConsoleUtils.displayDebug("Relation "+rel.type+" on field "+rel.field+" targets "+rel.entity_ref+"("+rel.field_ref.get(0)+")");
if(rel.type.equals("OneToMany")){ // set inverse relation if it doesn't exists
// Check if relation ManyToOne exists in target entity
ClassMetadata entity_ref = this.metas.get(rel.entity_ref);
// if it doesn't :
if(rel.mappedBy==null){
// Create it
FieldMetadata new_field = new FieldMetadata(cm);
new_field.columnDefinition = "integer";
new_field.hidden = true;
new_field.internal = true;
- new_field.name = cm.name+fm.name+"Internal";
+ new_field.name = cm.name+fm.name+"_Internal";
new_field.columnName = cm.name+"_"+fm.name+"_internal";
new_field.type = cm.name;
new_field.relation = new RelationMetadata();
new_field.relation.entity_ref = cm.name;
for(FieldMetadata id : cm.ids.values())
new_field.relation.field_ref.add(id.name);
new_field.relation.field = new_field.name;
new_field.relation.type = "ManyToOne";
new_field.relation.inversedBy = fm.name;
fm.relation.inversedBy = new_field.name;
entity_ref.fields.put(new_field.name, new_field);
entity_ref.relations.put(new_field.name, new_field);
rel.mappedBy = new_field.name;
}
}
if(rel.type.equals("ManyToMany")){
if(rel.joinTable==null || rel.joinTable.isEmpty()){
if(cm.name.compareTo(rel.entity_ref)>0) // Name JoinTable AtoB where A and B are the entities names ordered by alphabetic order
rel.joinTable = cm.name+"to"+rel.entity_ref;
else
rel.joinTable = rel.entity_ref+"to"+cm.name;
}
if(!this.metas.containsKey(rel.joinTable) && !this.newMetas.containsKey(rel.joinTable)){ // If jointable doesn't exist yet, create it
ConsoleUtils.displayDebug("Association Table => "+rel.joinTable);
ClassMetadata classMeta = new ClassMetadata();
classMeta.name = rel.joinTable;
classMeta.internal = true;
classMeta.space = cm.space;
FieldMetadata id = new FieldMetadata(classMeta);
id.columnDefinition = "integer";
id.type = "integer";
id.name = "id";
id.columnName = id.name;
id.id = true;
classMeta.ids.put("id", id);
classMeta.fields.put("id", id);
FieldMetadata ref1 = generateRefField(cm.name, cm);
RelationMetadata rel1 = new RelationMetadata();
rel1.entity_ref = cm.name;
for(FieldMetadata cmid : cm.ids.values())
rel1.field_ref.add(cmid.name);
rel1.inversedBy = fm.name;
rel1.type = "ManyToOne";
ref1.relation = rel1;
classMeta.fields.put(ref1.name, ref1);
classMeta.relations.put(ref1.name, ref1);
FieldMetadata ref2 = generateRefField(rel.entity_ref, cm);
RelationMetadata rel2 = new RelationMetadata();
rel2.entity_ref = rel.entity_ref;
rel2.field_ref = rel.field_ref;
//rel2.inversedBy = rel.inversedBy;
rel2.type = "ManyToOne";
ref2.relation = rel2;
classMeta.fields.put(ref2.name, ref2);
classMeta.relations.put(ref2.name, ref2);
this.newMetas.put(classMeta.name, classMeta);
}else if(this.newMetas.containsKey(rel.joinTable)){ // Complete it !
ClassMetadata jtable = this.newMetas.get(rel.joinTable);
FieldMetadata relation = jtable.relations.get(cm.name.toLowerCase()+"_id");
relation.relation.inversedBy = fm.name;
}
}
}
}
private static FieldMetadata generateRefField(String name, ClassMetadata owner){
FieldMetadata id = new FieldMetadata(owner);
id.columnDefinition = "integer";
id.type = "integer";
id.name = name.toLowerCase()+"_id";
id.columnName = id.name;
return id;
}
}
| true | true | private void updateRelations(ClassMetadata cm){
for(FieldMetadata fm : cm.relations.values()){ // For each relation in the class
RelationMetadata rel = fm.relation;
String targetEntity = rel.entity_ref;
if(rel.field_ref.isEmpty()){
ClassMetadata cm_ref = this.metas.get(targetEntity);
ArrayList<FieldMetadata> ids = new ArrayList<FieldMetadata>(cm_ref.ids.values());
for(int i=0;i<ids.size();i++){
rel.field_ref.add(ids.get(i).name);
}
fm.columnDefinition = ids.get(0).type;
}
ConsoleUtils.displayDebug("Relation "+rel.type+" on field "+rel.field+" targets "+rel.entity_ref+"("+rel.field_ref.get(0)+")");
if(rel.type.equals("OneToMany")){ // set inverse relation if it doesn't exists
// Check if relation ManyToOne exists in target entity
ClassMetadata entity_ref = this.metas.get(rel.entity_ref);
// if it doesn't :
if(rel.mappedBy==null){
// Create it
FieldMetadata new_field = new FieldMetadata(cm);
new_field.columnDefinition = "integer";
new_field.hidden = true;
new_field.internal = true;
new_field.name = cm.name+fm.name+"Internal";
new_field.columnName = cm.name+"_"+fm.name+"_internal";
new_field.type = cm.name;
new_field.relation = new RelationMetadata();
new_field.relation.entity_ref = cm.name;
for(FieldMetadata id : cm.ids.values())
new_field.relation.field_ref.add(id.name);
new_field.relation.field = new_field.name;
new_field.relation.type = "ManyToOne";
new_field.relation.inversedBy = fm.name;
fm.relation.inversedBy = new_field.name;
entity_ref.fields.put(new_field.name, new_field);
entity_ref.relations.put(new_field.name, new_field);
rel.mappedBy = new_field.name;
}
}
if(rel.type.equals("ManyToMany")){
if(rel.joinTable==null || rel.joinTable.isEmpty()){
if(cm.name.compareTo(rel.entity_ref)>0) // Name JoinTable AtoB where A and B are the entities names ordered by alphabetic order
rel.joinTable = cm.name+"to"+rel.entity_ref;
else
rel.joinTable = rel.entity_ref+"to"+cm.name;
}
if(!this.metas.containsKey(rel.joinTable) && !this.newMetas.containsKey(rel.joinTable)){ // If jointable doesn't exist yet, create it
ConsoleUtils.displayDebug("Association Table => "+rel.joinTable);
ClassMetadata classMeta = new ClassMetadata();
classMeta.name = rel.joinTable;
classMeta.internal = true;
classMeta.space = cm.space;
FieldMetadata id = new FieldMetadata(classMeta);
id.columnDefinition = "integer";
id.type = "integer";
id.name = "id";
id.columnName = id.name;
id.id = true;
classMeta.ids.put("id", id);
classMeta.fields.put("id", id);
FieldMetadata ref1 = generateRefField(cm.name, cm);
RelationMetadata rel1 = new RelationMetadata();
rel1.entity_ref = cm.name;
for(FieldMetadata cmid : cm.ids.values())
rel1.field_ref.add(cmid.name);
rel1.inversedBy = fm.name;
rel1.type = "ManyToOne";
ref1.relation = rel1;
classMeta.fields.put(ref1.name, ref1);
classMeta.relations.put(ref1.name, ref1);
FieldMetadata ref2 = generateRefField(rel.entity_ref, cm);
RelationMetadata rel2 = new RelationMetadata();
rel2.entity_ref = rel.entity_ref;
rel2.field_ref = rel.field_ref;
//rel2.inversedBy = rel.inversedBy;
rel2.type = "ManyToOne";
ref2.relation = rel2;
classMeta.fields.put(ref2.name, ref2);
classMeta.relations.put(ref2.name, ref2);
this.newMetas.put(classMeta.name, classMeta);
}else if(this.newMetas.containsKey(rel.joinTable)){ // Complete it !
ClassMetadata jtable = this.newMetas.get(rel.joinTable);
FieldMetadata relation = jtable.relations.get(cm.name.toLowerCase()+"_id");
relation.relation.inversedBy = fm.name;
}
}
}
}
| private void updateRelations(ClassMetadata cm){
for(FieldMetadata fm : cm.relations.values()){ // For each relation in the class
RelationMetadata rel = fm.relation;
String targetEntity = rel.entity_ref;
if(rel.field_ref.isEmpty()){
ClassMetadata cm_ref = this.metas.get(targetEntity);
ArrayList<FieldMetadata> ids = new ArrayList<FieldMetadata>(cm_ref.ids.values());
for(int i=0;i<ids.size();i++){
rel.field_ref.add(ids.get(i).name);
}
fm.columnDefinition = ids.get(0).type;
}
ConsoleUtils.displayDebug("Relation "+rel.type+" on field "+rel.field+" targets "+rel.entity_ref+"("+rel.field_ref.get(0)+")");
if(rel.type.equals("OneToMany")){ // set inverse relation if it doesn't exists
// Check if relation ManyToOne exists in target entity
ClassMetadata entity_ref = this.metas.get(rel.entity_ref);
// if it doesn't :
if(rel.mappedBy==null){
// Create it
FieldMetadata new_field = new FieldMetadata(cm);
new_field.columnDefinition = "integer";
new_field.hidden = true;
new_field.internal = true;
new_field.name = cm.name+fm.name+"_Internal";
new_field.columnName = cm.name+"_"+fm.name+"_internal";
new_field.type = cm.name;
new_field.relation = new RelationMetadata();
new_field.relation.entity_ref = cm.name;
for(FieldMetadata id : cm.ids.values())
new_field.relation.field_ref.add(id.name);
new_field.relation.field = new_field.name;
new_field.relation.type = "ManyToOne";
new_field.relation.inversedBy = fm.name;
fm.relation.inversedBy = new_field.name;
entity_ref.fields.put(new_field.name, new_field);
entity_ref.relations.put(new_field.name, new_field);
rel.mappedBy = new_field.name;
}
}
if(rel.type.equals("ManyToMany")){
if(rel.joinTable==null || rel.joinTable.isEmpty()){
if(cm.name.compareTo(rel.entity_ref)>0) // Name JoinTable AtoB where A and B are the entities names ordered by alphabetic order
rel.joinTable = cm.name+"to"+rel.entity_ref;
else
rel.joinTable = rel.entity_ref+"to"+cm.name;
}
if(!this.metas.containsKey(rel.joinTable) && !this.newMetas.containsKey(rel.joinTable)){ // If jointable doesn't exist yet, create it
ConsoleUtils.displayDebug("Association Table => "+rel.joinTable);
ClassMetadata classMeta = new ClassMetadata();
classMeta.name = rel.joinTable;
classMeta.internal = true;
classMeta.space = cm.space;
FieldMetadata id = new FieldMetadata(classMeta);
id.columnDefinition = "integer";
id.type = "integer";
id.name = "id";
id.columnName = id.name;
id.id = true;
classMeta.ids.put("id", id);
classMeta.fields.put("id", id);
FieldMetadata ref1 = generateRefField(cm.name, cm);
RelationMetadata rel1 = new RelationMetadata();
rel1.entity_ref = cm.name;
for(FieldMetadata cmid : cm.ids.values())
rel1.field_ref.add(cmid.name);
rel1.inversedBy = fm.name;
rel1.type = "ManyToOne";
ref1.relation = rel1;
classMeta.fields.put(ref1.name, ref1);
classMeta.relations.put(ref1.name, ref1);
FieldMetadata ref2 = generateRefField(rel.entity_ref, cm);
RelationMetadata rel2 = new RelationMetadata();
rel2.entity_ref = rel.entity_ref;
rel2.field_ref = rel.field_ref;
//rel2.inversedBy = rel.inversedBy;
rel2.type = "ManyToOne";
ref2.relation = rel2;
classMeta.fields.put(ref2.name, ref2);
classMeta.relations.put(ref2.name, ref2);
this.newMetas.put(classMeta.name, classMeta);
}else if(this.newMetas.containsKey(rel.joinTable)){ // Complete it !
ClassMetadata jtable = this.newMetas.get(rel.joinTable);
FieldMetadata relation = jtable.relations.get(cm.name.toLowerCase()+"_id");
relation.relation.inversedBy = fm.name;
}
}
}
}
|
diff --git a/src/main/java/org/vosao/jsf/FileBean.java b/src/main/java/org/vosao/jsf/FileBean.java
index 57313b8..c208d2b 100644
--- a/src/main/java/org/vosao/jsf/FileBean.java
+++ b/src/main/java/org/vosao/jsf/FileBean.java
@@ -1,176 +1,176 @@
package org.vosao.jsf;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.vosao.entity.FileEntity;
import org.vosao.entity.FolderEntity;
import org.vosao.servlet.FolderUtil;
import org.vosao.servlet.MimeType;
public class FileBean extends AbstractJSFBean implements Serializable {
private static final long serialVersionUID = 3L;
private static Log log = LogFactory.getLog(FileBean.class);
private FileEntity current;
private FolderEntity folder;
private String id;
private String folderId;
private String content;
public void init() {
initCurrent();
}
private void initCurrent() {
content = "";
current = new FileEntity();
current.setFolderId(folderId);
if (getCurrentId() != null) {
current = getDao().getFileDao().getById(getCurrentId());
if (current != null) {
if (isEditContent()) {
try {
content = new String(getDao().getFileDao()
.getFileContent(current), "UTF-8");
} catch (UnsupportedEncodingException e) {
JSFUtil.addErrorMessage("Encoding error while getting file content");
}
}
}
}
if (current.getFolderId() != null) {
folder = getDao().getFolderDao().getById(current.getFolderId());
}
}
public String cancelEdit() {
return "pretty:folders";
}
- public String update() {
+ public String update() throws UnsupportedEncodingException {
List<String> errors = getBusiness().getFileBusiness()
.validateBeforeUpdate(current);
if (errors.isEmpty()) {
- byte[] data = content.getBytes();
+ byte[] data = content.getBytes("UTF-8");
current.setMdtime(new Date());
current.setSize(data.length);
current.setMimeType(MimeType.getContentTypeByExt(
FolderUtil.getFileExt(current.getFilename())));
getDao().getFileDao().save(current);
getDao().getFileDao().saveFileContent(current, data);
String cacheUrl = getBusiness().getFolderBusiness()
.getFolderPath(folder) + "/" + current.getFilename();
getBusiness().getCache().remove(cacheUrl);
setCurrentId(current.getId());
initCurrent();
JSFUtil.addInfoMessage("File was successfully saved.");
return "pretty:fileUpdate";
}
else {
JSFUtil.addErrorMessages(errors);
return null;
}
}
public void create() {
setCurrentId(null);
initCurrent();
}
public void edit() {
if (id != null) {
setCurrentId(id);
initCurrent();
}
}
public FileEntity getCurrent() {
return current;
}
public void setCurrent(FileEntity current) {
this.current = current;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCurrentId() {
String name = this.getClass().getName() + "currentId";
return (String)JSFUtil.getSessionObject(name);
}
public void setCurrentId(String data) {
String name = this.getClass().getName() + "currentId";
JSFUtil.setSessionObject(name, data);
}
public boolean isEditContent() {
if (current.getId() == null) {
return false;
}
String editExt = getBusiness().getConfigBusiness().getEditExt();
String[] exts = editExt.split(",");
for (String ext : exts) {
if (FolderUtil.getFileExt(current.getFilename()).equals(ext)) {
return true;
}
}
return false;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
private static final String[] IMAGE_EXTENSIONS = {"jpg","jpeg","png","ico",
"gif"};
public boolean isImageContent() {
if (current.getId() == null) {
return false;
}
for (String ext : IMAGE_EXTENSIONS) {
if (FolderUtil.getFileExt(current.getFilename()).equals(ext)) {
return true;
}
}
return false;
}
public String getFileLink() {
if (folder != null) {
return "/file" + getBusiness().getFolderBusiness()
.getFolderPath(folder) + "/" + current.getFilename();
}
return "";
}
public String getFolderId() {
return folderId;
}
public void setFolderId(String folderId) {
this.folderId = folderId;
}
public boolean isEdit() {
return current.getId() != null;
}
}
| false | true | public String update() {
List<String> errors = getBusiness().getFileBusiness()
.validateBeforeUpdate(current);
if (errors.isEmpty()) {
byte[] data = content.getBytes();
current.setMdtime(new Date());
current.setSize(data.length);
current.setMimeType(MimeType.getContentTypeByExt(
FolderUtil.getFileExt(current.getFilename())));
getDao().getFileDao().save(current);
getDao().getFileDao().saveFileContent(current, data);
String cacheUrl = getBusiness().getFolderBusiness()
.getFolderPath(folder) + "/" + current.getFilename();
getBusiness().getCache().remove(cacheUrl);
setCurrentId(current.getId());
initCurrent();
JSFUtil.addInfoMessage("File was successfully saved.");
return "pretty:fileUpdate";
}
else {
JSFUtil.addErrorMessages(errors);
return null;
}
}
| public String update() throws UnsupportedEncodingException {
List<String> errors = getBusiness().getFileBusiness()
.validateBeforeUpdate(current);
if (errors.isEmpty()) {
byte[] data = content.getBytes("UTF-8");
current.setMdtime(new Date());
current.setSize(data.length);
current.setMimeType(MimeType.getContentTypeByExt(
FolderUtil.getFileExt(current.getFilename())));
getDao().getFileDao().save(current);
getDao().getFileDao().saveFileContent(current, data);
String cacheUrl = getBusiness().getFolderBusiness()
.getFolderPath(folder) + "/" + current.getFilename();
getBusiness().getCache().remove(cacheUrl);
setCurrentId(current.getId());
initCurrent();
JSFUtil.addInfoMessage("File was successfully saved.");
return "pretty:fileUpdate";
}
else {
JSFUtil.addErrorMessages(errors);
return null;
}
}
|
diff --git a/source/RMG/PopulateReactions.java b/source/RMG/PopulateReactions.java
index bd5b4f2f..20718554 100644
--- a/source/RMG/PopulateReactions.java
+++ b/source/RMG/PopulateReactions.java
@@ -1,567 +1,571 @@
////////////////////////////////////////////////////////////////////////////////
//
// RMG - Reaction Mechanism Generator
//
// Copyright (c) 2002-2009 Prof. William H. Green ([email protected]) and the
// RMG Team ([email protected])
//
// 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.
//
////////////////////////////////////////////////////////////////////////////////
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.StringTokenizer;
import jing.chem.ChemGraph;
import jing.chem.Species;
import jing.chemParser.ChemParser;
import jing.param.Temperature;
import jing.rxn.ArrheniusKinetics;
import jing.rxn.ArrheniusEPKinetics;
import jing.rxn.Kinetics;
import jing.rxn.LibraryReactionGenerator;
import jing.rxn.PDepIsomer;
import jing.rxn.PDepKineticsEstimator;
import jing.rxn.PDepNetwork;
import jing.rxn.PDepReaction;
import jing.rxn.Reaction;
import jing.rxn.ReactionLibrary;
import jing.rxn.TemplateReactionGenerator;
import jing.rxnSys.ConstantTM;
import jing.rxnSys.CoreEdgeReactionModel;
import jing.rxnSys.FinishController;
import jing.rxnSys.InitialStatus;
import jing.rxnSys.PressureModel;
import jing.rxnSys.RateBasedPDepRME;
import jing.rxnSys.RateBasedRME;
import jing.rxnSys.ReactionModelGenerator;
import jing.rxnSys.ReactionSystem;
import jing.rxnSys.TemperatureModel;
public class PopulateReactions {
/**
* Generates a list of all possible reactions, and their modified Arrhenius
* parameters, between all species supplied in the input file.
*
* The input file's first line should specify the system temperature. The
* line should be formatted as follows:
* Temperature: 500 (K)
* The input (.txt) file should contain a list of species, with the first
* line of each species being a user-defined name for the species and the
* remaining lines containing the graph (in the form of an adjacency list).
* There is no limit on the number of ChemGraphs the user may supply.
*
* The output of the function is two .txt files: PopRxnsOutput_rxns.txt and
* PopRxnsOutput_spcs.txt. The first contains the list of reactions (including
* the modified Arrhenius parameters and RMG-generated comments) and the second
* the list of species (including the ChemGraph) that are involved in the list
* of reactions.
*
* UPDATE by MRH on 10/Jan/2010 - Fixed 2 bugs:
* (1) Module did not report the correct A (pre-exponential factor) for reverse
* reactions (e.g. H+CH4=CH3+H2)
* (2) Module reported the same reaction multiple times (no dupliate catch)
*
* UPDATE by MRH on 7/Apr/2010 - Restructured input file + Added pdep options
* (1) In addition to reporting the non p-dep reaction rates, user will have
* the option to ask for (all) the p-dep networks.
* (2) The structure of the input file closely resembles the input file for
* the RMG module.
*/
public static void main(String[] args) {
initializeSystemProperties();
try {
ChemGraph.readForbiddenStructure();
} catch (IOException e1) {
System.err.println("PopulateReactions cannot locate forbiddenStructures.txt file");
e1.printStackTrace();
}
// Creating a new ReactionModelGenerator so I can set the variable temp4BestKinetics
// and call the new readAndMakePTL and readAndMakePRL methods
ReactionModelGenerator rmg = new ReactionModelGenerator();
rmg.setSpeciesSeed(new LinkedHashSet());
// Set Global.lowTemp and Global.highTemp
// The values of the low/highTemp are not used in the function
// (to the best of my knowledge).
// They are necessary for the instances of additionalKinetics,
// e.g. H2C*-CH2-CH2-CH3 -> H3C-CH2-*CH-CH3
/*
* 7Apr2010:
* The input file will now ask the user for a TemperatureModel
* and PressureModel (same as the RMG module). The Global
* .lowTemperature and .highTemperature will automatically
* be determined
*/
// Global.lowTemperature = new Temperature(300,"K");
// Global.highTemperature = new Temperature(1500,"K");
// Define variable 'speciesSet' to store the species contained in the input file
LinkedHashSet speciesSet = new LinkedHashSet();
// Define variable 'reactions' to store all possible rxns between the species in speciesSet
LinkedHashSet reactions = new LinkedHashSet();
// Define two string variables 'listOfReactions' and 'listOfSpecies'
// These strings will hold the list of rxns (including the structure,
// modified Arrhenius parameters, and source/comments) and the list of
// species (including the chemkin name and graph), respectively
String listOfReactions = "Arrhenius 'A' parameter has units of: mol,cm3,s\n" +
"Arrhenius 'n' parameter is unitless and assumes Tref = 1K\n" +
"Arrhenius 'E' parameter has units of: kcal/mol\n\n";
String listOfSpecies = "";
// Open and read the input file
try {
FileReader fr_input = new FileReader(args[0]);
BufferedReader br_input = new BufferedReader(fr_input);
// Read in the first line of the input file
// This line should hold the temperature of the system, e.g.
// Temperature: 500 (K)
String line = ChemParser.readMeaningfulLine(br_input, true);
/*
* Read max atom types (if they exist)
*/
line = rmg.readMaxAtomTypes(line,br_input);
/*
* Read primary thermo libraries (if they exist)
*/
if (line.toLowerCase().startsWith("primarythermolibrary")) {
rmg.readAndMakePTL(br_input);
}
else {
System.err.println("PopulateReactions: Could not locate the PrimaryThermoLibrary field.\n" +
"Line read was: " + line);
System.exit(0);
}
line = ChemParser.readMeaningfulLine(br_input, true);
// Read primary transport library
if (line.toLowerCase().startsWith("primarytransportlibrary"))
rmg.readAndMakePTransL(br_input);
else {
System.err.println("PopulateReactions: Could not locate the PrimaryTransportLibrary field.\n" +
"Line read was: " + line);
System.exit(0);
}
/*
* Read the temperature model (must be of length one)
*/
line = ChemParser.readMeaningfulLine(br_input, true);
rmg.createTModel(line);
if (rmg.getTempList().size() > 1) {
System.out.println("Please list only one temperature in the TemperatureModel field.");
System.exit(0);
}
/*
* Read the pressure model (must be of length 1)
*/
line = ChemParser.readMeaningfulLine(br_input, true);
rmg.createPModel(line);
if (rmg.getPressList().size() > 1) {
System.out.println("Please list only one pressure in the PressureModel field.");
System.exit(0);
}
/*
* Read the solvation field (if present)
*/
line = ChemParser.readMeaningfulLine(br_input, true);
StringTokenizer st = new StringTokenizer(line);
// The first line should start with "Solvation", otherwise do nothing and display a message to the user
if (st.nextToken().startsWith("Solvation")) {
line = st.nextToken().toLowerCase();
// The options for the "Solvation" field are "on" or "off" (as of 18May2009), otherwise do nothing and display a message to the user
// Note: I use "Species.useInChI" because the "Species.useSolvation" updates were not yet committed.
if (line.equals("on")) {
Species.useSolvation = true;
// rmg.setUseDiffusion(true);
listOfReactions += "Solution-phase chemistry!\n\n";
} else if (line.equals("off")) {
Species.useSolvation = false;
// rmg.setUseDiffusion(false);
listOfReactions += "Gas-phase chemistry.\n\n";
} else {
System.out.println("Error in reading input.txt file:\nThe field 'Solvation' has the options 'on' or 'off'." +
"\nPopulateReactions does not recognize: " + line);
return;
}
line = ChemParser.readMeaningfulLine(br_input, true);
}
/*
* Read in the species (name, concentration, adjacency list)
*/
if (line.toLowerCase().startsWith("speciesstatus")) {
LinkedHashMap lhm = new LinkedHashMap();
lhm = rmg.populateInitialStatusListWithReactiveSpecies(br_input);
speciesSet.addAll(lhm.values());
}
/*
* Read in the inert gas (name, concentration)
*/
line = ChemParser.readMeaningfulLine(br_input, true);
if (line.toLowerCase().startsWith("bathgas")) {
rmg.populateInitialStatusListWithInertSpecies(br_input);
}
/*
* Read in the p-dep options
*/
line = ChemParser.readMeaningfulLine(br_input, true);
if (line.toLowerCase().startsWith("spectroscopicdata")) {
rmg.setSpectroscopicDataMode(line);
line = ChemParser.readMeaningfulLine(br_input, true);
line = rmg.setPressureDependenceOptions(line,br_input);
}
/*
* Read primary kinetic libraries (if they exist)
*/
if (line.toLowerCase().startsWith("primarykineticlibrary")) {
rmg.readAndMakePKL(br_input);
}
else {
System.err.println("PopulateReactions: Could not locate the PrimaryKineticLibrary field." +
"Line read was: " + line);
System.exit(0);
}
line = ChemParser.readMeaningfulLine(br_input, true);
if (line.toLowerCase().startsWith("reactionlibrary")) {
rmg.readAndMakeReactionLibrary(br_input);
}
else {
System.err.println("PopulateReactions: Could not locate the ReactionLibrary field." +
"Line read was: " + line);
System.exit(0);
}
/*
* Read in verbosity field (if it exists)
*/
line = ChemParser.readMeaningfulLine(br_input, true);
if (line != null && line.toLowerCase().startsWith("verbose")) {
StringTokenizer st2 = new StringTokenizer(line);
String tempString = st2.nextToken();
tempString = st2.nextToken();
tempString = tempString.toLowerCase();
if (tempString.equals("on") || tempString.equals("true") || tempString.equals("yes"))
ArrheniusKinetics.setVerbose(true);
}
// Set the user's input temperature
LinkedList tempList = rmg.getTempList();
Temperature systemTemp = ((ConstantTM)tempList.get(0)).getTemperature();
rmg.setTemp4BestKinetics(systemTemp);
TemplateReactionGenerator rtLibrary = new TemplateReactionGenerator();
// Check Reaction Library
ReactionLibrary RL = rmg.getReactionLibrary();
LibraryReactionGenerator lrg1 =new LibraryReactionGenerator(RL);
reactions = lrg1.react(speciesSet);
if ( RL != null ){
System.out.println("Checking Reaction Library "+RL.getName()+" for reactions.");
Iterator ReactionIter = reactions.iterator();
while(ReactionIter.hasNext()){
Reaction current_reaction = (Reaction)ReactionIter.next();
System.out.println("Library Reaction: " +current_reaction.toString() );
}
}
// Add all reactions found from RMG template reaction generator
reactions.addAll(rtLibrary.react(speciesSet));
if (!(rmg.getReactionModelEnlarger() instanceof RateBasedRME)) {
// NOT an instance of RateBasedRME therefore assume RateBasedPDepRME and we're doing pressure dependence
CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(speciesSet, reactions);
rmg.setReactionModel(cerm);
rmg.setReactionGenerator(rtLibrary);
ReactionSystem rs = new ReactionSystem((TemperatureModel)rmg.getTempList().get(0),
(PressureModel)rmg.getPressList().get(0),
rmg.getReactionModelEnlarger(),
new FinishController(),
null,
rmg.getPrimaryKineticLibrary(),
rmg.getReactionGenerator(),
speciesSet,
(InitialStatus)rmg.getInitialStatusList().get(0),
rmg.getReactionModel(),
rmg.getLibraryReactionGenerator(),
0,
"GasPhase");
PDepNetwork.reactionModel = rmg.getReactionModel();
PDepNetwork.reactionSystem = rs;
// If the reaction structure is A + B = C + D, we are not concerned w/pdep
Iterator iter = reactions.iterator();
LinkedHashSet nonPdepReactions = new LinkedHashSet();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() < 2 || r.getProductNumber() < 2){
cerm.categorizeReaction(r.getStructure());
PDepNetwork.addReactionToNetworks(r);
}
else {
nonPdepReactions.add(r);
}
}
// Run fame calculation
PDepKineticsEstimator pDepKineticsEstimator =
((RateBasedPDepRME) rmg.getReactionModelEnlarger()).getPDepKineticsEstimator();
for (int numNetworks=0; numNetworks<PDepNetwork.getNetworks().size(); ++numNetworks) {
PDepNetwork pdepnetwork = PDepNetwork.getNetworks().get(numNetworks);
+ LinkedList isomers = pdepnetwork.getIsomers();
+ for (int numIsomers=0; numIsomers<isomers.size(); ++numIsomers) {
+ pdepnetwork.makeIsomerIncluded((PDepIsomer) isomers.get(numIsomers));
+ }
pDepKineticsEstimator.runPDepCalculation(pdepnetwork,rs,cerm);
LinkedList<PDepReaction> indivPDepRxns = pdepnetwork.getNetReactions();
for (int numPDepRxns=0; numPDepRxns<indivPDepRxns.size(); numPDepRxns++) {
listOfReactions += indivPDepRxns.get(numPDepRxns).toRestartString(systemTemp);
}
LinkedList<PDepReaction> nonIncludedRxns = pdepnetwork.getNonincludedReactions();
for (int numNonRxns=0; numNonRxns<nonIncludedRxns.size(); ++numNonRxns) {
listOfReactions += nonIncludedRxns.get(numNonRxns).toRestartString(systemTemp);
}
LinkedList<PDepIsomer> allpdepisomers = pdepnetwork.getIsomers();
for (int numIsomers=0; numIsomers<allpdepisomers.size(); ++numIsomers) {
LinkedList species = allpdepisomers.get(numIsomers).getSpeciesList();
speciesSet.addAll(species);
}
}
reactions = nonPdepReactions;
}
// Some of the reactions may be duplicates of one another
// (e.g. H+CH4=CH3+H2 as a forward reaction and reverse reaction)
// Create new LinkedHashSet which will store the non-duplicate rxns
LinkedHashSet nonDuplicateRxns = new LinkedHashSet();
int Counter = 0;
Iterator iter_rxns = reactions.iterator();
while (iter_rxns.hasNext()){
++Counter;
Reaction r = (Reaction)iter_rxns.next();
// The first reaction is not a duplicate of any previous reaction
if (Counter == 1) {
nonDuplicateRxns.add(r);
listOfReactions += writeOutputString(r,rtLibrary);
speciesSet.addAll(r.getProductList());
}
// Check whether the current reaction (or its reverse) has the same structure
// of any reactions already reported in the output
else {
Iterator iterOverNonDup = nonDuplicateRxns.iterator();
boolean dupRxn = false;
while (iterOverNonDup.hasNext()) {
Reaction temp_Reaction = (Reaction)iterOverNonDup.next();
if (r.getStructure() == temp_Reaction.getStructure()) {
dupRxn = true;
break;
} else if (r.hasReverseReaction()) {
if (r.getReverseReaction().getStructure() == temp_Reaction.getStructure()) {
dupRxn = true;
break;
}
}
}
if (!dupRxn) {
nonDuplicateRxns.add(r);
// If Reaction is Not a Library Reaction
listOfReactions += writeOutputString(r,rtLibrary);
speciesSet.addAll(r.getProductList());
}
}
}
Iterator iter_species = speciesSet.iterator();
// Define dummy integer 'i' so our getChemGraph().toString()
// call only returns the graph
int i = 0;
while (iter_species.hasNext()) {
Species species = (Species)iter_species.next();
listOfSpecies += species.getName()+"("+species.getID()+")\n" +
species.getChemGraph().toStringWithoutH(i) + "\n";
}
// Write the output files
try{
File rxns = new File("PopRxnsOutput_rxns.txt");
FileWriter fw_rxns = new FileWriter(rxns);
fw_rxns.write(listOfReactions);
fw_rxns.close();
File spcs = new File("PopRxnsOutput_spcs.txt");
FileWriter fw_spcs = new FileWriter(spcs);
fw_spcs.write(listOfSpecies);
fw_spcs.close();
}
catch (IOException e) {
System.out.println("Could not write PopRxnsOutput.txt files");
System.exit(0);
}
// Display to the user that the program was successful and also
// inform them where the results may be located
System.out.println("Reaction population complete. Results are stored"
+ " in PopRxnsOutput_rxns.txt and PopRxnsOutput_spcs.txt");
} catch (FileNotFoundException e) {
System.err.println("File was not found!\n");
} catch(IOException e) {
System.err.println("Something wrong with ChemParser.readChemGraph");
}
}
public static void initializeSystemProperties() {
RMG.globalInitializeSystemProperties();
File GATPFit = new File("GATPFit");
ChemParser.deleteDir(GATPFit);
GATPFit.mkdir();
File frankie = new File("frankie");
ChemParser.deleteDir(frankie);
frankie.mkdir();
File fame = new File("fame");
ChemParser.deleteDir(fame);
fame.mkdir();
};
public static String updateListOfReactions(Kinetics rxn_k, double H_rxn) {
double Ea = 0.0;
if (rxn_k instanceof ArrheniusEPKinetics){
Ea = ((ArrheniusEPKinetics)rxn_k).getEaValue(H_rxn);
}
else{
Ea = rxn_k.getEValue();
}
String output = rxn_k.getAValue() + "\t" + rxn_k.getNValue()
+ "\t" + Ea + "\t" + rxn_k.getSource()
+ "\t" + rxn_k.getComment()
+ "\tdeltaHrxn(T=298K) = " + H_rxn + " kcal/mol\n";
return output;
}
public static String writeOutputString(Reaction r, TemplateReactionGenerator rtLibrary) {
String listOfReactions = "";
Temperature stdtemp = new Temperature(298,"K");
double Hrxn = r.calculateHrxn(stdtemp);
// If r Reaction is from Reaction Library add it to list of reaction append its kinetics and return
String source = r.getKineticsSource(0);
if (source == null){
// If source is null I am assuming that its not a Reaction from Reaction Library or Seed Mechanism
source = "TemplateReaction:";
}
StringTokenizer st = new StringTokenizer(source,":");
String reaction_type = st.nextToken();
// Reactions from Reaction Libraries:
if (reaction_type.equals("ReactionLibrary") ){
// We will get the forward reaction
if(r.isBackward()){
r = r.getReverseReaction();
Hrxn = -Hrxn; // Reversing the heat of reaction
}
Kinetics[] allKinetics = getReactionKinetics(r);
for (int numKinetics=0; numKinetics<allKinetics.length; ++numKinetics) {
listOfReactions += r.toString() + "\t" + updateListOfReactions(allKinetics[numKinetics], Hrxn);
if (allKinetics.length != 1) listOfReactions += "\tDUP\n";
}
return listOfReactions;
}
// Reactions NOT from Reaction Libraries are from Templates:
if (r.isForward()) {
Kinetics[] allKinetics = r.getKinetics();
for (int numKinetics=0; numKinetics<allKinetics.length; ++numKinetics) {
listOfReactions += r.toString() + "\t" + updateListOfReactions(allKinetics[numKinetics], Hrxn);
if (allKinetics.length != 1) listOfReactions += "\tDUP\n";
}
}
else if (r.isBackward()) {
LinkedHashSet reverseReactions = new LinkedHashSet();
Iterator iter2 = r.getStructure().getProducts();
Species species1 = (Species)iter2.next();
Species species2 = species1;
while (iter2.hasNext())
species2 = (Species)iter2.next();
String rxnFamilyName = r.getReverseReaction().getReactionTemplate().getName();
LinkedHashSet speciesHashSet = new LinkedHashSet();
speciesHashSet.add(species1);
reverseReactions = rtLibrary.react(speciesHashSet, species2, rxnFamilyName);
for (Iterator iter3 = reverseReactions.iterator(); iter3.hasNext();) {
Reaction currentRxn = (Reaction)iter3.next();
if (currentRxn.getStructure() == r.getReverseReaction().getStructure()) {
Kinetics[] allKinetics = currentRxn.getKinetics();
for (int numKinetics=0; numKinetics<allKinetics.length; ++numKinetics) {
listOfReactions += currentRxn.toString() + "\t" + updateListOfReactions(allKinetics[numKinetics], -Hrxn);
if (allKinetics.length != 1) listOfReactions += "\tDUP\n";
}
}
}
}
else {
Kinetics[] allKinetics = r.getKinetics();
for (int numKinetics=0; numKinetics<allKinetics.length; ++numKinetics) {
listOfReactions += r.toString() + "\t" + updateListOfReactions(allKinetics[numKinetics], Hrxn);
if (allKinetics.length != 1) listOfReactions += "\tDUP\n";
}
}
return listOfReactions;
}
private static Kinetics[] getReactionKinetics(Reaction r) {
Kinetics[] allKinetics;
if (r.isForward()) {
allKinetics = r.getKinetics();
}
else if (r.isBackward()) {
allKinetics =r.getFittedReverseKinetics();
}
else {
allKinetics = r.getKinetics();
}
return allKinetics;
}
}
| true | true | public static void main(String[] args) {
initializeSystemProperties();
try {
ChemGraph.readForbiddenStructure();
} catch (IOException e1) {
System.err.println("PopulateReactions cannot locate forbiddenStructures.txt file");
e1.printStackTrace();
}
// Creating a new ReactionModelGenerator so I can set the variable temp4BestKinetics
// and call the new readAndMakePTL and readAndMakePRL methods
ReactionModelGenerator rmg = new ReactionModelGenerator();
rmg.setSpeciesSeed(new LinkedHashSet());
// Set Global.lowTemp and Global.highTemp
// The values of the low/highTemp are not used in the function
// (to the best of my knowledge).
// They are necessary for the instances of additionalKinetics,
// e.g. H2C*-CH2-CH2-CH3 -> H3C-CH2-*CH-CH3
/*
* 7Apr2010:
* The input file will now ask the user for a TemperatureModel
* and PressureModel (same as the RMG module). The Global
* .lowTemperature and .highTemperature will automatically
* be determined
*/
// Global.lowTemperature = new Temperature(300,"K");
// Global.highTemperature = new Temperature(1500,"K");
// Define variable 'speciesSet' to store the species contained in the input file
LinkedHashSet speciesSet = new LinkedHashSet();
// Define variable 'reactions' to store all possible rxns between the species in speciesSet
LinkedHashSet reactions = new LinkedHashSet();
// Define two string variables 'listOfReactions' and 'listOfSpecies'
// These strings will hold the list of rxns (including the structure,
// modified Arrhenius parameters, and source/comments) and the list of
// species (including the chemkin name and graph), respectively
String listOfReactions = "Arrhenius 'A' parameter has units of: mol,cm3,s\n" +
"Arrhenius 'n' parameter is unitless and assumes Tref = 1K\n" +
"Arrhenius 'E' parameter has units of: kcal/mol\n\n";
String listOfSpecies = "";
// Open and read the input file
try {
FileReader fr_input = new FileReader(args[0]);
BufferedReader br_input = new BufferedReader(fr_input);
// Read in the first line of the input file
// This line should hold the temperature of the system, e.g.
// Temperature: 500 (K)
String line = ChemParser.readMeaningfulLine(br_input, true);
/*
* Read max atom types (if they exist)
*/
line = rmg.readMaxAtomTypes(line,br_input);
/*
* Read primary thermo libraries (if they exist)
*/
if (line.toLowerCase().startsWith("primarythermolibrary")) {
rmg.readAndMakePTL(br_input);
}
else {
System.err.println("PopulateReactions: Could not locate the PrimaryThermoLibrary field.\n" +
"Line read was: " + line);
System.exit(0);
}
line = ChemParser.readMeaningfulLine(br_input, true);
// Read primary transport library
if (line.toLowerCase().startsWith("primarytransportlibrary"))
rmg.readAndMakePTransL(br_input);
else {
System.err.println("PopulateReactions: Could not locate the PrimaryTransportLibrary field.\n" +
"Line read was: " + line);
System.exit(0);
}
/*
* Read the temperature model (must be of length one)
*/
line = ChemParser.readMeaningfulLine(br_input, true);
rmg.createTModel(line);
if (rmg.getTempList().size() > 1) {
System.out.println("Please list only one temperature in the TemperatureModel field.");
System.exit(0);
}
/*
* Read the pressure model (must be of length 1)
*/
line = ChemParser.readMeaningfulLine(br_input, true);
rmg.createPModel(line);
if (rmg.getPressList().size() > 1) {
System.out.println("Please list only one pressure in the PressureModel field.");
System.exit(0);
}
/*
* Read the solvation field (if present)
*/
line = ChemParser.readMeaningfulLine(br_input, true);
StringTokenizer st = new StringTokenizer(line);
// The first line should start with "Solvation", otherwise do nothing and display a message to the user
if (st.nextToken().startsWith("Solvation")) {
line = st.nextToken().toLowerCase();
// The options for the "Solvation" field are "on" or "off" (as of 18May2009), otherwise do nothing and display a message to the user
// Note: I use "Species.useInChI" because the "Species.useSolvation" updates were not yet committed.
if (line.equals("on")) {
Species.useSolvation = true;
// rmg.setUseDiffusion(true);
listOfReactions += "Solution-phase chemistry!\n\n";
} else if (line.equals("off")) {
Species.useSolvation = false;
// rmg.setUseDiffusion(false);
listOfReactions += "Gas-phase chemistry.\n\n";
} else {
System.out.println("Error in reading input.txt file:\nThe field 'Solvation' has the options 'on' or 'off'." +
"\nPopulateReactions does not recognize: " + line);
return;
}
line = ChemParser.readMeaningfulLine(br_input, true);
}
/*
* Read in the species (name, concentration, adjacency list)
*/
if (line.toLowerCase().startsWith("speciesstatus")) {
LinkedHashMap lhm = new LinkedHashMap();
lhm = rmg.populateInitialStatusListWithReactiveSpecies(br_input);
speciesSet.addAll(lhm.values());
}
/*
* Read in the inert gas (name, concentration)
*/
line = ChemParser.readMeaningfulLine(br_input, true);
if (line.toLowerCase().startsWith("bathgas")) {
rmg.populateInitialStatusListWithInertSpecies(br_input);
}
/*
* Read in the p-dep options
*/
line = ChemParser.readMeaningfulLine(br_input, true);
if (line.toLowerCase().startsWith("spectroscopicdata")) {
rmg.setSpectroscopicDataMode(line);
line = ChemParser.readMeaningfulLine(br_input, true);
line = rmg.setPressureDependenceOptions(line,br_input);
}
/*
* Read primary kinetic libraries (if they exist)
*/
if (line.toLowerCase().startsWith("primarykineticlibrary")) {
rmg.readAndMakePKL(br_input);
}
else {
System.err.println("PopulateReactions: Could not locate the PrimaryKineticLibrary field." +
"Line read was: " + line);
System.exit(0);
}
line = ChemParser.readMeaningfulLine(br_input, true);
if (line.toLowerCase().startsWith("reactionlibrary")) {
rmg.readAndMakeReactionLibrary(br_input);
}
else {
System.err.println("PopulateReactions: Could not locate the ReactionLibrary field." +
"Line read was: " + line);
System.exit(0);
}
/*
* Read in verbosity field (if it exists)
*/
line = ChemParser.readMeaningfulLine(br_input, true);
if (line != null && line.toLowerCase().startsWith("verbose")) {
StringTokenizer st2 = new StringTokenizer(line);
String tempString = st2.nextToken();
tempString = st2.nextToken();
tempString = tempString.toLowerCase();
if (tempString.equals("on") || tempString.equals("true") || tempString.equals("yes"))
ArrheniusKinetics.setVerbose(true);
}
// Set the user's input temperature
LinkedList tempList = rmg.getTempList();
Temperature systemTemp = ((ConstantTM)tempList.get(0)).getTemperature();
rmg.setTemp4BestKinetics(systemTemp);
TemplateReactionGenerator rtLibrary = new TemplateReactionGenerator();
// Check Reaction Library
ReactionLibrary RL = rmg.getReactionLibrary();
LibraryReactionGenerator lrg1 =new LibraryReactionGenerator(RL);
reactions = lrg1.react(speciesSet);
if ( RL != null ){
System.out.println("Checking Reaction Library "+RL.getName()+" for reactions.");
Iterator ReactionIter = reactions.iterator();
while(ReactionIter.hasNext()){
Reaction current_reaction = (Reaction)ReactionIter.next();
System.out.println("Library Reaction: " +current_reaction.toString() );
}
}
// Add all reactions found from RMG template reaction generator
reactions.addAll(rtLibrary.react(speciesSet));
if (!(rmg.getReactionModelEnlarger() instanceof RateBasedRME)) {
// NOT an instance of RateBasedRME therefore assume RateBasedPDepRME and we're doing pressure dependence
CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(speciesSet, reactions);
rmg.setReactionModel(cerm);
rmg.setReactionGenerator(rtLibrary);
ReactionSystem rs = new ReactionSystem((TemperatureModel)rmg.getTempList().get(0),
(PressureModel)rmg.getPressList().get(0),
rmg.getReactionModelEnlarger(),
new FinishController(),
null,
rmg.getPrimaryKineticLibrary(),
rmg.getReactionGenerator(),
speciesSet,
(InitialStatus)rmg.getInitialStatusList().get(0),
rmg.getReactionModel(),
rmg.getLibraryReactionGenerator(),
0,
"GasPhase");
PDepNetwork.reactionModel = rmg.getReactionModel();
PDepNetwork.reactionSystem = rs;
// If the reaction structure is A + B = C + D, we are not concerned w/pdep
Iterator iter = reactions.iterator();
LinkedHashSet nonPdepReactions = new LinkedHashSet();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() < 2 || r.getProductNumber() < 2){
cerm.categorizeReaction(r.getStructure());
PDepNetwork.addReactionToNetworks(r);
}
else {
nonPdepReactions.add(r);
}
}
// Run fame calculation
PDepKineticsEstimator pDepKineticsEstimator =
((RateBasedPDepRME) rmg.getReactionModelEnlarger()).getPDepKineticsEstimator();
for (int numNetworks=0; numNetworks<PDepNetwork.getNetworks().size(); ++numNetworks) {
PDepNetwork pdepnetwork = PDepNetwork.getNetworks().get(numNetworks);
pDepKineticsEstimator.runPDepCalculation(pdepnetwork,rs,cerm);
LinkedList<PDepReaction> indivPDepRxns = pdepnetwork.getNetReactions();
for (int numPDepRxns=0; numPDepRxns<indivPDepRxns.size(); numPDepRxns++) {
listOfReactions += indivPDepRxns.get(numPDepRxns).toRestartString(systemTemp);
}
LinkedList<PDepReaction> nonIncludedRxns = pdepnetwork.getNonincludedReactions();
for (int numNonRxns=0; numNonRxns<nonIncludedRxns.size(); ++numNonRxns) {
listOfReactions += nonIncludedRxns.get(numNonRxns).toRestartString(systemTemp);
}
LinkedList<PDepIsomer> allpdepisomers = pdepnetwork.getIsomers();
for (int numIsomers=0; numIsomers<allpdepisomers.size(); ++numIsomers) {
LinkedList species = allpdepisomers.get(numIsomers).getSpeciesList();
speciesSet.addAll(species);
}
}
reactions = nonPdepReactions;
}
// Some of the reactions may be duplicates of one another
// (e.g. H+CH4=CH3+H2 as a forward reaction and reverse reaction)
// Create new LinkedHashSet which will store the non-duplicate rxns
LinkedHashSet nonDuplicateRxns = new LinkedHashSet();
int Counter = 0;
Iterator iter_rxns = reactions.iterator();
while (iter_rxns.hasNext()){
++Counter;
Reaction r = (Reaction)iter_rxns.next();
// The first reaction is not a duplicate of any previous reaction
if (Counter == 1) {
nonDuplicateRxns.add(r);
listOfReactions += writeOutputString(r,rtLibrary);
speciesSet.addAll(r.getProductList());
}
// Check whether the current reaction (or its reverse) has the same structure
// of any reactions already reported in the output
else {
Iterator iterOverNonDup = nonDuplicateRxns.iterator();
boolean dupRxn = false;
while (iterOverNonDup.hasNext()) {
Reaction temp_Reaction = (Reaction)iterOverNonDup.next();
if (r.getStructure() == temp_Reaction.getStructure()) {
dupRxn = true;
break;
} else if (r.hasReverseReaction()) {
if (r.getReverseReaction().getStructure() == temp_Reaction.getStructure()) {
dupRxn = true;
break;
}
}
}
if (!dupRxn) {
nonDuplicateRxns.add(r);
// If Reaction is Not a Library Reaction
listOfReactions += writeOutputString(r,rtLibrary);
speciesSet.addAll(r.getProductList());
}
}
}
Iterator iter_species = speciesSet.iterator();
// Define dummy integer 'i' so our getChemGraph().toString()
// call only returns the graph
int i = 0;
while (iter_species.hasNext()) {
Species species = (Species)iter_species.next();
listOfSpecies += species.getName()+"("+species.getID()+")\n" +
species.getChemGraph().toStringWithoutH(i) + "\n";
}
// Write the output files
try{
File rxns = new File("PopRxnsOutput_rxns.txt");
FileWriter fw_rxns = new FileWriter(rxns);
fw_rxns.write(listOfReactions);
fw_rxns.close();
File spcs = new File("PopRxnsOutput_spcs.txt");
FileWriter fw_spcs = new FileWriter(spcs);
fw_spcs.write(listOfSpecies);
fw_spcs.close();
}
catch (IOException e) {
System.out.println("Could not write PopRxnsOutput.txt files");
System.exit(0);
}
// Display to the user that the program was successful and also
// inform them where the results may be located
System.out.println("Reaction population complete. Results are stored"
+ " in PopRxnsOutput_rxns.txt and PopRxnsOutput_spcs.txt");
} catch (FileNotFoundException e) {
System.err.println("File was not found!\n");
} catch(IOException e) {
System.err.println("Something wrong with ChemParser.readChemGraph");
}
}
| public static void main(String[] args) {
initializeSystemProperties();
try {
ChemGraph.readForbiddenStructure();
} catch (IOException e1) {
System.err.println("PopulateReactions cannot locate forbiddenStructures.txt file");
e1.printStackTrace();
}
// Creating a new ReactionModelGenerator so I can set the variable temp4BestKinetics
// and call the new readAndMakePTL and readAndMakePRL methods
ReactionModelGenerator rmg = new ReactionModelGenerator();
rmg.setSpeciesSeed(new LinkedHashSet());
// Set Global.lowTemp and Global.highTemp
// The values of the low/highTemp are not used in the function
// (to the best of my knowledge).
// They are necessary for the instances of additionalKinetics,
// e.g. H2C*-CH2-CH2-CH3 -> H3C-CH2-*CH-CH3
/*
* 7Apr2010:
* The input file will now ask the user for a TemperatureModel
* and PressureModel (same as the RMG module). The Global
* .lowTemperature and .highTemperature will automatically
* be determined
*/
// Global.lowTemperature = new Temperature(300,"K");
// Global.highTemperature = new Temperature(1500,"K");
// Define variable 'speciesSet' to store the species contained in the input file
LinkedHashSet speciesSet = new LinkedHashSet();
// Define variable 'reactions' to store all possible rxns between the species in speciesSet
LinkedHashSet reactions = new LinkedHashSet();
// Define two string variables 'listOfReactions' and 'listOfSpecies'
// These strings will hold the list of rxns (including the structure,
// modified Arrhenius parameters, and source/comments) and the list of
// species (including the chemkin name and graph), respectively
String listOfReactions = "Arrhenius 'A' parameter has units of: mol,cm3,s\n" +
"Arrhenius 'n' parameter is unitless and assumes Tref = 1K\n" +
"Arrhenius 'E' parameter has units of: kcal/mol\n\n";
String listOfSpecies = "";
// Open and read the input file
try {
FileReader fr_input = new FileReader(args[0]);
BufferedReader br_input = new BufferedReader(fr_input);
// Read in the first line of the input file
// This line should hold the temperature of the system, e.g.
// Temperature: 500 (K)
String line = ChemParser.readMeaningfulLine(br_input, true);
/*
* Read max atom types (if they exist)
*/
line = rmg.readMaxAtomTypes(line,br_input);
/*
* Read primary thermo libraries (if they exist)
*/
if (line.toLowerCase().startsWith("primarythermolibrary")) {
rmg.readAndMakePTL(br_input);
}
else {
System.err.println("PopulateReactions: Could not locate the PrimaryThermoLibrary field.\n" +
"Line read was: " + line);
System.exit(0);
}
line = ChemParser.readMeaningfulLine(br_input, true);
// Read primary transport library
if (line.toLowerCase().startsWith("primarytransportlibrary"))
rmg.readAndMakePTransL(br_input);
else {
System.err.println("PopulateReactions: Could not locate the PrimaryTransportLibrary field.\n" +
"Line read was: " + line);
System.exit(0);
}
/*
* Read the temperature model (must be of length one)
*/
line = ChemParser.readMeaningfulLine(br_input, true);
rmg.createTModel(line);
if (rmg.getTempList().size() > 1) {
System.out.println("Please list only one temperature in the TemperatureModel field.");
System.exit(0);
}
/*
* Read the pressure model (must be of length 1)
*/
line = ChemParser.readMeaningfulLine(br_input, true);
rmg.createPModel(line);
if (rmg.getPressList().size() > 1) {
System.out.println("Please list only one pressure in the PressureModel field.");
System.exit(0);
}
/*
* Read the solvation field (if present)
*/
line = ChemParser.readMeaningfulLine(br_input, true);
StringTokenizer st = new StringTokenizer(line);
// The first line should start with "Solvation", otherwise do nothing and display a message to the user
if (st.nextToken().startsWith("Solvation")) {
line = st.nextToken().toLowerCase();
// The options for the "Solvation" field are "on" or "off" (as of 18May2009), otherwise do nothing and display a message to the user
// Note: I use "Species.useInChI" because the "Species.useSolvation" updates were not yet committed.
if (line.equals("on")) {
Species.useSolvation = true;
// rmg.setUseDiffusion(true);
listOfReactions += "Solution-phase chemistry!\n\n";
} else if (line.equals("off")) {
Species.useSolvation = false;
// rmg.setUseDiffusion(false);
listOfReactions += "Gas-phase chemistry.\n\n";
} else {
System.out.println("Error in reading input.txt file:\nThe field 'Solvation' has the options 'on' or 'off'." +
"\nPopulateReactions does not recognize: " + line);
return;
}
line = ChemParser.readMeaningfulLine(br_input, true);
}
/*
* Read in the species (name, concentration, adjacency list)
*/
if (line.toLowerCase().startsWith("speciesstatus")) {
LinkedHashMap lhm = new LinkedHashMap();
lhm = rmg.populateInitialStatusListWithReactiveSpecies(br_input);
speciesSet.addAll(lhm.values());
}
/*
* Read in the inert gas (name, concentration)
*/
line = ChemParser.readMeaningfulLine(br_input, true);
if (line.toLowerCase().startsWith("bathgas")) {
rmg.populateInitialStatusListWithInertSpecies(br_input);
}
/*
* Read in the p-dep options
*/
line = ChemParser.readMeaningfulLine(br_input, true);
if (line.toLowerCase().startsWith("spectroscopicdata")) {
rmg.setSpectroscopicDataMode(line);
line = ChemParser.readMeaningfulLine(br_input, true);
line = rmg.setPressureDependenceOptions(line,br_input);
}
/*
* Read primary kinetic libraries (if they exist)
*/
if (line.toLowerCase().startsWith("primarykineticlibrary")) {
rmg.readAndMakePKL(br_input);
}
else {
System.err.println("PopulateReactions: Could not locate the PrimaryKineticLibrary field." +
"Line read was: " + line);
System.exit(0);
}
line = ChemParser.readMeaningfulLine(br_input, true);
if (line.toLowerCase().startsWith("reactionlibrary")) {
rmg.readAndMakeReactionLibrary(br_input);
}
else {
System.err.println("PopulateReactions: Could not locate the ReactionLibrary field." +
"Line read was: " + line);
System.exit(0);
}
/*
* Read in verbosity field (if it exists)
*/
line = ChemParser.readMeaningfulLine(br_input, true);
if (line != null && line.toLowerCase().startsWith("verbose")) {
StringTokenizer st2 = new StringTokenizer(line);
String tempString = st2.nextToken();
tempString = st2.nextToken();
tempString = tempString.toLowerCase();
if (tempString.equals("on") || tempString.equals("true") || tempString.equals("yes"))
ArrheniusKinetics.setVerbose(true);
}
// Set the user's input temperature
LinkedList tempList = rmg.getTempList();
Temperature systemTemp = ((ConstantTM)tempList.get(0)).getTemperature();
rmg.setTemp4BestKinetics(systemTemp);
TemplateReactionGenerator rtLibrary = new TemplateReactionGenerator();
// Check Reaction Library
ReactionLibrary RL = rmg.getReactionLibrary();
LibraryReactionGenerator lrg1 =new LibraryReactionGenerator(RL);
reactions = lrg1.react(speciesSet);
if ( RL != null ){
System.out.println("Checking Reaction Library "+RL.getName()+" for reactions.");
Iterator ReactionIter = reactions.iterator();
while(ReactionIter.hasNext()){
Reaction current_reaction = (Reaction)ReactionIter.next();
System.out.println("Library Reaction: " +current_reaction.toString() );
}
}
// Add all reactions found from RMG template reaction generator
reactions.addAll(rtLibrary.react(speciesSet));
if (!(rmg.getReactionModelEnlarger() instanceof RateBasedRME)) {
// NOT an instance of RateBasedRME therefore assume RateBasedPDepRME and we're doing pressure dependence
CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(speciesSet, reactions);
rmg.setReactionModel(cerm);
rmg.setReactionGenerator(rtLibrary);
ReactionSystem rs = new ReactionSystem((TemperatureModel)rmg.getTempList().get(0),
(PressureModel)rmg.getPressList().get(0),
rmg.getReactionModelEnlarger(),
new FinishController(),
null,
rmg.getPrimaryKineticLibrary(),
rmg.getReactionGenerator(),
speciesSet,
(InitialStatus)rmg.getInitialStatusList().get(0),
rmg.getReactionModel(),
rmg.getLibraryReactionGenerator(),
0,
"GasPhase");
PDepNetwork.reactionModel = rmg.getReactionModel();
PDepNetwork.reactionSystem = rs;
// If the reaction structure is A + B = C + D, we are not concerned w/pdep
Iterator iter = reactions.iterator();
LinkedHashSet nonPdepReactions = new LinkedHashSet();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() < 2 || r.getProductNumber() < 2){
cerm.categorizeReaction(r.getStructure());
PDepNetwork.addReactionToNetworks(r);
}
else {
nonPdepReactions.add(r);
}
}
// Run fame calculation
PDepKineticsEstimator pDepKineticsEstimator =
((RateBasedPDepRME) rmg.getReactionModelEnlarger()).getPDepKineticsEstimator();
for (int numNetworks=0; numNetworks<PDepNetwork.getNetworks().size(); ++numNetworks) {
PDepNetwork pdepnetwork = PDepNetwork.getNetworks().get(numNetworks);
LinkedList isomers = pdepnetwork.getIsomers();
for (int numIsomers=0; numIsomers<isomers.size(); ++numIsomers) {
pdepnetwork.makeIsomerIncluded((PDepIsomer) isomers.get(numIsomers));
}
pDepKineticsEstimator.runPDepCalculation(pdepnetwork,rs,cerm);
LinkedList<PDepReaction> indivPDepRxns = pdepnetwork.getNetReactions();
for (int numPDepRxns=0; numPDepRxns<indivPDepRxns.size(); numPDepRxns++) {
listOfReactions += indivPDepRxns.get(numPDepRxns).toRestartString(systemTemp);
}
LinkedList<PDepReaction> nonIncludedRxns = pdepnetwork.getNonincludedReactions();
for (int numNonRxns=0; numNonRxns<nonIncludedRxns.size(); ++numNonRxns) {
listOfReactions += nonIncludedRxns.get(numNonRxns).toRestartString(systemTemp);
}
LinkedList<PDepIsomer> allpdepisomers = pdepnetwork.getIsomers();
for (int numIsomers=0; numIsomers<allpdepisomers.size(); ++numIsomers) {
LinkedList species = allpdepisomers.get(numIsomers).getSpeciesList();
speciesSet.addAll(species);
}
}
reactions = nonPdepReactions;
}
// Some of the reactions may be duplicates of one another
// (e.g. H+CH4=CH3+H2 as a forward reaction and reverse reaction)
// Create new LinkedHashSet which will store the non-duplicate rxns
LinkedHashSet nonDuplicateRxns = new LinkedHashSet();
int Counter = 0;
Iterator iter_rxns = reactions.iterator();
while (iter_rxns.hasNext()){
++Counter;
Reaction r = (Reaction)iter_rxns.next();
// The first reaction is not a duplicate of any previous reaction
if (Counter == 1) {
nonDuplicateRxns.add(r);
listOfReactions += writeOutputString(r,rtLibrary);
speciesSet.addAll(r.getProductList());
}
// Check whether the current reaction (or its reverse) has the same structure
// of any reactions already reported in the output
else {
Iterator iterOverNonDup = nonDuplicateRxns.iterator();
boolean dupRxn = false;
while (iterOverNonDup.hasNext()) {
Reaction temp_Reaction = (Reaction)iterOverNonDup.next();
if (r.getStructure() == temp_Reaction.getStructure()) {
dupRxn = true;
break;
} else if (r.hasReverseReaction()) {
if (r.getReverseReaction().getStructure() == temp_Reaction.getStructure()) {
dupRxn = true;
break;
}
}
}
if (!dupRxn) {
nonDuplicateRxns.add(r);
// If Reaction is Not a Library Reaction
listOfReactions += writeOutputString(r,rtLibrary);
speciesSet.addAll(r.getProductList());
}
}
}
Iterator iter_species = speciesSet.iterator();
// Define dummy integer 'i' so our getChemGraph().toString()
// call only returns the graph
int i = 0;
while (iter_species.hasNext()) {
Species species = (Species)iter_species.next();
listOfSpecies += species.getName()+"("+species.getID()+")\n" +
species.getChemGraph().toStringWithoutH(i) + "\n";
}
// Write the output files
try{
File rxns = new File("PopRxnsOutput_rxns.txt");
FileWriter fw_rxns = new FileWriter(rxns);
fw_rxns.write(listOfReactions);
fw_rxns.close();
File spcs = new File("PopRxnsOutput_spcs.txt");
FileWriter fw_spcs = new FileWriter(spcs);
fw_spcs.write(listOfSpecies);
fw_spcs.close();
}
catch (IOException e) {
System.out.println("Could not write PopRxnsOutput.txt files");
System.exit(0);
}
// Display to the user that the program was successful and also
// inform them where the results may be located
System.out.println("Reaction population complete. Results are stored"
+ " in PopRxnsOutput_rxns.txt and PopRxnsOutput_spcs.txt");
} catch (FileNotFoundException e) {
System.err.println("File was not found!\n");
} catch(IOException e) {
System.err.println("Something wrong with ChemParser.readChemGraph");
}
}
|
diff --git a/common/cpw/mods/fml/common/ProxyInjector.java b/common/cpw/mods/fml/common/ProxyInjector.java
index 079462ec..b3c4055e 100644
--- a/common/cpw/mods/fml/common/ProxyInjector.java
+++ b/common/cpw/mods/fml/common/ProxyInjector.java
@@ -1,74 +1,74 @@
/*
* The FML Forge Mod Loader suite.
* Copyright (C) 2012 cpw
*
* 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 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
*/
package cpw.mods.fml.common;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Set;
import java.util.logging.Level;
import org.objectweb.asm.Type;
import cpw.mods.fml.common.discovery.ASMDataTable;
import cpw.mods.fml.common.discovery.ASMDataTable.ASMData;
/**
* @author cpw
*
*/
public class ProxyInjector
{
public static void inject(ModContainer mod, ASMDataTable data, Side side)
{
FMLLog.fine("Attempting to inject @SidedProxy classes into %s", mod.getModId());
- Set<ASMData> targets = data.getAnnotationsFor(mod).get(Type.getDescriptor(SidedProxy.class));
+ Set<ASMData> targets = data.getAnnotationsFor(mod).get(SidedProxy.class.getName());
ClassLoader mcl = Loader.instance().getModClassLoader();
for (ASMData targ : targets)
{
try
{
Class<?> proxyTarget = Class.forName(targ.getClassName(), true, mcl);
Field target = proxyTarget.getDeclaredField(targ.getObjectName());
if (target == null)
{
// Impossible?
FMLLog.severe("Attempted to load a proxy type into %s.%s but the field was not found", targ.getClassName(), targ.getObjectName());
throw new LoaderException();
}
String targetType = side.isClient() ? target.getAnnotation(SidedProxy.class).clientSide() : target.getAnnotation(SidedProxy.class).serverSide();
Object proxy=Class.forName(targetType, true, mcl).newInstance();
- if ((target.getModifiers() & Modifier.STATIC) != 0 )
+ if ((target.getModifiers() & Modifier.STATIC) == 0 )
{
FMLLog.severe("Attempted to load a proxy type %s into %s.%s, but the field is not static", targetType, targ.getClassName(), targ.getObjectName());
throw new LoaderException();
}
if (!target.getType().isAssignableFrom(proxy.getClass()))
{
FMLLog.severe("Attempted to load a proxy type %s into %s.%s, but the types don't match", targetType, targ.getClassName(), targ.getObjectName());
throw new LoaderException();
}
target.set(null, proxy);
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "An error occured trying to load a proxy into %s.%s", targ.getAnnotationInfo(), targ.getClassName(), targ.getObjectName());
throw new LoaderException(e);
}
}
}
}
| false | true | public static void inject(ModContainer mod, ASMDataTable data, Side side)
{
FMLLog.fine("Attempting to inject @SidedProxy classes into %s", mod.getModId());
Set<ASMData> targets = data.getAnnotationsFor(mod).get(Type.getDescriptor(SidedProxy.class));
ClassLoader mcl = Loader.instance().getModClassLoader();
for (ASMData targ : targets)
{
try
{
Class<?> proxyTarget = Class.forName(targ.getClassName(), true, mcl);
Field target = proxyTarget.getDeclaredField(targ.getObjectName());
if (target == null)
{
// Impossible?
FMLLog.severe("Attempted to load a proxy type into %s.%s but the field was not found", targ.getClassName(), targ.getObjectName());
throw new LoaderException();
}
String targetType = side.isClient() ? target.getAnnotation(SidedProxy.class).clientSide() : target.getAnnotation(SidedProxy.class).serverSide();
Object proxy=Class.forName(targetType, true, mcl).newInstance();
if ((target.getModifiers() & Modifier.STATIC) != 0 )
{
FMLLog.severe("Attempted to load a proxy type %s into %s.%s, but the field is not static", targetType, targ.getClassName(), targ.getObjectName());
throw new LoaderException();
}
if (!target.getType().isAssignableFrom(proxy.getClass()))
{
FMLLog.severe("Attempted to load a proxy type %s into %s.%s, but the types don't match", targetType, targ.getClassName(), targ.getObjectName());
throw new LoaderException();
}
target.set(null, proxy);
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "An error occured trying to load a proxy into %s.%s", targ.getAnnotationInfo(), targ.getClassName(), targ.getObjectName());
throw new LoaderException(e);
}
}
}
| public static void inject(ModContainer mod, ASMDataTable data, Side side)
{
FMLLog.fine("Attempting to inject @SidedProxy classes into %s", mod.getModId());
Set<ASMData> targets = data.getAnnotationsFor(mod).get(SidedProxy.class.getName());
ClassLoader mcl = Loader.instance().getModClassLoader();
for (ASMData targ : targets)
{
try
{
Class<?> proxyTarget = Class.forName(targ.getClassName(), true, mcl);
Field target = proxyTarget.getDeclaredField(targ.getObjectName());
if (target == null)
{
// Impossible?
FMLLog.severe("Attempted to load a proxy type into %s.%s but the field was not found", targ.getClassName(), targ.getObjectName());
throw new LoaderException();
}
String targetType = side.isClient() ? target.getAnnotation(SidedProxy.class).clientSide() : target.getAnnotation(SidedProxy.class).serverSide();
Object proxy=Class.forName(targetType, true, mcl).newInstance();
if ((target.getModifiers() & Modifier.STATIC) == 0 )
{
FMLLog.severe("Attempted to load a proxy type %s into %s.%s, but the field is not static", targetType, targ.getClassName(), targ.getObjectName());
throw new LoaderException();
}
if (!target.getType().isAssignableFrom(proxy.getClass()))
{
FMLLog.severe("Attempted to load a proxy type %s into %s.%s, but the types don't match", targetType, targ.getClassName(), targ.getObjectName());
throw new LoaderException();
}
target.set(null, proxy);
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "An error occured trying to load a proxy into %s.%s", targ.getAnnotationInfo(), targ.getClassName(), targ.getObjectName());
throw new LoaderException(e);
}
}
}
|
diff --git a/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/internal/util/ASTCache.java b/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/internal/util/ASTCache.java
index f6651c8d..0d527494 100644
--- a/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/internal/util/ASTCache.java
+++ b/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/internal/util/ASTCache.java
@@ -1,155 +1,160 @@
/*
* Copyright (c) 2011, the Dart project authors.
*
* Licensed under the Eclipse Public License v1.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/legal/epl-v10.html
*
* 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.google.dart.tools.core.internal.util;
import com.google.dart.compiler.ast.DartUnit;
import com.google.dart.compiler.ast.LibraryUnit;
import com.google.dart.tools.core.DartCore;
import com.google.dart.tools.core.internal.model.DartLibraryImpl;
import com.google.dart.tools.core.model.CompilationUnit;
import com.google.dart.tools.core.model.DartModelException;
import com.google.dart.tools.core.utilities.compiler.DartCompilerUtilities;
import org.eclipse.core.resources.IResource;
import java.util.HashMap;
/**
* Instances of the class <code>ASTCache</code> maintain a cache of AST structures associated with
* compilation units.
*/
public class ASTCache {
/**
* Instances of the class <code>CacheEntry</code> contain the information being cached about a
* single compilation unit.
*/
private static class CacheEntry {
/**
* The modification stamp of the compilation unit at the time the AST structure was created.
*/
private long modificationStamp;
/**
* The AST structure that was created from the compilation unit.
*/
private DartUnit ast;
/**
* Return <code>true</code> if the AST structure maintained by this entry needs to be
* recomputed. The AST structure needs to be recreated if it does not exist, or if the
* compilation unit has been modified since the AST structure was last created.
*
* @param compilationUnit the compilation unit associated with the entry
* @return <code>true</code> if the AST structure maintained by this entry needs to be
* recomputed
*/
public boolean isStale(CompilationUnit compilationUnit) {
return ast == null || modificationStamp != compilationUnit.getModificationStamp();
}
}
/**
* A table mapping compilation units to the cache entries associated with those units.
*/
private HashMap<CompilationUnit, CacheEntry> entryMap = new HashMap<CompilationUnit, CacheEntry>();
/**
* The number of milliseconds that have been spent parsing source code since the last time that
* the time was requested.
*/
private long timeSpentParsing = 0;
/**
* Flush the contents of the cache.
*/
public void flush() {
entryMap.clear();
}
/**
* Return the number of milliseconds that have been spent parsing source code since the last time
* that the time was requested using this method.
*
* @return the number of milliseconds that have been spent parsing source code
*/
public long getAndResetTimeSpentParsing() {
long result = timeSpentParsing;
timeSpentParsing = 0;
return result;
}
/**
* Return the AST structure corresponding to the contents of the given compilation unit.
*
* @param compilationUnit the compilation unit whose AST structure is to be returned
* @return the AST structure corresponding to the contents of the given compilation unit
*/
public DartUnit getAST(CompilationUnit compilationUnit) {
CacheEntry entry = getOrCreateCacheEntry(compilationUnit);
if (entry.isStale(compilationUnit)) {
entry.ast = null;
DartLibraryImpl library = (DartLibraryImpl) compilationUnit.getLibrary();
if (library == null) {
try {
long startParsing = System.currentTimeMillis();
entry.ast = DartCompilerUtilities.resolveUnit(compilationUnit);
long endParsing = System.currentTimeMillis();
timeSpentParsing += (endParsing - startParsing);
} catch (DartModelException exception) {
DartCore.logError("Could not parse compilation unit " + compilationUnit.getElementName(),
exception);
}
} else {
try {
long startParsing = System.currentTimeMillis();
LibraryUnit libraryUnit = DartCompilerUtilities.resolveLibrary(library, true, null);
long endParsing = System.currentTimeMillis();
timeSpentParsing += (endParsing - startParsing);
if (libraryUnit != null) {
for (CompilationUnit unitInLibrary : library.getCompilationUnits()) {
IResource resource = unitInLibrary.getResource();
if (resource != null && resource.getLocationURI() != null) {
CacheEntry entryInLibrary = getOrCreateCacheEntry(unitInLibrary);
entryInLibrary.ast = libraryUnit.getUnit(resource.getLocationURI().toString());
+ if (entryInLibrary.ast == null) {
+ //TODO ugly hack to work around the fact that the compiler appends the file name to the file URI
+ entryInLibrary.ast = libraryUnit.getUnit(library.getCorrespondingResource().getLocationURI().toString()
+ + "/" + resource.getName());
+ }
}
}
}
} catch (DartModelException exception) {
DartCore.logError("Could not parse library " + library.getResource().getLocation(),
exception);
}
}
}
if (entry.ast != null && entry.ast.isDiet()) {
entry.ast = null;
}
return entry.ast;
}
/**
* Return the cache entry associated with the given compilation unit.
*
* @param compilationUnit the compilation unit whose cache entry is to be returned
* @return the cache entry associated with the given compilation unit
*/
private CacheEntry getOrCreateCacheEntry(CompilationUnit compilationUnit) {
CacheEntry entry = entryMap.get(compilationUnit);
if (entry == null) {
entry = new CacheEntry();
entry.modificationStamp = compilationUnit.getModificationStamp();
entryMap.put(compilationUnit, entry);
}
return entry;
}
}
| true | true | public DartUnit getAST(CompilationUnit compilationUnit) {
CacheEntry entry = getOrCreateCacheEntry(compilationUnit);
if (entry.isStale(compilationUnit)) {
entry.ast = null;
DartLibraryImpl library = (DartLibraryImpl) compilationUnit.getLibrary();
if (library == null) {
try {
long startParsing = System.currentTimeMillis();
entry.ast = DartCompilerUtilities.resolveUnit(compilationUnit);
long endParsing = System.currentTimeMillis();
timeSpentParsing += (endParsing - startParsing);
} catch (DartModelException exception) {
DartCore.logError("Could not parse compilation unit " + compilationUnit.getElementName(),
exception);
}
} else {
try {
long startParsing = System.currentTimeMillis();
LibraryUnit libraryUnit = DartCompilerUtilities.resolveLibrary(library, true, null);
long endParsing = System.currentTimeMillis();
timeSpentParsing += (endParsing - startParsing);
if (libraryUnit != null) {
for (CompilationUnit unitInLibrary : library.getCompilationUnits()) {
IResource resource = unitInLibrary.getResource();
if (resource != null && resource.getLocationURI() != null) {
CacheEntry entryInLibrary = getOrCreateCacheEntry(unitInLibrary);
entryInLibrary.ast = libraryUnit.getUnit(resource.getLocationURI().toString());
}
}
}
} catch (DartModelException exception) {
DartCore.logError("Could not parse library " + library.getResource().getLocation(),
exception);
}
}
}
if (entry.ast != null && entry.ast.isDiet()) {
entry.ast = null;
}
return entry.ast;
}
| public DartUnit getAST(CompilationUnit compilationUnit) {
CacheEntry entry = getOrCreateCacheEntry(compilationUnit);
if (entry.isStale(compilationUnit)) {
entry.ast = null;
DartLibraryImpl library = (DartLibraryImpl) compilationUnit.getLibrary();
if (library == null) {
try {
long startParsing = System.currentTimeMillis();
entry.ast = DartCompilerUtilities.resolveUnit(compilationUnit);
long endParsing = System.currentTimeMillis();
timeSpentParsing += (endParsing - startParsing);
} catch (DartModelException exception) {
DartCore.logError("Could not parse compilation unit " + compilationUnit.getElementName(),
exception);
}
} else {
try {
long startParsing = System.currentTimeMillis();
LibraryUnit libraryUnit = DartCompilerUtilities.resolveLibrary(library, true, null);
long endParsing = System.currentTimeMillis();
timeSpentParsing += (endParsing - startParsing);
if (libraryUnit != null) {
for (CompilationUnit unitInLibrary : library.getCompilationUnits()) {
IResource resource = unitInLibrary.getResource();
if (resource != null && resource.getLocationURI() != null) {
CacheEntry entryInLibrary = getOrCreateCacheEntry(unitInLibrary);
entryInLibrary.ast = libraryUnit.getUnit(resource.getLocationURI().toString());
if (entryInLibrary.ast == null) {
//TODO ugly hack to work around the fact that the compiler appends the file name to the file URI
entryInLibrary.ast = libraryUnit.getUnit(library.getCorrespondingResource().getLocationURI().toString()
+ "/" + resource.getName());
}
}
}
}
} catch (DartModelException exception) {
DartCore.logError("Could not parse library " + library.getResource().getLocation(),
exception);
}
}
}
if (entry.ast != null && entry.ast.isDiet()) {
entry.ast = null;
}
return entry.ast;
}
|
diff --git a/src/main/java/egovframework/com/guruguru/dashboard/state/controller/StateController.java b/src/main/java/egovframework/com/guruguru/dashboard/state/controller/StateController.java
index a5c5b14..6365e22 100644
--- a/src/main/java/egovframework/com/guruguru/dashboard/state/controller/StateController.java
+++ b/src/main/java/egovframework/com/guruguru/dashboard/state/controller/StateController.java
@@ -1,101 +1,101 @@
package egovframework.com.guruguru.dashboard.state.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.common.base.Splitter;
@Controller
@RequestMapping("/state")
public class StateController {
@RequestMapping("/getStateInfo")
@ResponseBody
- public String getStateInfo() {
+ public Map<String, Object> getStateInfo() {
String os = System.getProperty("os.name");
Map<String, Object> map = new HashMap<String, Object>();
if (os.equalsIgnoreCase("linux")) {
getMemroyInfo(map);
}
// System.out.println(System.getProperty("os.name"));
//
// String line = "";
//
// try {
// ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", "vmstat");
// Process proc = pb.start();
//
// BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
//
// while ((line = br.readLine()) != null) {
// Iterator<String> it = Splitter.on(' ').omitEmptyStrings().split(line).iterator();
//
// while (it.hasNext()) {
// System.out.println(it.next());
// }
// }
//
// br.close();
//
// } catch (IOException ioe) {
// throw new RuntimeException(ioe.getMessage());
// }
- return "";
+ return map;
}
private void getMemroyInfo(Map<String, Object> map) {
String memoryInfo = executeProcess("/bin/sh", "-c", "free");
int i = 0;
String[] memInfo = {"memTotal", "memUsed", "memFree", "memShared", "memBuffers"};
Iterator<String> it = Splitter.on(' ').omitEmptyStrings().split(memoryInfo).iterator();
while (it.hasNext()) {
System.out.println(i);
if (i > 10) break;
if (i > 5) {
String value = it.next();
System.out.println("name : " + memInfo[i - 6] + " , value : " + value);
map.put(memInfo[i - 6], value);
}
i++;
}
}
private String executeProcess(String... cmd) {
StringBuffer sb = new StringBuffer();
try {
ProcessBuilder pb = new ProcessBuilder(cmd);
Process proc = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException ioe) {
throw new RuntimeException(ioe.getMessage());
}
return sb.toString();
}
}
| false | true | public String getStateInfo() {
String os = System.getProperty("os.name");
Map<String, Object> map = new HashMap<String, Object>();
if (os.equalsIgnoreCase("linux")) {
getMemroyInfo(map);
}
// System.out.println(System.getProperty("os.name"));
//
// String line = "";
//
// try {
// ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", "vmstat");
// Process proc = pb.start();
//
// BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
//
// while ((line = br.readLine()) != null) {
// Iterator<String> it = Splitter.on(' ').omitEmptyStrings().split(line).iterator();
//
// while (it.hasNext()) {
// System.out.println(it.next());
// }
// }
//
// br.close();
//
// } catch (IOException ioe) {
// throw new RuntimeException(ioe.getMessage());
// }
return "";
}
| public Map<String, Object> getStateInfo() {
String os = System.getProperty("os.name");
Map<String, Object> map = new HashMap<String, Object>();
if (os.equalsIgnoreCase("linux")) {
getMemroyInfo(map);
}
// System.out.println(System.getProperty("os.name"));
//
// String line = "";
//
// try {
// ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", "vmstat");
// Process proc = pb.start();
//
// BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
//
// while ((line = br.readLine()) != null) {
// Iterator<String> it = Splitter.on(' ').omitEmptyStrings().split(line).iterator();
//
// while (it.hasNext()) {
// System.out.println(it.next());
// }
// }
//
// br.close();
//
// } catch (IOException ioe) {
// throw new RuntimeException(ioe.getMessage());
// }
return map;
}
|
diff --git a/modules/org.restlet/src/org/restlet/engine/io/IoUtils.java b/modules/org.restlet/src/org/restlet/engine/io/IoUtils.java
index 7d07edd4e..7ea7256ad 100644
--- a/modules/org.restlet/src/org/restlet/engine/io/IoUtils.java
+++ b/modules/org.restlet/src/org/restlet/engine/io/IoUtils.java
@@ -1,77 +1,77 @@
/**
* Copyright 2005-2010 Noelios Technologies.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
* "Licenses"). You can select the license that you prefer but you may not use
* this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1.php
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1.php
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.engine.io;
import java.io.BufferedReader;
/**
* IO manipulation utilities.
*
* @author Thierry Boileau
*/
public class IoUtils {
/** The buffer size. */
public static final int BUFFER_SIZE = 8192;
/** The number of milliseconds after which IO operation will time out. */
public static final int IO_TIMEOUT = 60000;
/**
* Returns the size to use when instantiating buffered items such as
* instances of the {@link BufferedReader} class. It looks for the System
* property "org.restlet.engine.io.buffer.size" and if not defined, uses the
* {@link #BUFFER_SIZE}.
*
* @return The size to use when instantiating buffered items.
*/
public static int getBufferSize() {
int result = BUFFER_SIZE;
// [ifndef gwt]
try {
- result = Integer.parseInt(System.getProperties().getProperty(
- "org.restlet.engine.io.buffer.size"));
+ result = Integer.parseInt(System
+ .getProperty("org.restlet.engine.io.buffer.size"));
} catch (NumberFormatException nfe) {
result = BUFFER_SIZE;
}
// [enddef]
return result;
}
/**
* Private constructor to ensure that the class acts as a true utility class
* i.e. it isn't instantiable and extensible.
*/
private IoUtils() {
}
}
| true | true | public static int getBufferSize() {
int result = BUFFER_SIZE;
// [ifndef gwt]
try {
result = Integer.parseInt(System.getProperties().getProperty(
"org.restlet.engine.io.buffer.size"));
} catch (NumberFormatException nfe) {
result = BUFFER_SIZE;
}
// [enddef]
return result;
}
| public static int getBufferSize() {
int result = BUFFER_SIZE;
// [ifndef gwt]
try {
result = Integer.parseInt(System
.getProperty("org.restlet.engine.io.buffer.size"));
} catch (NumberFormatException nfe) {
result = BUFFER_SIZE;
}
// [enddef]
return result;
}
|
diff --git a/src/com/atlan1/mctpo/mobile/MainGamePanel.java b/src/com/atlan1/mctpo/mobile/MainGamePanel.java
index 3e005a1..92ed6be 100644
--- a/src/com/atlan1/mctpo/mobile/MainGamePanel.java
+++ b/src/com/atlan1/mctpo/mobile/MainGamePanel.java
@@ -1,206 +1,207 @@
package com.atlan1.mctpo.mobile;
import com.atlan1.mctpo.mobile.Inventory.Inventory;
import com.atlan1.mctpo.mobile.Inventory.Slot;
import android.content.Context;
import android.graphics.Canvas;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.graphics.*;
public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback {
private GameThread gThread;
int mode = 0;
int rmode = 0;
Paint p = new Paint();
int frames;
int fps;
long countTime = System.nanoTime();
int pointerBuildId = -1;
int pointerFingerId = -1;
public MainGamePanel(Context context) {
super(context);
// adding the callback (this) to the surface holder to intercept events
getHolder().addCallback(this);
gThread = new GameThread(getHolder(), this);
setFocusable(true);
p.setARGB(255, 255, 255, 255);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Canvas canvas = null;
try {
// try locking the canvas for exclusive pixel editing on the surface
canvas = getHolder().lockCanvas();
canvas.drawARGB(255, 0, 0, 0);
canvas.drawText("Loading...", 30, 60, p);
synchronized (this) {
// update game state
// draws the canvas on the panel
onDraw(canvas);
}
} catch(Exception e) {
e.printStackTrace();
} finally {
// in case of an exception the surface is not left in
// an inconsistent state
if (canvas != null) {
getHolder().unlockCanvasAndPost(canvas);
}
}
if (gThread.getState() == Thread.State.TERMINATED) {
gThread = new GameThread(getHolder(), this);
gThread.setRunning(true);
gThread.start();
}
else {
gThread.setRunning(true);
gThread.start();
}
/*gThread.setRunning(true);
Log.d("alive", String.valueOf(gThread.isAlive()));
if (!gThread.isAlive()) {
gThread.start();
}*/
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
gThread.setRunning(false);
boolean retry = true;
while (retry) {
try {
gThread.join();
retry = false;
} catch (InterruptedException e) {
// try again shutting down the thread
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
synchronized (this) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
float eventX = event.getX();
float eventY = event.getY();
Slot[] slots = MCTPO.character.inventory.slots;
if ((eventX >= MCTPO.size.width - Character.modeButtonSize && eventX <= MCTPO.size.width && eventY >= 0 && eventY <= Character.modeButtonSize)) {
MCTPO.character.buildMode = MCTPO.character.buildMode.getNext();
return true;
}
if (MCTPO.character.inventory.inflated) {
for (int i = 0; i < slots.length; i++) {
if (slots[i].contains(eventX, eventY)) {
MCTPO.character.inventory.selected = i;
return true;
}
}
}
if (Inventory.inflateButtonRect.contains((int) eventX, (int) eventY)) {
MCTPO.character.inventory.inflated = !MCTPO.character.inventory.inflated;
+ return true;
}
if (Math.sqrt(Math.pow((this.getWidth() / 2 - eventX) / MCTPO.pixelSize, 2) + Math.pow((this.getHeight() / 2 - eventY) / MCTPO.pixelSize, 2)) > 60) {
MCTPO.fingerDownP.x = event.getX();
MCTPO.fingerDownP.y = event.getY();
MCTPO.fingerP.x = MCTPO.fingerDownP.x;
MCTPO.fingerP.y = MCTPO.fingerDownP.y;
//MCTPO.lastFingerP = MCTPO.fingerP;
MCTPO.fingerDown = true;
return true;
} else {
MCTPO.fingerBuildDownP.x = event.getX();
MCTPO.fingerBuildDownP.y = event.getY();
MCTPO.fingerBuildP.x = MCTPO.fingerBuildDownP.x;
MCTPO.fingerBuildP.y = MCTPO.fingerBuildDownP.y;
MCTPO.fingerBuildDown = true;
MCTPO.fingerBuildMoved = false;
return true;
}
case MotionEvent.ACTION_UP:
if (MCTPO.fingerDown) {
MCTPO.fingerDown = false;
MCTPO.fingerDownP.x = -1;
MCTPO.fingerDownP.y = -1;
//MCTPO.lastFingerP.x = -1;
//MCTPO.lastFingerP.y = -1;
MCTPO.fingerP.x = -1;
MCTPO.fingerP.y = -1;
return true;
} else if (MCTPO.fingerBuildDown) {
MCTPO.fingerBuildDown = false;
MCTPO.fingerBuildP.x = -1;
MCTPO.fingerBuildP.y = -1;
return true;
}
case MotionEvent.ACTION_MOVE:
if (MCTPO.fingerDown) {
//MCTPO.lastFingerP = MCTPO.fingerP;
MCTPO.fingerP.x = event.getX();
MCTPO.fingerP.y = event.getY();
return true;
} else if (MCTPO.fingerBuildDown) {
MCTPO.fingerBuildP.x = event.getX();
MCTPO.fingerBuildP.y = event.getY();
MCTPO.fingerBuildMoved = true;
return true;
}
}
/*try {
//this.wait(1000L);
Thread.sleep(15);
} catch (InterruptedException e) {
}*/
}
return true;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawText("fps: " + fps, 30, 30, p);
frames ++;
if (System.nanoTime() - countTime > 1000000000) {
fps = frames;
frames = 0;
countTime = System.nanoTime();
Log.d("fps", "fps: " + fps);
}
}
}
| true | true | public boolean onTouchEvent(MotionEvent event) {
synchronized (this) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
float eventX = event.getX();
float eventY = event.getY();
Slot[] slots = MCTPO.character.inventory.slots;
if ((eventX >= MCTPO.size.width - Character.modeButtonSize && eventX <= MCTPO.size.width && eventY >= 0 && eventY <= Character.modeButtonSize)) {
MCTPO.character.buildMode = MCTPO.character.buildMode.getNext();
return true;
}
if (MCTPO.character.inventory.inflated) {
for (int i = 0; i < slots.length; i++) {
if (slots[i].contains(eventX, eventY)) {
MCTPO.character.inventory.selected = i;
return true;
}
}
}
if (Inventory.inflateButtonRect.contains((int) eventX, (int) eventY)) {
MCTPO.character.inventory.inflated = !MCTPO.character.inventory.inflated;
}
if (Math.sqrt(Math.pow((this.getWidth() / 2 - eventX) / MCTPO.pixelSize, 2) + Math.pow((this.getHeight() / 2 - eventY) / MCTPO.pixelSize, 2)) > 60) {
MCTPO.fingerDownP.x = event.getX();
MCTPO.fingerDownP.y = event.getY();
MCTPO.fingerP.x = MCTPO.fingerDownP.x;
MCTPO.fingerP.y = MCTPO.fingerDownP.y;
//MCTPO.lastFingerP = MCTPO.fingerP;
MCTPO.fingerDown = true;
return true;
} else {
MCTPO.fingerBuildDownP.x = event.getX();
MCTPO.fingerBuildDownP.y = event.getY();
MCTPO.fingerBuildP.x = MCTPO.fingerBuildDownP.x;
MCTPO.fingerBuildP.y = MCTPO.fingerBuildDownP.y;
MCTPO.fingerBuildDown = true;
MCTPO.fingerBuildMoved = false;
return true;
}
case MotionEvent.ACTION_UP:
if (MCTPO.fingerDown) {
MCTPO.fingerDown = false;
MCTPO.fingerDownP.x = -1;
MCTPO.fingerDownP.y = -1;
//MCTPO.lastFingerP.x = -1;
//MCTPO.lastFingerP.y = -1;
MCTPO.fingerP.x = -1;
MCTPO.fingerP.y = -1;
return true;
} else if (MCTPO.fingerBuildDown) {
MCTPO.fingerBuildDown = false;
MCTPO.fingerBuildP.x = -1;
MCTPO.fingerBuildP.y = -1;
return true;
}
case MotionEvent.ACTION_MOVE:
if (MCTPO.fingerDown) {
//MCTPO.lastFingerP = MCTPO.fingerP;
MCTPO.fingerP.x = event.getX();
MCTPO.fingerP.y = event.getY();
return true;
} else if (MCTPO.fingerBuildDown) {
MCTPO.fingerBuildP.x = event.getX();
MCTPO.fingerBuildP.y = event.getY();
MCTPO.fingerBuildMoved = true;
return true;
}
}
/*try {
//this.wait(1000L);
Thread.sleep(15);
} catch (InterruptedException e) {
}*/
}
| public boolean onTouchEvent(MotionEvent event) {
synchronized (this) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
float eventX = event.getX();
float eventY = event.getY();
Slot[] slots = MCTPO.character.inventory.slots;
if ((eventX >= MCTPO.size.width - Character.modeButtonSize && eventX <= MCTPO.size.width && eventY >= 0 && eventY <= Character.modeButtonSize)) {
MCTPO.character.buildMode = MCTPO.character.buildMode.getNext();
return true;
}
if (MCTPO.character.inventory.inflated) {
for (int i = 0; i < slots.length; i++) {
if (slots[i].contains(eventX, eventY)) {
MCTPO.character.inventory.selected = i;
return true;
}
}
}
if (Inventory.inflateButtonRect.contains((int) eventX, (int) eventY)) {
MCTPO.character.inventory.inflated = !MCTPO.character.inventory.inflated;
return true;
}
if (Math.sqrt(Math.pow((this.getWidth() / 2 - eventX) / MCTPO.pixelSize, 2) + Math.pow((this.getHeight() / 2 - eventY) / MCTPO.pixelSize, 2)) > 60) {
MCTPO.fingerDownP.x = event.getX();
MCTPO.fingerDownP.y = event.getY();
MCTPO.fingerP.x = MCTPO.fingerDownP.x;
MCTPO.fingerP.y = MCTPO.fingerDownP.y;
//MCTPO.lastFingerP = MCTPO.fingerP;
MCTPO.fingerDown = true;
return true;
} else {
MCTPO.fingerBuildDownP.x = event.getX();
MCTPO.fingerBuildDownP.y = event.getY();
MCTPO.fingerBuildP.x = MCTPO.fingerBuildDownP.x;
MCTPO.fingerBuildP.y = MCTPO.fingerBuildDownP.y;
MCTPO.fingerBuildDown = true;
MCTPO.fingerBuildMoved = false;
return true;
}
case MotionEvent.ACTION_UP:
if (MCTPO.fingerDown) {
MCTPO.fingerDown = false;
MCTPO.fingerDownP.x = -1;
MCTPO.fingerDownP.y = -1;
//MCTPO.lastFingerP.x = -1;
//MCTPO.lastFingerP.y = -1;
MCTPO.fingerP.x = -1;
MCTPO.fingerP.y = -1;
return true;
} else if (MCTPO.fingerBuildDown) {
MCTPO.fingerBuildDown = false;
MCTPO.fingerBuildP.x = -1;
MCTPO.fingerBuildP.y = -1;
return true;
}
case MotionEvent.ACTION_MOVE:
if (MCTPO.fingerDown) {
//MCTPO.lastFingerP = MCTPO.fingerP;
MCTPO.fingerP.x = event.getX();
MCTPO.fingerP.y = event.getY();
return true;
} else if (MCTPO.fingerBuildDown) {
MCTPO.fingerBuildP.x = event.getX();
MCTPO.fingerBuildP.y = event.getY();
MCTPO.fingerBuildMoved = true;
return true;
}
}
/*try {
//this.wait(1000L);
Thread.sleep(15);
} catch (InterruptedException e) {
}*/
}
|
diff --git a/jboss-5/src/main/java/org/mobicents/ha/javax/sip/SipStackImpl.java b/jboss-5/src/main/java/org/mobicents/ha/javax/sip/SipStackImpl.java
index 6abab0b..727dec0 100644
--- a/jboss-5/src/main/java/org/mobicents/ha/javax/sip/SipStackImpl.java
+++ b/jboss-5/src/main/java/org/mobicents/ha/javax/sip/SipStackImpl.java
@@ -1,110 +1,110 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.ha.javax.sip;
import gov.nist.core.CommonLogger;
import gov.nist.core.StackLogger;
import gov.nist.javax.sip.stack.MessageProcessor;
import java.util.Properties;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.sip.PeerUnavailableException;
import javax.sip.ProviderDoesNotExistException;
import javax.sip.SipException;
import org.mobicents.ha.javax.sip.cache.SipCache;
/**
* This class extends the ClusteredSipStack to provide an implementation backed by JBoss Cache 3.X
*
* @author [email protected]
*
*/
public class SipStackImpl extends ClusteredSipStackImpl implements SipStackImplMBean, NotificationListener {
private static StackLogger logger = CommonLogger.getLogger(SipStackImpl.class);
public static String LOG4J_SERVICE_MBEAN_NAME = "jboss.system:service=Logging,type=Log4jService";
public SipStackImpl(Properties configurationProperties) throws PeerUnavailableException {
super(updateConfigProperties(configurationProperties));
}
@Override
public void start() throws ProviderDoesNotExistException, SipException {
super.start();
try {
- if(logger.isLoggingEnabled(StackLogger.TRACE_INFO)) {
- logger.logInfo("Adding notification listener for logging mbean \"" + LOG4J_SERVICE_MBEAN_NAME + "\" to server " + getMBeanServer());
+ if(logger.isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
+ logger.logDebug("Adding notification listener for logging mbean \"" + LOG4J_SERVICE_MBEAN_NAME + "\" to server " + getMBeanServer());
}
getMBeanServer().addNotificationListener(new ObjectName(LOG4J_SERVICE_MBEAN_NAME), this, null, null);
} catch (Exception e) {
logger.logWarning("Could not register the stack as a Notification Listener of " + LOG4J_SERVICE_MBEAN_NAME + " runtime changes to log4j.xml won't affect SIP Stack Logging");
}
}
private static final Properties updateConfigProperties(Properties configurationProperties) {
if(configurationProperties.getProperty(ClusteredSipStack.CACHE_CLASS_NAME_PROPERTY) == null) {
configurationProperties.setProperty(ClusteredSipStack.CACHE_CLASS_NAME_PROPERTY, SipCache.SIP_DEFAULT_CACHE_CLASS_NAME);
}
return configurationProperties;
}
public int getNumberOfClientTransactions() {
return getClientTransactionTableSize();
}
public int getNumberOfDialogs() {
return dialogTable.size();
}
public int getNumberOfEarlyDialogs() {
return earlyDialogTable.size();
}
public int getNumberOfServerTransactions() {
return getServerTransactionTableSize();
}
public boolean isLocalMode() {
return getSipCache().inLocalMode();
}
/*
* (non-Javadoc)
* @see org.mobicents.ha.javax.sip.ClusteredSipStack#passivateDialog(org.mobicents.ha.javax.sip.HASipDialog)
*/
public void passivateDialog(HASipDialog dialog) {
String dialogId = dialog.getDialogIdToReplicate();
sipCache.evictDialog(dialogId);
String mergeId = dialog.getMergeId();
if (mergeId != null) {
serverDialogMergeTestTable.remove(mergeId);
}
dialogTable.remove(dialogId);
}
public MessageProcessor[] getStackMessageProcessors() {
return getMessageProcessors();
}
}
| true | true | public void start() throws ProviderDoesNotExistException, SipException {
super.start();
try {
if(logger.isLoggingEnabled(StackLogger.TRACE_INFO)) {
logger.logInfo("Adding notification listener for logging mbean \"" + LOG4J_SERVICE_MBEAN_NAME + "\" to server " + getMBeanServer());
}
getMBeanServer().addNotificationListener(new ObjectName(LOG4J_SERVICE_MBEAN_NAME), this, null, null);
} catch (Exception e) {
logger.logWarning("Could not register the stack as a Notification Listener of " + LOG4J_SERVICE_MBEAN_NAME + " runtime changes to log4j.xml won't affect SIP Stack Logging");
}
}
| public void start() throws ProviderDoesNotExistException, SipException {
super.start();
try {
if(logger.isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
logger.logDebug("Adding notification listener for logging mbean \"" + LOG4J_SERVICE_MBEAN_NAME + "\" to server " + getMBeanServer());
}
getMBeanServer().addNotificationListener(new ObjectName(LOG4J_SERVICE_MBEAN_NAME), this, null, null);
} catch (Exception e) {
logger.logWarning("Could not register the stack as a Notification Listener of " + LOG4J_SERVICE_MBEAN_NAME + " runtime changes to log4j.xml won't affect SIP Stack Logging");
}
}
|
diff --git a/src/awana/database/Book.java b/src/awana/database/Book.java
index 9067944..2977037 100644
--- a/src/awana/database/Book.java
+++ b/src/awana/database/Book.java
@@ -1,219 +1,219 @@
package awana.database;
import static awana.database.DatabaseWrapper.bookPrefix;
import static awana.database.DatabaseWrapper.completedPostfix;
import static awana.database.DatabaseWrapper.datePostfix;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JSeparator;
/**
*
* @author Renlar
*/
public final class Book implements ItemListener {
public static final String[] bookNames = {
"T&T_Ultimate Adventure 1", "T&T_Ultimate Adventure 2", "T&T_Ultimate Challenge 1", "T&T_Ultimate Challenge 2",
"Trek_Treck Check", "Trek_Roadsign Series", "Trek_Dashboard Series", "Trek_Billboard Series",
"Journey_Faith Foundations", "Journey_Main Study 1", "Journey_Elective 1", "Journey_Main Study 2",
"Journey_Elective 2", "Journey_Main Study 3", "Journey_Elective 3", "Journey_Main Study 4","Journey_Elective 4",
"Journey_Bible Reading"
};
public static final String[][] bookSections = {
//1
{"Discovery 1", "Discovery 2", "Discovery 3", "Discovery 4", "Discovery 5", "Discovery 6", "Discovery 7", "Discovery 8"},
//2
{"Discovery 1", "Discovery 2", "Discovery 3", "Discovery 4", "Discovery 5", "Discovery 6", "Discovery 7", "Discovery 8"},
//3
{"Discovery 1", "Discovery 2", "Discovery 3", "Discovery 4", "Discovery 5", "Discovery 6", "Discovery 7", "Discovery 8"},
//4
{"Discovery 1", "Discovery 2", "Discovery 3", "Discovery 4", "Discovery 5", "Discovery 6", "Discovery 7", "Discovery 8"},
//5
{""},
//6
{"Lesson 1", "Lesson 2", "Lesson 3", "Lesson 4", "Lesson 5", "Lesson 6", "Oasis 1",
"Lesson 7", "Lesson 8", "Lesson 9", "Lesson 10", "Lesson 11", "Lesson 12", "Oasis 2"},
//7
{"Lesson 1", "Lesson 2", "Lesson 3", "Lesson 4", "Lesson 5", "Lesson 6", "Oasis 1",
"Lesson 7", "Lesson 8", "Lesson 9", "Lesson 10", "Lesson 11", "Lesson 12", "Oasis 2"},
//8
{"Lesson 1", "Lesson 2", "Lesson 3", "Lesson 4", "Lesson 5", "Lesson 6", "Oasis 1",
"Lesson 7", "Lesson 8", "Lesson 9", "Lesson 10", "Lesson 11", "Lesson 12", "Oasis 2"},
//9
{""},
//10
{"Lesson 1", "Lesson 2", "Lesson 3", "Lesson 4", "Lesson 5", "Lesson 6", "Review 1-6",
"Lesson 7", "Lesson 8", "Lesson 9", "Lesson 10", "Lesson 11", "Lesson 12", "Review 7-12"},
//11
{"Lesson 1", "Lesson 2", "Lesson 3", "Lesson 4", "Lesson 5", "Lesson 6", "Review 1-6",
"Lesson 7", "Lesson 8", "Lesson 9", "Lesson 10", "Lesson 11", "Lesson 12", "Review 7-12"},
//12
{"Lesson 1", "Lesson 2", "Lesson 3", "Lesson 4", "Lesson 5", "Lesson 6", "Review 1-6",
"Lesson 7", "Lesson 8", "Lesson 9", "Lesson 10", "Lesson 11", "Lesson 12", "Review 7-12"},
//13
{"Lesson 1", "Lesson 2", "Lesson 3", "Lesson 4", "Lesson 5", "Lesson 6", "Review 1-6",
"Lesson 7", "Lesson 8", "Lesson 9", "Lesson 10", "Lesson 11", "Lesson 12", "Review 7-12"},
//14
{"Lesson 1", "Lesson 2", "Lesson 3", "Lesson 4", "Lesson 5", "Lesson 6", "Review 1-6",
"Lesson 7", "Lesson 8", "Lesson 9", "Lesson 10", "Lesson 11", "Lesson 12", "Review 7-12"},
//15
{"Lesson 1", "Lesson 2", "Lesson 3", "Lesson 4", "Lesson 5", "Lesson 6", "Review 1-6",
"Lesson 7", "Lesson 8", "Lesson 9", "Lesson 10", "Lesson 11", "Lesson 12", "Review 7-12"},
//16
{"Lesson 1", "Lesson 2", "Lesson 3", "Lesson 4", "Lesson 5", "Lesson 6", "Review 1-6",
"Lesson 7", "Lesson 8", "Lesson 9", "Lesson 10", "Lesson 11", "Lesson 12", "Review 7-12"},
//17
{"Lesson 1", "Lesson 2", "Lesson 3", "Lesson 4", "Lesson 5", "Lesson 6", "Review 1-6",
"Lesson 7", "Lesson 8", "Lesson 9", "Lesson 10", "Lesson 11", "Lesson 12", "Review 7-12"},
//18
{"Genesis", "Exodus", "Leviticus", "Numbers", "Deuteronomy", "Joshua", "Judges", "Ruth",
"1 Samuel", "2 Samuel", "1 Kings", "2 Kings", "1 Chronicles", "2 Chronicles", "Ezra",
"Nehemiah", "Esther", "Job", "Psalm", "Proverbs", "Ecclesiastes", "Song of Solomon",
"Isaiah", "Jeremiah", "Lamentations", "Ezekiel", "Daniel", "Hosea", "Joel", "Amos",
"Obadiah", "Jonah", "Micah", "Nahum", "Habakkuk", "Zephaniah", "Haggai", "Zechariah",
"Malachi", "Matthew", "Mark", "Luke", "John", "Acts", "Romans", "1 Corinthians",
"2 Corinthians", "Galatians", "Ephesians", "Philippians", "Colossians", "1 Thessalonians",
"2 Thessalonians", "1 Timothy", "2 Timothy", "Titus", "Philemon", "Hebrews", "James",
"1 Peter", "2 Peter", "1 John", "2 John", "3 John", "Jude", "Revelation"}
};
private ArrayList<Section> sections;
private String group;
private String name;
private boolean completed;
private String completionDate;
private JCheckBox checkBox;
public Book(String groupAndName, ArrayList<Section> sections, boolean completed, String completionDate) {
setGroupAndName(groupAndName);
this.sections = sections;
this.completed = completed;
this.completionDate = completionDate;
}
private void setGroupAndName(String groupAndName) {
int index = groupAndName.indexOf('_');
group = groupAndName.substring(0, index);
name = groupAndName.substring(index + 1);
}
public String getFullName() {
return group + "_" + name;
}
public String getGroup() {
return group;
}
public String getName() {
return name;
}
public int getNumberOfSections() {
return sections.size();
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
if (completed == true) {
completionDate = Record.calculateCompletionDate();
setAllSectionsCompleted();
} else {
completionDate = null;
}
}
public ArrayList<Section> getCompletedSections() {
ArrayList<Section> completedSections = new ArrayList<>();
for (int i = 0; i < sections.size(); i++) {
Section test = sections.get(i);
if (test.isCompleted()) {
completedSections.add(test);
}
}
return completedSections;
}
public String getCompletionDate() {
return completionDate;
}
private void setAllSectionsCompleted() {
Section check;
for (int i = 0; i < sections.size(); i++) {
check = sections.get(i);
if (!check.isCompleted()) {
check.setCompleted(true);
}
}
}
public Section getSection(int i) {
return sections.get(i);
}
public JPanel getRenderable() {
JPanel panel = new JPanel();
panel.setName(getName());
panel.setSize(new Dimension(1, 1));
panel.setLayout(new WrapLayout());
checkBox = new JCheckBox(getName(), isCompleted());
checkBox.addItemListener(this);
panel.add(checkBox);
panel.add(new JSeparator());
if (getNumberOfSections() > 1) {
for (int j = 0; j < getNumberOfSections(); j++) {
panel.add(getSection(j).getRenderable());
}
}
return panel;
}
@Override
public void itemStateChanged(ItemEvent e) {
setCompleted(checkBox.isSelected());
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("\n" + getName() + " Group:" + getGroup() + " Completed:" + isCompleted());
for (int i = 0; i < sections.size(); i++) {
b.append("\n").append(sections.get(i).toString());
}
return b.toString();
}
public String getSaveString() {
StringBuilder builder = new StringBuilder();
Section s;
for (int j = 0; j < getNumberOfSections(); j++) {
s = getSection(j);
builder.append("`").append(bookPrefix).append(getGroup()).append("_").append(getName()).append("_").append(s.getName()).append(completedPostfix);
builder.append("` = '").append(s.isCompleted()).append("', `");
builder.append(bookPrefix).append(getGroup()).append("_").append(getName()).append("_").append(s.getName()).append(datePostfix).append("` = ");
if (s.isCompleted()) {
- builder.append(s.getCompletionDate()).append(", ");
+ builder.append("'").append(s.getCompletionDate()).append("', ");
} else {
builder.append("null, ");
}
}
builder.append("`").append(bookPrefix).append(getGroup()).append("_").append(getName()).append(completedPostfix).append("` = '");
builder.append(isCompleted()).append("', `");
builder.append(bookPrefix).append(getGroup()).append("_").append(getName()).append(datePostfix).append("` = ");
if (isCompleted()) {
- builder.append(getCompletionDate());
+ builder.append("'").append(getCompletionDate()).append("'");
} else {
builder.append("null");
}
return builder.toString();
}
}
| false | true | public String getSaveString() {
StringBuilder builder = new StringBuilder();
Section s;
for (int j = 0; j < getNumberOfSections(); j++) {
s = getSection(j);
builder.append("`").append(bookPrefix).append(getGroup()).append("_").append(getName()).append("_").append(s.getName()).append(completedPostfix);
builder.append("` = '").append(s.isCompleted()).append("', `");
builder.append(bookPrefix).append(getGroup()).append("_").append(getName()).append("_").append(s.getName()).append(datePostfix).append("` = ");
if (s.isCompleted()) {
builder.append(s.getCompletionDate()).append(", ");
} else {
builder.append("null, ");
}
}
builder.append("`").append(bookPrefix).append(getGroup()).append("_").append(getName()).append(completedPostfix).append("` = '");
builder.append(isCompleted()).append("', `");
builder.append(bookPrefix).append(getGroup()).append("_").append(getName()).append(datePostfix).append("` = ");
if (isCompleted()) {
builder.append(getCompletionDate());
} else {
builder.append("null");
}
return builder.toString();
}
| public String getSaveString() {
StringBuilder builder = new StringBuilder();
Section s;
for (int j = 0; j < getNumberOfSections(); j++) {
s = getSection(j);
builder.append("`").append(bookPrefix).append(getGroup()).append("_").append(getName()).append("_").append(s.getName()).append(completedPostfix);
builder.append("` = '").append(s.isCompleted()).append("', `");
builder.append(bookPrefix).append(getGroup()).append("_").append(getName()).append("_").append(s.getName()).append(datePostfix).append("` = ");
if (s.isCompleted()) {
builder.append("'").append(s.getCompletionDate()).append("', ");
} else {
builder.append("null, ");
}
}
builder.append("`").append(bookPrefix).append(getGroup()).append("_").append(getName()).append(completedPostfix).append("` = '");
builder.append(isCompleted()).append("', `");
builder.append(bookPrefix).append(getGroup()).append("_").append(getName()).append(datePostfix).append("` = ");
if (isCompleted()) {
builder.append("'").append(getCompletionDate()).append("'");
} else {
builder.append("null");
}
return builder.toString();
}
|
diff --git a/grails/test/scaffolding/org/codehaus/groovy/grails/scaffolding/ControllerScaffoldingTests.java b/grails/test/scaffolding/org/codehaus/groovy/grails/scaffolding/ControllerScaffoldingTests.java
index 32bba5924..37293f8e6 100644
--- a/grails/test/scaffolding/org/codehaus/groovy/grails/scaffolding/ControllerScaffoldingTests.java
+++ b/grails/test/scaffolding/org/codehaus/groovy/grails/scaffolding/ControllerScaffoldingTests.java
@@ -1,319 +1,319 @@
package org.codehaus.groovy.grails.scaffolding;
import groovy.lang.Closure;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.lang.MissingMethodException;
import groovy.lang.MissingPropertyException;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.groovy.grails.commons.DefaultGrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.metaclass.ProxyMetaClass;
import org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator;
import org.codehaus.groovy.grails.orm.hibernate.cfg.DefaultGrailsDomainConfiguration;
import org.codehaus.groovy.grails.web.metaclass.ControllerDynamicMethods;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper;
import org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsControllerHelper;
import org.hibernate.SessionFactory;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
import org.springframework.web.servlet.ModelAndView;
public class ControllerScaffoldingTests extends
AbstractDependencyInjectionSpringContextTests {
private GenericApplicationContext localContext;
private ConfigurableApplicationContext appCtx;
private GrailsApplication grailsApplication;
private SessionFactory sessionFactory;
private Class domainClass;
private Class controllerClass;
protected void onSetUp() throws Exception {
GroovyClassLoader cl = new GroovyClassLoader();
Thread.currentThread().setContextClassLoader(cl);
Class tmpClass = cl.parseClass( "class ScaffoldController {\n" +
- "@Property boolean scaffold = true" +
+ "boolean scaffold = true" +
"}" );
Class tmpClass2 = cl.parseClass( "class Scaffold {\n" +
- "@Property Long id\n" +
- "@Property Long version\n" +
- "@Property String name\n" +
+ "Long id\n" +
+ "Long version\n" +
+ "String name\n" +
"}" );
this.controllerClass = tmpClass;
this.domainClass = tmpClass2;
//grailsApplication = new DefaultGrailsApplication(,cl);
this.localContext = new GenericApplicationContext(super.applicationContext);
ConstructorArgumentValues args = new ConstructorArgumentValues();
args.addGenericArgumentValue(new Class[]{ controllerClass, domainClass});
args.addGenericArgumentValue(cl);
MutablePropertyValues propValues = new MutablePropertyValues();
BeanDefinition grailsApplicationBean = new RootBeanDefinition(DefaultGrailsApplication.class,args,propValues);
localContext.registerBeanDefinition( "grailsApplication", grailsApplicationBean );
this.localContext.refresh();
/*BeanDefinition applicationEventMulticaster = new RootBeanDefinition(SimpleApplicationEventMulticaster.class);
context.registerBeanDefinition( "applicationEventMulticaster ", applicationEventMulticaster);*/
this.grailsApplication = (GrailsApplication)localContext.getBean("grailsApplication");
DefaultGrailsDomainConfiguration config = new DefaultGrailsDomainConfiguration();
config.setGrailsApplication(this.grailsApplication);
Properties props = new Properties();
props.put("hibernate.connection.username","sa");
props.put("hibernate.connection.password","");
props.put("hibernate.connection.url","jdbc:hsqldb:mem:grailsDB");
props.put("hibernate.connection.driver_class","org.hsqldb.jdbcDriver");
props.put("hibernate.dialect","org.hibernate.dialect.HSQLDialect");
props.put("hibernate.hbm2ddl.auto","create-drop");
config.setProperties(props);
//originalClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(cl);
this.sessionFactory = config.buildSessionFactory();
assertNotNull(this.sessionFactory);
GrailsRuntimeConfigurator rConfig = new GrailsRuntimeConfigurator(grailsApplication,this.localContext);
this.appCtx = (ConfigurableApplicationContext)rConfig.configure(new MockServletContext());
assertNotNull(appCtx);
GroovyObject domainObject = (GroovyObject)domainClass.newInstance();
domainObject.setProperty("name", "fred");
domainObject.invokeMethod("save", new Object[0]);
GroovyObject domainObject2 = (GroovyObject)domainClass.newInstance();
domainObject2.setProperty("name", "wilma");
domainObject2.invokeMethod("save", new Object[0]);
super.onSetUp();
}
public void testScaffoldList() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setRequestURI("/scaffold/list");
GroovyObject go = configureDynamicGO(controllerClass, grailsApplication,request,response);
// first test redirection within the same controller
try {
Closure closure = (Closure)go.getProperty("list");
Object returnValue = closure.call();
assertNotNull(returnValue);
assertTrue(returnValue instanceof ModelAndView);
ModelAndView mv = (ModelAndView)returnValue;
assertEquals("/scaffold/list",mv.getViewName());
assertTrue(mv.getModel().containsKey("scaffoldList"));
}
catch(MissingMethodException mme) {
fail("Missing method exception should not have been thrown!");
}
catch(MissingPropertyException mpex) {
fail("Missing property exception should not have been thrown!");
}
}
public void testScaffoldDelete() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setRequestURI("/scaffold/delete");
request.addParameter("id", "1");
GroovyObject go = configureDynamicGO(controllerClass, grailsApplication,request,response);
// first test redirection within the same controller
try {
Closure closure = (Closure)go.getProperty("delete");
Object returnValue = closure.call();
assertNotNull(returnValue);
assertTrue(returnValue instanceof ModelAndView);
ModelAndView mv = (ModelAndView)returnValue;
// should delegate to list
assertEquals("/scaffold/list",mv.getViewName());
assertTrue(mv.getModel().containsKey("scaffoldList"));
assertNull(mv.getModel().get("scaffold"));
}
catch(MissingMethodException mme) {
fail("Missing method exception should not have been thrown!");
}
catch(MissingPropertyException mpex) {
fail("Missing property exception should not have been thrown!");
}
}
public void testScaffoldSave() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setRequestURI("/scaffold/save");
request.addParameter("name", "dino");
GroovyObject go = configureDynamicGO(controllerClass, grailsApplication,request,response);
// first test redirection within the same controller
try {
Closure closure = (Closure)go.getProperty("save");
Object returnValue = closure.call();
assertNotNull(returnValue);
assertTrue(returnValue instanceof ModelAndView);
ModelAndView mv = (ModelAndView)returnValue;
// should end up at the show view
assertEquals("/scaffold/show",mv.getViewName());
// and contain the appropriate model
assertTrue(mv.getModel().containsKey("scaffold"));
GroovyObject domainObject = (GroovyObject)mv.getModel().get("scaffold");
assertNotNull(domainObject);
assertEquals("dino", domainObject.getProperty("name"));
}
catch(MissingMethodException mme) {
fail("Missing method exception should not have been thrown!");
}
catch(MissingPropertyException mpex) {
fail("Missing property exception should not have been thrown!");
}
}
public void testScaffoldUpdate() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setRequestURI("/scaffold/update");
request.addParameter("id", "1");
request.addParameter("name", "fredjnr");
GroovyObject go = configureDynamicGO(controllerClass, grailsApplication,request,response);
// first test redirection within the same controller
try {
Closure closure = (Closure)go.getProperty("update");
Object returnValue = closure.call();
assertNotNull(returnValue);
assertTrue(returnValue instanceof ModelAndView);
ModelAndView mv = (ModelAndView)returnValue;
// should end up at the show view
assertEquals("/scaffold/show",mv.getViewName());
// and contain the appropriate model
assertTrue(mv.getModel().containsKey("scaffold"));
GroovyObject domainObject = (GroovyObject)mv.getModel().get("scaffold");
assertNotNull(domainObject);
assertEquals("fredjnr", domainObject.getProperty("name"));
}
catch(MissingMethodException mme) {
fail("Missing method exception should not have been thrown!");
}
catch(MissingPropertyException mpex) {
fail("Missing property exception should not have been thrown!");
}
}
public void testScaffoldShow() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setRequestURI("/scaffold/show");
request.addParameter("id", "1");
GroovyObject go = configureDynamicGO(controllerClass, grailsApplication,request,response);
// first test redirection within the same controller
try {
Closure closure = (Closure)go.getProperty("show");
Object returnValue = closure.call();
assertNotNull(returnValue);
assertTrue(returnValue instanceof ModelAndView);
ModelAndView mv = (ModelAndView)returnValue;
assertEquals("/scaffold/show",mv.getViewName());
assertTrue(mv.getModel().containsKey("scaffold"));
// now try a rubish id
request = new MockHttpServletRequest();
request.setRequestURI("/scaffold/show");
request.addParameter("id", "13423");
go = configureDynamicGO(controllerClass, grailsApplication,request,response);
closure = (Closure)go.getProperty("show");
returnValue = closure.call();
assertNotNull(returnValue);
assertTrue(returnValue instanceof ModelAndView);
mv = (ModelAndView)returnValue;
assertEquals("/scaffold/show",mv.getViewName());
assertTrue(mv.getModel().containsKey("scaffold"));
// now try a different action name that uses the same class
// to implement scaffolding
request = new MockHttpServletRequest();
request.setRequestURI("/scaffold/edit");
request.addParameter("id", "1");
go = configureDynamicGO(controllerClass, grailsApplication,request,response);
closure = (Closure)go.getProperty("edit");
returnValue = closure.call();
assertNotNull(returnValue);
assertTrue(returnValue instanceof ModelAndView);
mv = (ModelAndView)returnValue;
assertEquals("/scaffold/edit",mv.getViewName());
assertTrue(mv.getModel().containsKey("scaffold"));
}
catch(MissingMethodException mme) {
fail("Missing method exception should not have been thrown!");
}
catch(MissingPropertyException mpex) {
fail("Missing property exception should not have been thrown!");
}
}
private GroovyObject configureDynamicGO(Class groovyClass,GrailsApplication application, HttpServletRequest request, HttpServletResponse response)
throws Exception {
ProxyMetaClass pmc = ProxyMetaClass.getInstance(groovyClass);
// proof of concept to try out proxy meta class
BeanDefinition bd = new RootBeanDefinition(groovyClass,false);
localContext.registerBeanDefinition( groovyClass.getName(), bd );
GrailsControllerHelper helper = new SimpleGrailsControllerHelper(application,this.appCtx, new MockServletContext());
GroovyObject go = (GroovyObject)groovyClass.newInstance();
pmc.setInterceptor( new ControllerDynamicMethods(go,helper,request,response) );
go.setMetaClass( pmc );
return go;
}
protected String[] getConfigLocations() {
return new String[] { "org/codehaus/groovy/grails/scaffolding/grails-scaffolding-tests.xml" };
}
}
| false | true | protected void onSetUp() throws Exception {
GroovyClassLoader cl = new GroovyClassLoader();
Thread.currentThread().setContextClassLoader(cl);
Class tmpClass = cl.parseClass( "class ScaffoldController {\n" +
"@Property boolean scaffold = true" +
"}" );
Class tmpClass2 = cl.parseClass( "class Scaffold {\n" +
"@Property Long id\n" +
"@Property Long version\n" +
"@Property String name\n" +
"}" );
this.controllerClass = tmpClass;
this.domainClass = tmpClass2;
//grailsApplication = new DefaultGrailsApplication(,cl);
this.localContext = new GenericApplicationContext(super.applicationContext);
ConstructorArgumentValues args = new ConstructorArgumentValues();
args.addGenericArgumentValue(new Class[]{ controllerClass, domainClass});
args.addGenericArgumentValue(cl);
MutablePropertyValues propValues = new MutablePropertyValues();
BeanDefinition grailsApplicationBean = new RootBeanDefinition(DefaultGrailsApplication.class,args,propValues);
localContext.registerBeanDefinition( "grailsApplication", grailsApplicationBean );
this.localContext.refresh();
/*BeanDefinition applicationEventMulticaster = new RootBeanDefinition(SimpleApplicationEventMulticaster.class);
context.registerBeanDefinition( "applicationEventMulticaster ", applicationEventMulticaster);*/
this.grailsApplication = (GrailsApplication)localContext.getBean("grailsApplication");
DefaultGrailsDomainConfiguration config = new DefaultGrailsDomainConfiguration();
config.setGrailsApplication(this.grailsApplication);
Properties props = new Properties();
props.put("hibernate.connection.username","sa");
props.put("hibernate.connection.password","");
props.put("hibernate.connection.url","jdbc:hsqldb:mem:grailsDB");
props.put("hibernate.connection.driver_class","org.hsqldb.jdbcDriver");
props.put("hibernate.dialect","org.hibernate.dialect.HSQLDialect");
props.put("hibernate.hbm2ddl.auto","create-drop");
config.setProperties(props);
//originalClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(cl);
this.sessionFactory = config.buildSessionFactory();
assertNotNull(this.sessionFactory);
GrailsRuntimeConfigurator rConfig = new GrailsRuntimeConfigurator(grailsApplication,this.localContext);
this.appCtx = (ConfigurableApplicationContext)rConfig.configure(new MockServletContext());
assertNotNull(appCtx);
GroovyObject domainObject = (GroovyObject)domainClass.newInstance();
domainObject.setProperty("name", "fred");
domainObject.invokeMethod("save", new Object[0]);
GroovyObject domainObject2 = (GroovyObject)domainClass.newInstance();
domainObject2.setProperty("name", "wilma");
domainObject2.invokeMethod("save", new Object[0]);
super.onSetUp();
}
| protected void onSetUp() throws Exception {
GroovyClassLoader cl = new GroovyClassLoader();
Thread.currentThread().setContextClassLoader(cl);
Class tmpClass = cl.parseClass( "class ScaffoldController {\n" +
"boolean scaffold = true" +
"}" );
Class tmpClass2 = cl.parseClass( "class Scaffold {\n" +
"Long id\n" +
"Long version\n" +
"String name\n" +
"}" );
this.controllerClass = tmpClass;
this.domainClass = tmpClass2;
//grailsApplication = new DefaultGrailsApplication(,cl);
this.localContext = new GenericApplicationContext(super.applicationContext);
ConstructorArgumentValues args = new ConstructorArgumentValues();
args.addGenericArgumentValue(new Class[]{ controllerClass, domainClass});
args.addGenericArgumentValue(cl);
MutablePropertyValues propValues = new MutablePropertyValues();
BeanDefinition grailsApplicationBean = new RootBeanDefinition(DefaultGrailsApplication.class,args,propValues);
localContext.registerBeanDefinition( "grailsApplication", grailsApplicationBean );
this.localContext.refresh();
/*BeanDefinition applicationEventMulticaster = new RootBeanDefinition(SimpleApplicationEventMulticaster.class);
context.registerBeanDefinition( "applicationEventMulticaster ", applicationEventMulticaster);*/
this.grailsApplication = (GrailsApplication)localContext.getBean("grailsApplication");
DefaultGrailsDomainConfiguration config = new DefaultGrailsDomainConfiguration();
config.setGrailsApplication(this.grailsApplication);
Properties props = new Properties();
props.put("hibernate.connection.username","sa");
props.put("hibernate.connection.password","");
props.put("hibernate.connection.url","jdbc:hsqldb:mem:grailsDB");
props.put("hibernate.connection.driver_class","org.hsqldb.jdbcDriver");
props.put("hibernate.dialect","org.hibernate.dialect.HSQLDialect");
props.put("hibernate.hbm2ddl.auto","create-drop");
config.setProperties(props);
//originalClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(cl);
this.sessionFactory = config.buildSessionFactory();
assertNotNull(this.sessionFactory);
GrailsRuntimeConfigurator rConfig = new GrailsRuntimeConfigurator(grailsApplication,this.localContext);
this.appCtx = (ConfigurableApplicationContext)rConfig.configure(new MockServletContext());
assertNotNull(appCtx);
GroovyObject domainObject = (GroovyObject)domainClass.newInstance();
domainObject.setProperty("name", "fred");
domainObject.invokeMethod("save", new Object[0]);
GroovyObject domainObject2 = (GroovyObject)domainClass.newInstance();
domainObject2.setProperty("name", "wilma");
domainObject2.invokeMethod("save", new Object[0]);
super.onSetUp();
}
|
diff --git a/api/src/test/java/org/openmrs/util/UserByNameComparatorTest.java b/api/src/test/java/org/openmrs/util/UserByNameComparatorTest.java
index 51c43d88..019c9de8 100755
--- a/api/src/test/java/org/openmrs/util/UserByNameComparatorTest.java
+++ b/api/src/test/java/org/openmrs/util/UserByNameComparatorTest.java
@@ -1,74 +1,74 @@
/**
* The contents of this file are subject to the OpenMRS 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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.openmrs.Person;
import org.openmrs.PersonName;
import org.openmrs.User;
import org.openmrs.test.Verifies;
/**
* This test class (should) contain tests for all of the {@link UserByNameComparator} methods.
*/
public class UserByNameComparatorTest {
/**
* This tests sorting with the {@link UserByNameComparator} given a set of users with
* personNames
*
* @see {@link UserByNameComparator#compare(User,User)}
*/
@Test
@Verifies(value = "should sort users by personNames", method = "compare(User,User)")
public void compare_shouldSortUsersByPersonNames() throws Exception {
Person person1 = new Person();
- person1.addName(new PersonName("givenName", "midsdleName", "familyName"));
+ person1.addName(new PersonName("givenName", "middleName", "familyName"));
User user1 = new User(person1);
Person person2 = new Person();
person2.addName(new PersonName("givenName", "middleNamf", "familyName"));
User user2 = new User(person2);
Person person3 = new Person();
person3.addName(new PersonName("givenName", "middleNamg", "familyName"));
User user3 = new User(person3);
Person person4 = new Person();
person4.addName(new PersonName("givenName", "middleNamh", "familyName"));
User user4 = new User(person4);
List<User> listToSort = new ArrayList<User>();
// add the users randomly
listToSort.add(user3);
listToSort.add(user1);
listToSort.add(user4);
listToSort.add(user2);
// sort the list with userByNameComparator
Collections.sort(listToSort, new UserByNameComparator());
// make sure that the users are sorted in the expected order
Iterator<User> it = listToSort.iterator();
Assert.assertTrue("Expected user1 to be the first in the sorted user list but wasn't", user1.equals(it.next()));
Assert.assertTrue("Expected user2 to be the second in the sorted user list but wasn't", user2.equals(it.next()));
Assert.assertTrue("Expected user3 to be the third in the sorted user list but wasn't", user3.equals(it.next()));
Assert.assertTrue("Expected user4 to be the fourth in the sorted user list but wasn't", user4.equals(it.next()));
;
}
}
| true | true | public void compare_shouldSortUsersByPersonNames() throws Exception {
Person person1 = new Person();
person1.addName(new PersonName("givenName", "midsdleName", "familyName"));
User user1 = new User(person1);
Person person2 = new Person();
person2.addName(new PersonName("givenName", "middleNamf", "familyName"));
User user2 = new User(person2);
Person person3 = new Person();
person3.addName(new PersonName("givenName", "middleNamg", "familyName"));
User user3 = new User(person3);
Person person4 = new Person();
person4.addName(new PersonName("givenName", "middleNamh", "familyName"));
User user4 = new User(person4);
List<User> listToSort = new ArrayList<User>();
// add the users randomly
listToSort.add(user3);
listToSort.add(user1);
listToSort.add(user4);
listToSort.add(user2);
// sort the list with userByNameComparator
Collections.sort(listToSort, new UserByNameComparator());
// make sure that the users are sorted in the expected order
Iterator<User> it = listToSort.iterator();
Assert.assertTrue("Expected user1 to be the first in the sorted user list but wasn't", user1.equals(it.next()));
Assert.assertTrue("Expected user2 to be the second in the sorted user list but wasn't", user2.equals(it.next()));
Assert.assertTrue("Expected user3 to be the third in the sorted user list but wasn't", user3.equals(it.next()));
Assert.assertTrue("Expected user4 to be the fourth in the sorted user list but wasn't", user4.equals(it.next()));
;
}
| public void compare_shouldSortUsersByPersonNames() throws Exception {
Person person1 = new Person();
person1.addName(new PersonName("givenName", "middleName", "familyName"));
User user1 = new User(person1);
Person person2 = new Person();
person2.addName(new PersonName("givenName", "middleNamf", "familyName"));
User user2 = new User(person2);
Person person3 = new Person();
person3.addName(new PersonName("givenName", "middleNamg", "familyName"));
User user3 = new User(person3);
Person person4 = new Person();
person4.addName(new PersonName("givenName", "middleNamh", "familyName"));
User user4 = new User(person4);
List<User> listToSort = new ArrayList<User>();
// add the users randomly
listToSort.add(user3);
listToSort.add(user1);
listToSort.add(user4);
listToSort.add(user2);
// sort the list with userByNameComparator
Collections.sort(listToSort, new UserByNameComparator());
// make sure that the users are sorted in the expected order
Iterator<User> it = listToSort.iterator();
Assert.assertTrue("Expected user1 to be the first in the sorted user list but wasn't", user1.equals(it.next()));
Assert.assertTrue("Expected user2 to be the second in the sorted user list but wasn't", user2.equals(it.next()));
Assert.assertTrue("Expected user3 to be the third in the sorted user list but wasn't", user3.equals(it.next()));
Assert.assertTrue("Expected user4 to be the fourth in the sorted user list but wasn't", user4.equals(it.next()));
;
}
|
diff --git a/src/main/java/com/bna/test.java b/src/main/java/com/bna/test.java
index 032a6f9..05c1146 100644
--- a/src/main/java/com/bna/test.java
+++ b/src/main/java/com/bna/test.java
@@ -1,12 +1,12 @@
package com.bna;
import java.io.IOException;
import javax.servlet.http.*;
public class test extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
- resp.getWriter().println("Hello, world");
+ resp.getWriter().println("<h1>BNA Test Page</h1>");
}
}
| true | true | public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
}
| public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("<h1>BNA Test Page</h1>");
}
|
diff --git a/src/main/java/org/exolab/castor/xml/schema/util/DatatypeHandler.java b/src/main/java/org/exolab/castor/xml/schema/util/DatatypeHandler.java
index 67f72662..7f6698a6 100644
--- a/src/main/java/org/exolab/castor/xml/schema/util/DatatypeHandler.java
+++ b/src/main/java/org/exolab/castor/xml/schema/util/DatatypeHandler.java
@@ -1,260 +1,261 @@
/**
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. 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.
*
* 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of Intalio, Inc. For written permission,
* please contact [email protected].
*
* 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written
* permission of Intalio, Inc. Exolab is a registered
* trademark of Intalio, Inc.
*
* 5. Due credit should be given to the Exolab Project
* (http://www.exolab.org/).
*
* THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS
* ``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
* INTALIO, INC. OR ITS 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.
*
* Copyright 1999-2002 (C) Intalio, Inc. All Rights Reserved.
*
* $Id$
*/
package org.exolab.castor.xml.schema.util;
import org.exolab.castor.types.Date;
import org.exolab.castor.types.Time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
/**
* A class used for "guessing" the proper datatype of
* an XML attribute or an XML element with simpleContent.
*
* @author <a href="mailto:[email protected]">Keith Visco</a>
* @version $Revision$ $Date: 2005-03-07 01:33:49 -0700 (Mon, 07 Mar 2005) $
**/
public class DatatypeHandler {
/**
* The name of the XML Schema boolean type
**/
public static final String BOOLEAN_TYPE = "boolean";
/**
* The name of the XML Schema date type
**/
public static final String DATE_TYPE = "date";
/**
* The name of the XML Schema dateTime type
**/
public static final String DATETIME_TYPE = "dateTime";
/**
* The name of the XML Schema double type
**/
public static final String DOUBLE_TYPE = "double";
/**
* The name of the XML Schema float type
**/
public static final String FLOAT_TYPE = "float";
/**
* The name of the XML Schema integer type
**/
public static final String INTEGER_TYPE = "integer";
/**
* The name of the XML Schema long type
**/
public static final String LONG_TYPE = "long";
/**
* The name of the XML Schema string type
**/
public static final String STRING_TYPE = "string";
/**
* The name of the XML Schema time type
**/
public static final String TIME_TYPE = "time";
private static final String TRUE = "true";
private static final String FALSE = "false";
private static final String DATE_FORMAT =
"yyyy-MM-dd'T'HH:mm:ss.SSS";
private static final String DATE_FORMAT_2 =
"yyyy-MM-dd'T'HH:mm:ss";
/**
* Creates a new DatatypeHandler
*
**/
private DatatypeHandler() {
super();
} //-- DatatypeHandler
/**
* Guesses the datatype for the given value. When the type
* cannot be determined, it simply defaults to
* DatatypeHandler.STRING_TYPE.
* <BR />
* <B>Note:</B> This may be a slow process.
*
* @param value the value to determine the type for
* @return the type that the value may be
**/
public static String guessType(String value) {
if (value == null) return null;
//-- If string is empty...not much we
//-- can do...
if (value.length() == 0) return STRING_TYPE;
//-- check for integer, must be done before check for long
try {
Integer.parseInt(value);
return INTEGER_TYPE;
}
catch(NumberFormatException nfe) {}
//-- check for long
try {
Long.parseLong(value);
return LONG_TYPE;
}
catch(NumberFormatException nfe) {}
//-- check for float, must be done before check for double
try {
Float.valueOf(value);
return FLOAT_TYPE;
}
catch(NumberFormatException nfe) {}
//-- check for double
try {
Double.valueOf(value);
return DOUBLE_TYPE;
}
catch(NumberFormatException nfe) {}
//-- check for boolean
if (value.equals(TRUE) || value.equals(FALSE)) {
return BOOLEAN_TYPE;
}
//-- check for date
try {
Date.parseDate(value);
return DATE_TYPE;
}
catch(ParseException px) {}
//-- check for time
try {
Time.parseTime(value);
return TIME_TYPE;
}
catch(ParseException px) {}
+ catch(IllegalArgumentException ex) {}
//-- check for dateTime
DateFormat df = null;
if (value.indexOf('.') < 0)
df = new SimpleDateFormat(DATE_FORMAT);
else
df = new SimpleDateFormat(DATE_FORMAT_2);
try {
df.parse(value);
return DATETIME_TYPE;
}
catch (java.text.ParseException ex) {}
//-- when all else fails :-)
return STRING_TYPE;
} //-- guessType
/**
* Guesses which datatype should be used.
*
*/
protected static String whichType(String type1, String type2) {
//-- if both types are the same, return the type
if (type1.equals(type2)) return type1;
//-- if any type is a string, return string
if (type1.equals(STRING_TYPE) || (type2.equals(STRING_TYPE)))
return STRING_TYPE;
//-- neither type is a string
if (INTEGER_TYPE.equals(type1)) {
if (LONG_TYPE.equals(type2))
return LONG_TYPE;
else if (FLOAT_TYPE.equals(type2))
return FLOAT_TYPE;
else if (DOUBLE_TYPE.equals(type2))
return DOUBLE_TYPE;
}
else if (LONG_TYPE.equals(type1)) {
if (INTEGER_TYPE.equals(type2))
return LONG_TYPE;
else if (FLOAT_TYPE.equals(type2))
return DOUBLE_TYPE;
else if (DOUBLE_TYPE.equals(type2))
return DOUBLE_TYPE;
}
else if (FLOAT_TYPE.equals(type1)) {
if (INTEGER_TYPE.equals(type2))
return FLOAT_TYPE;
else if (LONG_TYPE.equals(type2))
return DOUBLE_TYPE;
else if (DOUBLE_TYPE.equals(type2))
return DOUBLE_TYPE;
}
else if (DOUBLE_TYPE.equals(type1)) {
if (INTEGER_TYPE.equals(type2))
return DOUBLE_TYPE;
else if (LONG_TYPE.equals(type2))
return DOUBLE_TYPE;
else if (FLOAT_TYPE.equals(type2))
return DOUBLE_TYPE;
}
//-- when in doubt...return string
return STRING_TYPE;
} //-- whichType
} //-- DatatypeHandler
| true | true | public static String guessType(String value) {
if (value == null) return null;
//-- If string is empty...not much we
//-- can do...
if (value.length() == 0) return STRING_TYPE;
//-- check for integer, must be done before check for long
try {
Integer.parseInt(value);
return INTEGER_TYPE;
}
catch(NumberFormatException nfe) {}
//-- check for long
try {
Long.parseLong(value);
return LONG_TYPE;
}
catch(NumberFormatException nfe) {}
//-- check for float, must be done before check for double
try {
Float.valueOf(value);
return FLOAT_TYPE;
}
catch(NumberFormatException nfe) {}
//-- check for double
try {
Double.valueOf(value);
return DOUBLE_TYPE;
}
catch(NumberFormatException nfe) {}
//-- check for boolean
if (value.equals(TRUE) || value.equals(FALSE)) {
return BOOLEAN_TYPE;
}
//-- check for date
try {
Date.parseDate(value);
return DATE_TYPE;
}
catch(ParseException px) {}
//-- check for time
try {
Time.parseTime(value);
return TIME_TYPE;
}
catch(ParseException px) {}
//-- check for dateTime
DateFormat df = null;
if (value.indexOf('.') < 0)
df = new SimpleDateFormat(DATE_FORMAT);
else
df = new SimpleDateFormat(DATE_FORMAT_2);
try {
df.parse(value);
return DATETIME_TYPE;
}
catch (java.text.ParseException ex) {}
//-- when all else fails :-)
return STRING_TYPE;
} //-- guessType
| public static String guessType(String value) {
if (value == null) return null;
//-- If string is empty...not much we
//-- can do...
if (value.length() == 0) return STRING_TYPE;
//-- check for integer, must be done before check for long
try {
Integer.parseInt(value);
return INTEGER_TYPE;
}
catch(NumberFormatException nfe) {}
//-- check for long
try {
Long.parseLong(value);
return LONG_TYPE;
}
catch(NumberFormatException nfe) {}
//-- check for float, must be done before check for double
try {
Float.valueOf(value);
return FLOAT_TYPE;
}
catch(NumberFormatException nfe) {}
//-- check for double
try {
Double.valueOf(value);
return DOUBLE_TYPE;
}
catch(NumberFormatException nfe) {}
//-- check for boolean
if (value.equals(TRUE) || value.equals(FALSE)) {
return BOOLEAN_TYPE;
}
//-- check for date
try {
Date.parseDate(value);
return DATE_TYPE;
}
catch(ParseException px) {}
//-- check for time
try {
Time.parseTime(value);
return TIME_TYPE;
}
catch(ParseException px) {}
catch(IllegalArgumentException ex) {}
//-- check for dateTime
DateFormat df = null;
if (value.indexOf('.') < 0)
df = new SimpleDateFormat(DATE_FORMAT);
else
df = new SimpleDateFormat(DATE_FORMAT_2);
try {
df.parse(value);
return DATETIME_TYPE;
}
catch (java.text.ParseException ex) {}
//-- when all else fails :-)
return STRING_TYPE;
} //-- guessType
|
diff --git a/smartuser/smart-user-ui/module/src/main/java/com/smartitengineering/user/ui/AddUserTopComponent.java b/smartuser/smart-user-ui/module/src/main/java/com/smartitengineering/user/ui/AddUserTopComponent.java
index bc34d775..e6d25abe 100644
--- a/smartuser/smart-user-ui/module/src/main/java/com/smartitengineering/user/ui/AddUserTopComponent.java
+++ b/smartuser/smart-user-ui/module/src/main/java/com/smartitengineering/user/ui/AddUserTopComponent.java
@@ -1,371 +1,371 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.smartitengineering.user.ui;
import com.smartitengineering.ui.component.BasicIdentityPanel;
import com.smartitengineering.ui.component.DatePanel;
import java.io.Serializable;
import java.util.logging.Logger;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.openide.util.Utilities;
/**
* Top component which displays something.
*/
final class AddUserTopComponent extends TopComponent {
private static AddUserTopComponent instance;
/** path to the icon used by the component and its open action */
static final String ICON_PATH = "com/smartitengineering/user/ui/add_user.gif";
private static final String PREFERRED_ID = "AddUserTopComponent";
private AddUserTopComponent() {
initComponents();
setName(NbBundle.getMessage(AddUserTopComponent.class, "CTL_AddUserTopComponent"));
setToolTipText(NbBundle.getMessage(AddUserTopComponent.class, "HINT_AddUserTopComponent"));
setIcon(Utilities.loadImage(ICON_PATH, true));
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
baseScrollPane = new javax.swing.JScrollPane();
basePanel = new javax.swing.JPanel();
bottomPanel = new javax.swing.JPanel();
saveButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
addUserTabbedPane = new javax.swing.JTabbedPane();
userInformationTabPanel = new javax.swing.JPanel();
selfBasicIdentityPanel = new BasicIdentityPanel("Personal Information");
userInformationPanel = new com.smartitengineering.ui.component.UserInformationPanel();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
addressPanel2 = new com.smartitengineering.ui.component.AddressPanel();
fatherBasicIdentityPanel1 = new BasicIdentityPanel("Father's Information");
motherBasicIdentityPanel1 = new com.smartitengineering.ui.component.BasicIdentityPanel("Mother's Information");
spouseBasicIdentityPanel1 = new com.smartitengineering.ui.component.BasicIdentityPanel("Spouse's Information");
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
secondaryEmailAddressTextField1 = new javax.swing.JTextField();
phoneNumberTextField1 = new javax.swing.JTextField();
cellPhoneNumberTextField1 = new javax.swing.JTextField();
faxNumberTextField1 = new javax.swing.JTextField();
datePanel2 = new com.smartitengineering.ui.component.DatePanel();
baseScrollPane.setFont(baseScrollPane.getFont());
baseScrollPane.setPreferredSize(new java.awt.Dimension(550, 552));
basePanel.setFont(basePanel.getFont());
basePanel.setPreferredSize(new java.awt.Dimension(850, 550));
bottomPanel.setFont(bottomPanel.getFont());
org.openide.awt.Mnemonics.setLocalizedText(saveButton, org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.saveButton.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.cancelButton.text")); // NOI18N
javax.swing.GroupLayout bottomPanelLayout = new javax.swing.GroupLayout(bottomPanel);
bottomPanel.setLayout(bottomPanelLayout);
bottomPanelLayout.setHorizontalGroup(
bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, bottomPanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
bottomPanelLayout.setVerticalGroup(
bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(saveButton)
.addComponent(cancelButton))
);
addUserTabbedPane.setFont(addUserTabbedPane.getFont());
userInformationTabPanel.setFont(userInformationTabPanel.getFont());
selfBasicIdentityPanel.setFont(selfBasicIdentityPanel.getFont());
userInformationPanel.setFont(userInformationPanel.getFont());
javax.swing.GroupLayout userInformationTabPanelLayout = new javax.swing.GroupLayout(userInformationTabPanel);
userInformationTabPanel.setLayout(userInformationTabPanelLayout);
userInformationTabPanelLayout.setHorizontalGroup(
userInformationTabPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(userInformationTabPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(userInformationTabPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(selfBasicIdentityPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(userInformationPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(485, Short.MAX_VALUE))
);
userInformationTabPanelLayout.setVerticalGroup(
userInformationTabPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(userInformationTabPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(selfBasicIdentityPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(48, 48, 48)
.addComponent(userInformationPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(130, Short.MAX_VALUE))
);
addUserTabbedPane.addTab(org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.userInformationTabPanel.TabConstraints.tabTitle"), new javax.swing.ImageIcon(getClass().getResource("/com/smartitengineering/user/ui/user_information_icon.gif")), userInformationTabPanel); // NOI18N
addressPanel2.setFont(addressPanel2.getFont());
fatherBasicIdentityPanel1.setFont(fatherBasicIdentityPanel1.getFont());
motherBasicIdentityPanel1.setFont(motherBasicIdentityPanel1.getFont());
spouseBasicIdentityPanel1.setFont(spouseBasicIdentityPanel1.getFont());
jLabel5.setFont(jLabel5.getFont());
org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.jLabel5.text")); // NOI18N
jLabel6.setFont(jLabel6.getFont());
org.openide.awt.Mnemonics.setLocalizedText(jLabel6, org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.jLabel6.text")); // NOI18N
jLabel7.setFont(jLabel7.getFont());
org.openide.awt.Mnemonics.setLocalizedText(jLabel7, org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.jLabel7.text_1")); // NOI18N
jLabel8.setFont(jLabel8.getFont());
org.openide.awt.Mnemonics.setLocalizedText(jLabel8, org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.jLabel8.text_1")); // NOI18N
secondaryEmailAddressTextField1.setFont(secondaryEmailAddressTextField1.getFont());
secondaryEmailAddressTextField1.setText(org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.secondaryEmailAddressTextField1.text")); // NOI18N
phoneNumberTextField1.setFont(phoneNumberTextField1.getFont());
phoneNumberTextField1.setText(org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.phoneNumberTextField1.text")); // NOI18N
cellPhoneNumberTextField1.setFont(cellPhoneNumberTextField1.getFont());
cellPhoneNumberTextField1.setText(org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.cellPhoneNumberTextField1.text")); // NOI18N
faxNumberTextField1.setFont(faxNumberTextField1.getFont());
faxNumberTextField1.setText(org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.faxNumberTextField1.text")); // NOI18N
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(addressPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(secondaryEmailAddressTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8)
.addComponent(jLabel7)
.addComponent(jLabel6))
.addGap(52, 52, 52)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(phoneNumberTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)
.addComponent(cellPhoneNumberTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)
.addComponent(faxNumberTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)))))
.addComponent(datePanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(spouseBasicIdentityPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(motherBasicIdentityPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(fatherBasicIdentityPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(193, 193, 193))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
.addComponent(addressPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34)
.addComponent(datePanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(secondaryEmailAddressTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(phoneNumberTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(cellPhoneNumberTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8)
.addComponent(faxNumberTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
.addComponent(fatherBasicIdentityPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(motherBasicIdentityPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spouseBasicIdentityPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(60, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 865, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
addUserTabbedPane.addTab(org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.jPanel1.TabConstraints.tabTitle"), jPanel1); // NOI18N
javax.swing.GroupLayout basePanelLayout = new javax.swing.GroupLayout(basePanel);
basePanel.setLayout(basePanelLayout);
basePanelLayout.setHorizontalGroup(
basePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(basePanelLayout.createSequentialGroup()
.addGroup(basePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(bottomPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(addUserTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(26, Short.MAX_VALUE))
);
basePanelLayout.setVerticalGroup(
basePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(basePanelLayout.createSequentialGroup()
.addComponent(addUserTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 512, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bottomPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ .addContainerGap(15, Short.MAX_VALUE))
);
baseScrollPane.setViewportView(basePanel);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(baseScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 917, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addComponent(baseScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(baseScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 564, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTabbedPane addUserTabbedPane;
private com.smartitengineering.ui.component.AddressPanel addressPanel2;
private javax.swing.JPanel basePanel;
private javax.swing.JScrollPane baseScrollPane;
private javax.swing.JPanel bottomPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JTextField cellPhoneNumberTextField1;
private com.smartitengineering.ui.component.DatePanel datePanel2;
private com.smartitengineering.ui.component.BasicIdentityPanel fatherBasicIdentityPanel1;
private javax.swing.JTextField faxNumberTextField1;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private com.smartitengineering.ui.component.BasicIdentityPanel motherBasicIdentityPanel1;
private javax.swing.JTextField phoneNumberTextField1;
private javax.swing.JButton saveButton;
private javax.swing.JTextField secondaryEmailAddressTextField1;
private com.smartitengineering.ui.component.BasicIdentityPanel selfBasicIdentityPanel;
private com.smartitengineering.ui.component.BasicIdentityPanel spouseBasicIdentityPanel1;
private com.smartitengineering.ui.component.UserInformationPanel userInformationPanel;
private javax.swing.JPanel userInformationTabPanel;
// End of variables declaration//GEN-END:variables
/**
* Gets default instance. Do not use directly: reserved for *.settings files only,
* i.e. deserialization routines; otherwise you could get a non-deserialized instance.
* To obtain the singleton instance, use {@link #findInstance}.
*/
public static synchronized AddUserTopComponent getDefault() {
if (instance == null) {
instance = new AddUserTopComponent();
}
return instance;
}
/**
* Obtain the AddUserTopComponent instance. Never call {@link #getDefault} directly!
*/
public static synchronized AddUserTopComponent findInstance() {
TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
if (win == null) {
Logger.getLogger(AddUserTopComponent.class.getName()).warning(
"Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
return getDefault();
}
if (win instanceof AddUserTopComponent) {
return (AddUserTopComponent) win;
}
Logger.getLogger(AddUserTopComponent.class.getName()).warning(
"There seem to be multiple components with the '" + PREFERRED_ID +
"' ID. That is a potential source of errors and unexpected behavior.");
return getDefault();
}
@Override
public int getPersistenceType() {
return TopComponent.PERSISTENCE_ALWAYS;
}
@Override
public void componentOpened() {
// TODO add custom code on component opening
}
@Override
public void componentClosed() {
// TODO add custom code on component closing
}
/** replaces this in object stream */
@Override
public Object writeReplace() {
return new ResolvableHelper();
}
@Override
protected String preferredID() {
return PREFERRED_ID;
}
final static class ResolvableHelper implements Serializable {
private static final long serialVersionUID = 1L;
public Object readResolve() {
return AddUserTopComponent.getDefault();
}
}
}
| false | true | private void initComponents() {
baseScrollPane = new javax.swing.JScrollPane();
basePanel = new javax.swing.JPanel();
bottomPanel = new javax.swing.JPanel();
saveButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
addUserTabbedPane = new javax.swing.JTabbedPane();
userInformationTabPanel = new javax.swing.JPanel();
selfBasicIdentityPanel = new BasicIdentityPanel("Personal Information");
userInformationPanel = new com.smartitengineering.ui.component.UserInformationPanel();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
addressPanel2 = new com.smartitengineering.ui.component.AddressPanel();
fatherBasicIdentityPanel1 = new BasicIdentityPanel("Father's Information");
motherBasicIdentityPanel1 = new com.smartitengineering.ui.component.BasicIdentityPanel("Mother's Information");
spouseBasicIdentityPanel1 = new com.smartitengineering.ui.component.BasicIdentityPanel("Spouse's Information");
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
secondaryEmailAddressTextField1 = new javax.swing.JTextField();
phoneNumberTextField1 = new javax.swing.JTextField();
cellPhoneNumberTextField1 = new javax.swing.JTextField();
faxNumberTextField1 = new javax.swing.JTextField();
datePanel2 = new com.smartitengineering.ui.component.DatePanel();
baseScrollPane.setFont(baseScrollPane.getFont());
baseScrollPane.setPreferredSize(new java.awt.Dimension(550, 552));
basePanel.setFont(basePanel.getFont());
basePanel.setPreferredSize(new java.awt.Dimension(850, 550));
bottomPanel.setFont(bottomPanel.getFont());
org.openide.awt.Mnemonics.setLocalizedText(saveButton, org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.saveButton.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.cancelButton.text")); // NOI18N
javax.swing.GroupLayout bottomPanelLayout = new javax.swing.GroupLayout(bottomPanel);
bottomPanel.setLayout(bottomPanelLayout);
bottomPanelLayout.setHorizontalGroup(
bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, bottomPanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
bottomPanelLayout.setVerticalGroup(
bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(saveButton)
.addComponent(cancelButton))
);
addUserTabbedPane.setFont(addUserTabbedPane.getFont());
userInformationTabPanel.setFont(userInformationTabPanel.getFont());
selfBasicIdentityPanel.setFont(selfBasicIdentityPanel.getFont());
userInformationPanel.setFont(userInformationPanel.getFont());
javax.swing.GroupLayout userInformationTabPanelLayout = new javax.swing.GroupLayout(userInformationTabPanel);
userInformationTabPanel.setLayout(userInformationTabPanelLayout);
userInformationTabPanelLayout.setHorizontalGroup(
userInformationTabPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(userInformationTabPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(userInformationTabPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(selfBasicIdentityPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(userInformationPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(485, Short.MAX_VALUE))
);
userInformationTabPanelLayout.setVerticalGroup(
userInformationTabPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(userInformationTabPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(selfBasicIdentityPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(48, 48, 48)
.addComponent(userInformationPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(130, Short.MAX_VALUE))
);
addUserTabbedPane.addTab(org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.userInformationTabPanel.TabConstraints.tabTitle"), new javax.swing.ImageIcon(getClass().getResource("/com/smartitengineering/user/ui/user_information_icon.gif")), userInformationTabPanel); // NOI18N
addressPanel2.setFont(addressPanel2.getFont());
fatherBasicIdentityPanel1.setFont(fatherBasicIdentityPanel1.getFont());
motherBasicIdentityPanel1.setFont(motherBasicIdentityPanel1.getFont());
spouseBasicIdentityPanel1.setFont(spouseBasicIdentityPanel1.getFont());
jLabel5.setFont(jLabel5.getFont());
org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.jLabel5.text")); // NOI18N
jLabel6.setFont(jLabel6.getFont());
org.openide.awt.Mnemonics.setLocalizedText(jLabel6, org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.jLabel6.text")); // NOI18N
jLabel7.setFont(jLabel7.getFont());
org.openide.awt.Mnemonics.setLocalizedText(jLabel7, org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.jLabel7.text_1")); // NOI18N
jLabel8.setFont(jLabel8.getFont());
org.openide.awt.Mnemonics.setLocalizedText(jLabel8, org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.jLabel8.text_1")); // NOI18N
secondaryEmailAddressTextField1.setFont(secondaryEmailAddressTextField1.getFont());
secondaryEmailAddressTextField1.setText(org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.secondaryEmailAddressTextField1.text")); // NOI18N
phoneNumberTextField1.setFont(phoneNumberTextField1.getFont());
phoneNumberTextField1.setText(org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.phoneNumberTextField1.text")); // NOI18N
cellPhoneNumberTextField1.setFont(cellPhoneNumberTextField1.getFont());
cellPhoneNumberTextField1.setText(org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.cellPhoneNumberTextField1.text")); // NOI18N
faxNumberTextField1.setFont(faxNumberTextField1.getFont());
faxNumberTextField1.setText(org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.faxNumberTextField1.text")); // NOI18N
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(addressPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(secondaryEmailAddressTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8)
.addComponent(jLabel7)
.addComponent(jLabel6))
.addGap(52, 52, 52)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(phoneNumberTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)
.addComponent(cellPhoneNumberTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)
.addComponent(faxNumberTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)))))
.addComponent(datePanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(spouseBasicIdentityPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(motherBasicIdentityPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(fatherBasicIdentityPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(193, 193, 193))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
.addComponent(addressPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34)
.addComponent(datePanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(secondaryEmailAddressTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(phoneNumberTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(cellPhoneNumberTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8)
.addComponent(faxNumberTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
.addComponent(fatherBasicIdentityPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(motherBasicIdentityPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spouseBasicIdentityPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(60, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 865, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
addUserTabbedPane.addTab(org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.jPanel1.TabConstraints.tabTitle"), jPanel1); // NOI18N
javax.swing.GroupLayout basePanelLayout = new javax.swing.GroupLayout(basePanel);
basePanel.setLayout(basePanelLayout);
basePanelLayout.setHorizontalGroup(
basePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(basePanelLayout.createSequentialGroup()
.addGroup(basePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(bottomPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(addUserTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(26, Short.MAX_VALUE))
);
basePanelLayout.setVerticalGroup(
basePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(basePanelLayout.createSequentialGroup()
.addComponent(addUserTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 512, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bottomPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
baseScrollPane.setViewportView(basePanel);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(baseScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 917, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(baseScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
baseScrollPane = new javax.swing.JScrollPane();
basePanel = new javax.swing.JPanel();
bottomPanel = new javax.swing.JPanel();
saveButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
addUserTabbedPane = new javax.swing.JTabbedPane();
userInformationTabPanel = new javax.swing.JPanel();
selfBasicIdentityPanel = new BasicIdentityPanel("Personal Information");
userInformationPanel = new com.smartitengineering.ui.component.UserInformationPanel();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
addressPanel2 = new com.smartitengineering.ui.component.AddressPanel();
fatherBasicIdentityPanel1 = new BasicIdentityPanel("Father's Information");
motherBasicIdentityPanel1 = new com.smartitengineering.ui.component.BasicIdentityPanel("Mother's Information");
spouseBasicIdentityPanel1 = new com.smartitengineering.ui.component.BasicIdentityPanel("Spouse's Information");
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
secondaryEmailAddressTextField1 = new javax.swing.JTextField();
phoneNumberTextField1 = new javax.swing.JTextField();
cellPhoneNumberTextField1 = new javax.swing.JTextField();
faxNumberTextField1 = new javax.swing.JTextField();
datePanel2 = new com.smartitengineering.ui.component.DatePanel();
baseScrollPane.setFont(baseScrollPane.getFont());
baseScrollPane.setPreferredSize(new java.awt.Dimension(550, 552));
basePanel.setFont(basePanel.getFont());
basePanel.setPreferredSize(new java.awt.Dimension(850, 550));
bottomPanel.setFont(bottomPanel.getFont());
org.openide.awt.Mnemonics.setLocalizedText(saveButton, org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.saveButton.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.cancelButton.text")); // NOI18N
javax.swing.GroupLayout bottomPanelLayout = new javax.swing.GroupLayout(bottomPanel);
bottomPanel.setLayout(bottomPanelLayout);
bottomPanelLayout.setHorizontalGroup(
bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, bottomPanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
bottomPanelLayout.setVerticalGroup(
bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(saveButton)
.addComponent(cancelButton))
);
addUserTabbedPane.setFont(addUserTabbedPane.getFont());
userInformationTabPanel.setFont(userInformationTabPanel.getFont());
selfBasicIdentityPanel.setFont(selfBasicIdentityPanel.getFont());
userInformationPanel.setFont(userInformationPanel.getFont());
javax.swing.GroupLayout userInformationTabPanelLayout = new javax.swing.GroupLayout(userInformationTabPanel);
userInformationTabPanel.setLayout(userInformationTabPanelLayout);
userInformationTabPanelLayout.setHorizontalGroup(
userInformationTabPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(userInformationTabPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(userInformationTabPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(selfBasicIdentityPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(userInformationPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(485, Short.MAX_VALUE))
);
userInformationTabPanelLayout.setVerticalGroup(
userInformationTabPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(userInformationTabPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(selfBasicIdentityPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(48, 48, 48)
.addComponent(userInformationPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(130, Short.MAX_VALUE))
);
addUserTabbedPane.addTab(org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.userInformationTabPanel.TabConstraints.tabTitle"), new javax.swing.ImageIcon(getClass().getResource("/com/smartitengineering/user/ui/user_information_icon.gif")), userInformationTabPanel); // NOI18N
addressPanel2.setFont(addressPanel2.getFont());
fatherBasicIdentityPanel1.setFont(fatherBasicIdentityPanel1.getFont());
motherBasicIdentityPanel1.setFont(motherBasicIdentityPanel1.getFont());
spouseBasicIdentityPanel1.setFont(spouseBasicIdentityPanel1.getFont());
jLabel5.setFont(jLabel5.getFont());
org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.jLabel5.text")); // NOI18N
jLabel6.setFont(jLabel6.getFont());
org.openide.awt.Mnemonics.setLocalizedText(jLabel6, org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.jLabel6.text")); // NOI18N
jLabel7.setFont(jLabel7.getFont());
org.openide.awt.Mnemonics.setLocalizedText(jLabel7, org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.jLabel7.text_1")); // NOI18N
jLabel8.setFont(jLabel8.getFont());
org.openide.awt.Mnemonics.setLocalizedText(jLabel8, org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.jLabel8.text_1")); // NOI18N
secondaryEmailAddressTextField1.setFont(secondaryEmailAddressTextField1.getFont());
secondaryEmailAddressTextField1.setText(org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.secondaryEmailAddressTextField1.text")); // NOI18N
phoneNumberTextField1.setFont(phoneNumberTextField1.getFont());
phoneNumberTextField1.setText(org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.phoneNumberTextField1.text")); // NOI18N
cellPhoneNumberTextField1.setFont(cellPhoneNumberTextField1.getFont());
cellPhoneNumberTextField1.setText(org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.cellPhoneNumberTextField1.text")); // NOI18N
faxNumberTextField1.setFont(faxNumberTextField1.getFont());
faxNumberTextField1.setText(org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.faxNumberTextField1.text")); // NOI18N
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(addressPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(secondaryEmailAddressTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8)
.addComponent(jLabel7)
.addComponent(jLabel6))
.addGap(52, 52, 52)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(phoneNumberTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)
.addComponent(cellPhoneNumberTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)
.addComponent(faxNumberTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)))))
.addComponent(datePanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(spouseBasicIdentityPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(motherBasicIdentityPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(fatherBasicIdentityPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(193, 193, 193))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
.addComponent(addressPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34)
.addComponent(datePanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(secondaryEmailAddressTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(phoneNumberTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(cellPhoneNumberTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8)
.addComponent(faxNumberTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
.addComponent(fatherBasicIdentityPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(motherBasicIdentityPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spouseBasicIdentityPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(60, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 865, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
addUserTabbedPane.addTab(org.openide.util.NbBundle.getMessage(AddUserTopComponent.class, "AddUserTopComponent.jPanel1.TabConstraints.tabTitle"), jPanel1); // NOI18N
javax.swing.GroupLayout basePanelLayout = new javax.swing.GroupLayout(basePanel);
basePanel.setLayout(basePanelLayout);
basePanelLayout.setHorizontalGroup(
basePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(basePanelLayout.createSequentialGroup()
.addGroup(basePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(bottomPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(addUserTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(26, Short.MAX_VALUE))
);
basePanelLayout.setVerticalGroup(
basePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(basePanelLayout.createSequentialGroup()
.addComponent(addUserTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 512, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bottomPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(15, Short.MAX_VALUE))
);
baseScrollPane.setViewportView(basePanel);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(baseScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 917, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(baseScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 564, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/com/itmill/toolkit/terminal/web/ApplicationServlet.java b/src/com/itmill/toolkit/terminal/web/ApplicationServlet.java
index 24f9390af..af16b23f3 100644
--- a/src/com/itmill/toolkit/terminal/web/ApplicationServlet.java
+++ b/src/com/itmill/toolkit/terminal/web/ApplicationServlet.java
@@ -1,1854 +1,1855 @@
/* *************************************************************************
IT Mill Toolkit
Development of Browser User Intarfaces Made Easy
Copyright (C) 2000-2006 IT Mill Ltd
*************************************************************************
This product is distributed under commercial license that can be found
from the product package on license/license.txt. Use of this product might
require purchasing a commercial license from IT Mill Ltd. For guidelines
on usage, see license/licensing-guidelines.html
*************************************************************************
For more information, contact:
IT Mill Ltd phone: +358 2 4802 7180
Ruukinkatu 2-4 fax: +358 2 4802 7181
20540, Turku email: [email protected]
Finland company www: www.itmill.com
Primary source for information and releases: www.itmill.com
********************************************************************** */
package com.itmill.toolkit.terminal.web;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.WeakHashMap;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import org.xml.sax.SAXException;
import com.itmill.toolkit.Application;
import com.itmill.toolkit.Application.WindowAttachEvent;
import com.itmill.toolkit.Application.WindowDetachEvent;
import com.itmill.toolkit.service.FileTypeResolver;
import com.itmill.toolkit.terminal.DownloadStream;
import com.itmill.toolkit.terminal.Paintable;
import com.itmill.toolkit.terminal.ParameterHandler;
import com.itmill.toolkit.terminal.ThemeResource;
import com.itmill.toolkit.terminal.URIHandler;
import com.itmill.toolkit.terminal.Paintable.RepaintRequestEvent;
import com.itmill.toolkit.terminal.web.ThemeSource.ThemeException;
import com.itmill.toolkit.ui.Window;
import com.itmill.toolkit.service.License;
import com.itmill.toolkit.service.License.InvalidLicenseFile;
import com.itmill.toolkit.service.License.LicenseFileHasAlreadyBeenRead;
import com.itmill.toolkit.service.License.LicenseFileHasNotBeenRead;
import com.itmill.toolkit.service.License.LicenseSignatureIsInvalid;
import com.itmill.toolkit.service.License.LicenseViolation;
/**
* This servlet connects IT Mill Toolkit Application to Web. This servlet
* replaces both WebAdapterServlet and AjaxAdapterServlet.
*
* @author IT Mill Ltd.
* @version
* @VERSION@
* @since 4.0
*/
public class ApplicationServlet extends HttpServlet implements
Application.WindowAttachListener, Application.WindowDetachListener,
Paintable.RepaintRequestListener {
/** Version number of this release. For example "4.0.0" */
public static final String VERSION;
/** Major version number. For example 4 in 4.1.0. */
public static final int VERSION_MAJOR;
/** Minor version number. For example 1 in 4.1.0. */
public static final int VERSION_MINOR;
/** Build number. For example 0-beta1 in 4.0.0-beta1. */
public static final String VERSION_BUILD;
/* Initialize version numbers from string replaced by build-script. */
static {
if ("@VERSION@".equals("@" + "VERSION" + "@"))
VERSION = "4.0.0-INTERNAL-NONVERSIONED-DEBUG-BUILD";
else
VERSION = "@VERSION@";
String[] digits = VERSION.split("\\.");
VERSION_MAJOR = Integer.parseInt(digits[0]);
VERSION_MINOR = Integer.parseInt(digits[1]);
VERSION_BUILD = digits[2];
}
// Configurable parameter names
private static final String PARAMETER_DEBUG = "Debug";
private static final String PARAMETER_DEFAULT_THEME_JAR = "DefaultThemeJar";
private static final String PARAMETER_THEMESOURCE = "ThemeSource";
private static final String PARAMETER_THEME_CACHETIME = "ThemeCacheTime";
private static final String PARAMETER_MAX_TRANSFORMERS = "MaxTransformers";
private static final String PARAMETER_TRANSFORMER_CACHETIME = "TransformerCacheTime";
private static final int DEFAULT_THEME_CACHETIME = 1000 * 60 * 60 * 24;
private static final int DEFAULT_BUFFER_SIZE = 32 * 1024;
private static final int DEFAULT_MAX_TRANSFORMERS = 1;
private static final int MAX_BUFFER_SIZE = 64 * 1024;
private static final String SESSION_ATTR_VARMAP = "itmill-toolkit-varmap";
private static final String SESSION_ATTR_CONTEXT = "itmill-toolkit-context";
protected static final String SESSION_ATTR_APPS = "itmill-toolkit-apps";
private static final String SESSION_BINDING_LISTENER = "itmill-toolkit-bindinglistener";
// TODO Should default or base theme be the default?
protected static final String DEFAULT_THEME = "base";
private static final String RESOURCE_URI = "/RES/";
private static final String AJAX_UIDL_URI = "/UIDL/";
private static final String THEME_DIRECTORY_PATH = "WEB-INF/lib/themes/";
private static final String THEME_LISTING_FILE = THEME_DIRECTORY_PATH
+ "themes.txt";
private static final String DEFAULT_THEME_JAR_PREFIX = "itmill-toolkit-themes";
private static final String DEFAULT_THEME_JAR = "WEB-INF/lib/"
+ DEFAULT_THEME_JAR_PREFIX + "-" + VERSION + ".jar";
private static final String DEFAULT_THEME_TEMP_FILE_PREFIX = "ITMILL_TMP_";
private static final String SERVER_COMMAND_PARAM = "SERVER_COMMANDS";
private static final int SERVER_COMMAND_STREAM_MAINTAIN_PERIOD = 15000;
private static final int SERVER_COMMAND_HEADER_PADDING = 2000;
// Maximum delay between request for an user to be considered active (in ms)
private static final long ACTIVE_USER_REQUEST_INTERVAL = 1000 * 45;
// Private fields
private Class applicationClass;
private Properties applicationProperties;
private UIDLTransformerFactory transformerFactory;
private CollectionThemeSource themeSource;
private String resourcePath = null;
private boolean debugMode = false;
private int maxConcurrentTransformers;
private long transformerCacheTime;
private long themeCacheTime;
private WeakHashMap applicationToDirtyWindowSetMap = new WeakHashMap();
private WeakHashMap applicationToServerCommandStreamLock = new WeakHashMap();
private static WeakHashMap applicationToLastRequestDate = new WeakHashMap();
private List allWindows = new LinkedList();
private WeakHashMap applicationToAjaxAppMgrMap = new WeakHashMap();
private HashMap licenseForApplicationClass = new HashMap();
private static HashSet licensePrintedForApplicationClass = new HashSet();
/**
* Called by the servlet container to indicate to a servlet that the servlet
* is being placed into service.
*
* @param servletConfig
* object containing the servlet's configuration and
* initialization parameters
* @throws ServletException
* if an exception has occurred that interferes with the
* servlet's normal operation.
*/
public void init(javax.servlet.ServletConfig servletConfig)
throws javax.servlet.ServletException {
super.init(servletConfig);
// Get the application class name
String applicationClassName = servletConfig
.getInitParameter("application");
if (applicationClassName == null) {
Log.error("Application not specified in servlet parameters");
}
// Store the application parameters into Properties object
this.applicationProperties = new Properties();
for (Enumeration e = servletConfig.getInitParameterNames(); e
.hasMoreElements();) {
String name = (String) e.nextElement();
this.applicationProperties.setProperty(name, servletConfig
.getInitParameter(name));
}
// Override with server.xml parameters
ServletContext context = servletConfig.getServletContext();
for (Enumeration e = context.getInitParameterNames(); e
.hasMoreElements();) {
String name = (String) e.nextElement();
this.applicationProperties.setProperty(name, context
.getInitParameter(name));
}
// Get the debug window parameter
String debug = getApplicationOrSystemProperty(PARAMETER_DEBUG, "false");
// Enable application specific debug
this.debugMode = debug.equals("true");
// Get the maximum number of simultaneous transformers
this.maxConcurrentTransformers = Integer
.parseInt(getApplicationOrSystemProperty(
PARAMETER_MAX_TRANSFORMERS, "-1"));
if (this.maxConcurrentTransformers < 1)
this.maxConcurrentTransformers = DEFAULT_MAX_TRANSFORMERS;
// Get cache time for transformers
this.transformerCacheTime = Integer
.parseInt(getApplicationOrSystemProperty(
PARAMETER_TRANSFORMER_CACHETIME, "-1")) * 1000;
// Get cache time for theme resources
this.themeCacheTime = Integer.parseInt(getApplicationOrSystemProperty(
PARAMETER_THEME_CACHETIME, "-1")) * 1000;
if (this.themeCacheTime < 0) {
this.themeCacheTime = DEFAULT_THEME_CACHETIME;
}
// Add all specified theme sources
this.themeSource = new CollectionThemeSource();
List directorySources = getThemeSources();
for (Iterator i = directorySources.iterator(); i.hasNext();) {
this.themeSource.add((ThemeSource) i.next());
}
// Add the default theme source
String[] defaultThemeFiles = new String[] { getApplicationOrSystemProperty(
PARAMETER_DEFAULT_THEME_JAR, DEFAULT_THEME_JAR) };
File f = findDefaultThemeJar(defaultThemeFiles);
try {
// Add themes.jar if exists
if (f != null && f.exists())
this.themeSource.add(new JarThemeSource(f, this, ""));
else {
Log.warn("Default theme JAR not found in: "
+ Arrays.asList(defaultThemeFiles));
}
} catch (Exception e) {
throw new ServletException("Failed to load default theme from "
+ Arrays.asList(defaultThemeFiles), e);
}
// Check that at least one themesource was loaded
if (this.themeSource.getThemes().size() <= 0) {
throw new ServletException(
"No themes found in specified themesources.");
}
// Initialize the transformer factory, if not initialized
if (this.transformerFactory == null) {
this.transformerFactory = new UIDLTransformerFactory(
this.themeSource, this, this.maxConcurrentTransformers,
this.transformerCacheTime);
}
// Load the application class using the same class loader
// as the servlet itself
ClassLoader loader = this.getClass().getClassLoader();
try {
this.applicationClass = loader.loadClass(applicationClassName);
} catch (ClassNotFoundException e) {
throw new ServletException("Failed to load application class: "
+ applicationClassName);
}
}
/**
* Get an application or system property value.
*
* @param parameterName
* Name or the parameter
* @param defaultValue
* Default to be used
* @return String value or default if not found
*/
private String getApplicationOrSystemProperty(String parameterName,
String defaultValue) {
// Try application properties
String val = this.applicationProperties.getProperty(parameterName);
if (val != null) {
return val;
}
// Try lowercased application properties for backward compability with
// 3.0.2 and earlier
val = this.applicationProperties.getProperty(parameterName
.toLowerCase());
if (val != null) {
return val;
}
// Try system properties
String pkgName;
Package pkg = this.getClass().getPackage();
if (pkg != null) {
pkgName = pkg.getName();
} else {
String clazzName = this.getClass().getName();
pkgName = new String(clazzName.toCharArray(), 0, clazzName
.lastIndexOf('.'));
}
val = System.getProperty(pkgName + "." + parameterName);
if (val != null) {
return val;
}
// Try lowercased system properties
val = System.getProperty(pkgName + "." + parameterName.toLowerCase());
if (val != null) {
return val;
}
return defaultValue;
}
/**
* Get ThemeSources from given path. Construct the list of avalable themes
* in path using the following sources: 1. content of THEME_PATH directory
* (if available) 2. The themes listed in THEME_LIST_FILE 3. "themesource"
* application parameter - "org. millstone.webadapter. themesource" system
* property
*
* @param THEME_DIRECTORY_PATH
* @return List
*/
private List getThemeSources() throws ServletException {
List returnValue = new LinkedList();
// Check the list file in theme directory
List sourcePaths = new LinkedList();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
this.getServletContext().getResourceAsStream(
THEME_LISTING_FILE)));
String line = null;
while ((line = reader.readLine()) != null) {
sourcePaths.add(THEME_DIRECTORY_PATH + line.trim());
}
if (this.isDebugMode()) {
Log.debug("Listed " + sourcePaths.size() + " themes in "
+ THEME_LISTING_FILE + ". Loading " + sourcePaths);
}
} catch (Exception ignored) {
// If the file reading fails, just skip to next method
}
// If no file was found or it was empty,
// try to add themes filesystem directory if it is accessible
if (sourcePaths.size() <= 0) {
if (this.isDebugMode()) {
Log.debug("No themes listed in " + THEME_LISTING_FILE
+ ". Trying to read the content of directory "
+ THEME_DIRECTORY_PATH);
}
try {
String path = this.getServletContext().getRealPath(
THEME_DIRECTORY_PATH);
if (path != null) {
File f = new File(path);
if (f != null && f.exists())
returnValue.add(new DirectoryThemeSource(f, this));
}
} catch (java.io.IOException je) {
Log.info("Theme directory " + THEME_DIRECTORY_PATH
+ " not available. Skipped.");
} catch (ThemeException e) {
throw new ServletException("Failed to load themes from "
+ THEME_DIRECTORY_PATH, e);
}
}
// Add the theme sources from application properties
String paramValue = getApplicationOrSystemProperty(
PARAMETER_THEMESOURCE, null);
if (paramValue != null) {
StringTokenizer st = new StringTokenizer(paramValue, ";");
while (st.hasMoreTokens()) {
sourcePaths.add(st.nextToken());
}
}
// Construct appropriate theme source instances for each path
for (Iterator i = sourcePaths.iterator(); i.hasNext();) {
String source = (String) i.next();
File sourceFile = new File(source);
try {
// Relative files are treated as streams (to support
// resource inside WAR files)
if (!sourceFile.isAbsolute()) {
returnValue.add(new ServletThemeSource(this
.getServletContext(), this, source));
} else if (sourceFile.isDirectory()) {
// Absolute directories are read from filesystem
returnValue.add(new DirectoryThemeSource(sourceFile, this));
} else {
// Absolute JAR-files are read from filesystem
returnValue.add(new JarThemeSource(sourceFile, this, ""));
}
} catch (Exception e) {
// Any exception breaks the the init
throw new ServletException("Invalid theme source: " + source, e);
}
}
// Return the constructed list of theme sources
return returnValue;
}
/**
* Receives standard HTTP requests from the public service method and
* dispatches them.
*
* @param request
* object that contains the request the client made of the
* servlet
* @param response
* object that contains the response the servlet returns to the
* client
* @throws ServletException
* if an input or output error occurs while the servlet is
* handling the TRACE request
* @throws IOException
* if the request for the TRACE cannot be handled
*/
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Transformer and output stream for the result
UIDLTransformer transformer = null;
HttpVariableMap variableMap = null;
OutputStream out = response.getOutputStream();
HashSet currentlyDirtyWindowsForThisApplication = new HashSet();
Application application = null;
try {
// Handle resource requests
if (handleResourceRequest(request, response))
return;
// Handle server commands
if (handleServerCommands(request, response))
return;
// Get the application
application = getApplication(request);
// Create application if it doesn't exist
if (application == null)
application = createApplication(request);
// Set the last application request date
applicationToLastRequestDate.put(application, new Date());
// Invoke context transaction listeners
((WebApplicationContext) application.getContext())
.startTransaction(application, request);
// Is this a download request from application
DownloadStream download = null;
// The rest of the process is synchronized with the application
// in order to guarantee that no parallel variable handling is
// made
synchronized (application) {
// Handle UIDL requests?
String resourceId = request.getPathInfo();
if (resourceId != null && resourceId.startsWith(AJAX_UIDL_URI)) {
getApplicationManager(application).handleUidlRequest(
request, response);
return;
}
// Get the variable map
variableMap = getVariableMap(application, request);
if (variableMap == null)
return;
// Change all variables based on request parameters
Map unhandledParameters = variableMap.handleVariables(request,
application);
// Check/handle client side feature checks
WebBrowserProbe
.handleProbeRequest(request, unhandledParameters);
// Handle the URI if the application is still running
if (application.isRunning())
download = handleURI(application, request, response);
// If this is not a download request
if (download == null) {
// Window renders are not cacheable
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
// Find the window within the application
Window window = null;
if (application.isRunning())
window = getApplicationWindow(request, application);
// Handle the unhandled parameters if the application is
// still running
if (window != null && unhandledParameters != null
&& !unhandledParameters.isEmpty()) {
try {
window.handleParameters(unhandledParameters);
} catch (Throwable t) {
application
.terminalError(new ParameterHandlerErrorImpl(
window, t));
}
}
// Remove application if it has stopped
if (!application.isRunning()) {
endApplication(request, response, application);
return;
}
// Return blank page, if no window found
if (window == null) {
response.setContentType("text/html");
BufferedWriter page = new BufferedWriter(
new OutputStreamWriter(out));
page.write("<html><head><script>");
page
.write(ThemeFunctionLibrary
.generateWindowScript(
null,
application,
this,
WebBrowserProbe
.getTerminalType(request
.getSession())));
page.write("</script></head><body>");
page
.write("The requested window has been removed from application.");
page.write("</body></html>");
page.close();
return;
}
// Get the terminal type for the window
WebBrowser terminalType = (WebBrowser) window.getTerminal();
// Set terminal type for the window, if not already set
if (terminalType == null) {
terminalType = WebBrowserProbe.getTerminalType(request
.getSession());
window.setTerminal(terminalType);
}
// Find theme
Theme theme = themeSource
.getThemeByName(window.getTheme() != null ? window
.getTheme() : DEFAULT_THEME);
if (theme == null)
throw new ServletException("Default theme (named '"
+ DEFAULT_THEME + "') can not be found");
// If UIDL rendering mode is preferred, a page for it is
// rendered
String renderingMode = theme.getPreferredMode(terminalType,
themeSource);
if (Theme.MODE_UIDL.equals(renderingMode)) {
response.setContentType("text/html");
BufferedWriter page = new BufferedWriter(
new OutputStreamWriter(out));
page
.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" "
+ "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
page.write("<html><head>\n<title>"
+ window.getCaption() + "</title>\n");
Theme t = theme;
Vector themes = new Vector();
themes.add(t);
while (t.getParent() != null) {
String parentName = t.getParent();
t = themeSource.getThemeByName(parentName);
themes.add(t);
}
for (int k=themes.size()-1; k>=0; k--) {
t = (Theme) themes.get(k);
Collection files = t.getFileNames(terminalType,
Theme.MODE_UIDL);
for (Iterator i = files.iterator(); i.hasNext();) {
String file = (String) i.next();
if (file.endsWith(".css"))
page
.write("<link rel=\"stylesheet\" href=\""
+ getResourceLocation(t
.getName(),
new ThemeResource(
file))
+ "\" type=\"text/css\" />\n");
else if (file.endsWith(".js"))
page
.write("<script src=\""
+ getResourceLocation(t
.getName(),
new ThemeResource(
file))
+ "\" type=\"text/javascript\"></script>\n");
}
}
page.write("</head><body>\n");
page
.write("<div id=\"ajax-wait\"><div>Loading...</div></div>\n");
page.write("<div id=\"ajax-window\"></div>\n");
page.write("<script language=\"JavaScript\">\n");
+ String appUrl = getApplicationUrl(request).toString();
page
.write("var client = new ITMillToolkitClient("
+ "document.getElementById('ajax-window'),"
+ "\""
- + getApplicationUrl(request)
- + "/UIDL/"
+ + appUrl + (appUrl.endsWith("/") ? "" : "/")
+ + "UIDL/"
+ "\",\""
+ resourcePath + ((Theme)themes.get(themes.size()-1)).getName() + "/"
+ "client/\",document.getElementById('ajax-wait'));\n");
// TODO Should we also show debug information?
/*
* var debug =
* document.location.href.split("debug=")[1]; if (debug &&
* debug.split("&")[0] == "1") client.debugEnabled =
* true;
*/
for (int k=themes.size()-1; k>=0; k--) {
t = (Theme) themes.get(k);
String themeObjName = t.getName() + "Theme";
themeObjName = themeObjName.substring(0,1).toUpperCase() + themeObjName.substring(1);
page
.write(" (new "+themeObjName+"(\"" + resourcePath + ((Theme)themes.get(k)).getName() + "/\")).registerTo(client);\n");
}
page.write("client.start();\n");
page.write("</script>\n");
page.write("</body></html>\n");
page.close();
return;
}
// If other than XSLT or UIDL mode is requested
if (!Theme.MODE_XSLT.equals(renderingMode)) {
// TODO More informal message should be given is browser
// is not supported
response.setContentType("text/html");
BufferedWriter page = new BufferedWriter(
new OutputStreamWriter(out));
page.write("<html><head></head><body>");
page.write("Unsupported browser.");
page.write("</body></html>");
page.close();
return;
}
// Initialize Transformer
UIDLTransformerType transformerType = new UIDLTransformerType(
terminalType, theme);
transformer = this.transformerFactory
.getTransformer(transformerType);
// Set the response type
response.setContentType(terminalType.getContentType());
// Create UIDL writer
WebPaintTarget paintTarget = transformer
.getPaintTarget(variableMap);
// Assure that the correspoding debug window will be
// repainted property
// by clearing it before the actual paint.
DebugWindow debugWindow = (DebugWindow) application
.getWindow(DebugWindow.WINDOW_NAME);
if (debugWindow != null && debugWindow != window) {
debugWindow.setWindowUIDL(window, "Painting...");
}
// Paint window
window.paint(paintTarget);
paintTarget.close();
// For exception handling, memorize the current dirty status
Collection dirtyWindows = (Collection) applicationToDirtyWindowSetMap
.get(application);
if (dirtyWindows == null) {
dirtyWindows = new HashSet();
applicationToDirtyWindowSetMap.put(application,
dirtyWindows);
}
currentlyDirtyWindowsForThisApplication
.addAll(dirtyWindows);
// Window is now painted
windowPainted(application, window);
// Debug
if (debugWindow != null && debugWindow != window) {
debugWindow
.setWindowUIDL(window, paintTarget.getUIDL());
}
// Set the function library state for this thread
ThemeFunctionLibrary.setState(application, window,
transformerType.getWebBrowser(), request
.getSession(), this, transformerType
.getTheme().getName());
}
}
// For normal requests, transform the window
if (download == null) {
// Transform and output the result to browser
// Note that the transform and transfer of the result is
// not synchronized with the variable map. This allows
// parallel transfers and transforms for better performance,
// but requires that all calls from the XSL to java are
// thread-safe
transformer.transform(out);
}
// For download request, transfer the downloaded data
else {
handleDownload(download, request, response);
}
} catch (UIDLTransformerException te) {
try {
// Write the error report to client
response.setContentType("text/html");
BufferedWriter err = new BufferedWriter(new OutputStreamWriter(
out));
err
.write("<html><head><title>Application Internal Error</title></head><body>");
err.write("<h1>" + te.getMessage() + "</h1>");
err.write(te.getHTMLDescription());
err.write("</body></html>");
err.close();
} catch (Throwable t) {
Log.except("Failed to write error page: " + t
+ ". Original exception was: ", te);
}
// Add previously dirty windows to dirtyWindowList in order
// to make sure that eventually they are repainted
Application currentApplication = getApplication(request);
for (Iterator iter = currentlyDirtyWindowsForThisApplication
.iterator(); iter.hasNext();) {
Window dirtyWindow = (Window) iter.next();
addDirtyWindow(currentApplication, dirtyWindow);
}
} catch (Throwable e) {
// Re-throw other exceptions
throw new ServletException(e);
} finally {
// Release transformer
if (transformer != null)
transformerFactory.releaseTransformer(transformer);
// Notify transaction end
if (application != null)
((WebApplicationContext) application.getContext())
.endTransaction(application, request);
// Clean the function library state for this thread
// for security reasons
ThemeFunctionLibrary.cleanState();
}
}
/**
* Handle the requested URI. An application can add handlers to do special
* processing, when a certain URI is requested. The handlers are invoked
* before any windows URIs are processed and if a DownloadStream is returned
* it is sent to the client.
*
* @see com.itmill.toolkit.terminal.URIHandler
*
* @param application
* Application owning the URI
* @param request
* HTTP request instance
* @param response
* HTTP response to write to.
* @return boolean True if the request was handled and further processing
* should be suppressed, false otherwise.
*/
private DownloadStream handleURI(Application application,
HttpServletRequest request, HttpServletResponse response) {
String uri = request.getPathInfo();
// If no URI is available
if (uri == null || uri.length() == 0 || uri.equals("/"))
return null;
// Remove the leading /
while (uri.startsWith("/") && uri.length() > 0)
uri = uri.substring(1);
// Handle the uri
DownloadStream stream = null;
try {
stream = application.handleURI(application.getURL(), uri);
} catch (Throwable t) {
application.terminalError(new URIHandlerErrorImpl(application, t));
}
return stream;
}
/**
* Handle the requested URI. An application can add handlers to do special
* processing, when a certain URI is requested. The handlers are invoked
* before any windows URIs are processed and if a DownloadStream is returned
* it is sent to the client.
*
* @see com.itmill.toolkit.terminal.URIHandler
*
* @param application
* Application owning the URI
* @param request
* HTTP request instance
* @param response
* HTTP response to write to.
* @return boolean True if the request was handled and further processing
* should be suppressed, false otherwise.
*/
private void handleDownload(DownloadStream stream,
HttpServletRequest request, HttpServletResponse response) {
// Download from given stream
InputStream data = stream.getStream();
if (data != null) {
// Set content type
response.setContentType(stream.getContentType());
// Set cache headers
long cacheTime = stream.getCacheTime();
if (cacheTime <= 0) {
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
} else {
response.setHeader("Cache-Control", "max-age=" + cacheTime
/ 1000);
response.setDateHeader("Expires", System.currentTimeMillis()
+ cacheTime);
response.setHeader("Pragma", "cache"); // Required to apply
// caching in some
// Tomcats
}
// Copy download stream parameters directly
// to HTTP headers.
Iterator i = stream.getParameterNames();
if (i != null) {
while (i.hasNext()) {
String param = (String) i.next();
response.setHeader((String) param, stream
.getParameter(param));
}
}
int bufferSize = stream.getBufferSize();
if (bufferSize <= 0 || bufferSize > MAX_BUFFER_SIZE)
bufferSize = DEFAULT_BUFFER_SIZE;
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
try {
OutputStream out = response.getOutputStream();
while ((bytesRead = data.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
out.flush();
}
out.close();
} catch (IOException ignored) {
}
}
}
/**
* Look for default theme JAR file.
*
* @return Jar file or null if not found.
*/
private File findDefaultThemeJar(String[] fileList) {
// Try to find the default theme JAR file based on the given path
for (int i = 0; i < fileList.length; i++) {
String path = this.getServletContext().getRealPath(fileList[i]);
File file = null;
if (path != null && (file = new File(path)).exists()) {
return file;
}
}
// If we do not have access to individual files, create a temporary
// file from named resource.
for (int i = 0; i < fileList.length; i++) {
InputStream defaultTheme = this.getServletContext()
.getResourceAsStream(fileList[i]);
// Read the content to temporary file and return it
if (defaultTheme != null) {
return createTemporaryFile(defaultTheme, ".jar");
}
}
// Try to find the default theme JAR file based on file naming scheme
// NOTE: This is for backward compability with 3.0.2 and earlier.
String path = this.getServletContext().getRealPath("/WEB-INF/lib");
if (path != null) {
File lib = new File(path);
String[] files = lib.list();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].toLowerCase().endsWith(".jar")
&& files[i].startsWith(DEFAULT_THEME_JAR_PREFIX)) {
return new File(lib, files[i]);
}
}
}
}
// If no file was found return null
return null;
}
/**
* Create a temporary file for given stream.
*
* @param stream
* Stream to be stored into temporary file.
* @param extension
* File type extension
* @return File
*/
private File createTemporaryFile(InputStream stream, String extension) {
File tmpFile;
try {
tmpFile = File.createTempFile(DEFAULT_THEME_TEMP_FILE_PREFIX,
extension);
FileOutputStream out = new FileOutputStream(tmpFile);
byte[] buf = new byte[1024];
int bytes = 0;
while ((bytes = stream.read(buf)) > 0) {
out.write(buf, 0, bytes);
}
out.close();
} catch (IOException e) {
System.err
.println("Failed to create temporary file for default theme: "
+ e);
tmpFile = null;
}
return tmpFile;
}
/**
* Handle theme resource file requests. Resources supplied with the themes
* are provided by the WebAdapterServlet.
*
* @param request
* HTTP request
* @param response
* HTTP response
* @return boolean True if the request was handled and further processing
* should be suppressed, false otherwise.
*/
private boolean handleResourceRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException {
// If the resource path is unassigned, initialize it
if (resourcePath == null)
resourcePath = request.getContextPath() + request.getServletPath()
+ RESOURCE_URI;
String resourceId = request.getPathInfo();
// Check if this really is a resource request
if (resourceId == null || !resourceId.startsWith(RESOURCE_URI))
return false;
// Check the resource type
resourceId = resourceId.substring(RESOURCE_URI.length());
InputStream data = null;
// Get theme resources
try {
data = themeSource.getResource(resourceId);
} catch (ThemeSource.ThemeException e) {
Log.info(e.getMessage());
data = null;
}
// Write the response
try {
if (data != null) {
response.setContentType(FileTypeResolver
.getMIMEType(resourceId));
// Use default cache time for theme resources
if (this.themeCacheTime > 0) {
response.setHeader("Cache-Control", "max-age="
+ this.themeCacheTime / 1000);
response.setDateHeader("Expires", System
.currentTimeMillis()
+ this.themeCacheTime);
response.setHeader("Pragma", "cache"); // Required to apply
// caching in some
// Tomcats
}
// Write the data to client
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int bytesRead = 0;
OutputStream out = response.getOutputStream();
while ((bytesRead = data.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.close();
data.close();
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
} catch (java.io.IOException e) {
Log.info("Resource transfer failed: " + request.getRequestURI()
+ ". (" + e.getMessage() + ")");
}
return true;
}
/** Get the variable map for the session */
private static synchronized HttpVariableMap getVariableMap(
Application application, HttpServletRequest request) {
HttpSession session = request.getSession();
// Get the application to variablemap map
Map varMapMap = (Map) session.getAttribute(SESSION_ATTR_VARMAP);
if (varMapMap == null) {
varMapMap = new WeakHashMap();
session.setAttribute(SESSION_ATTR_VARMAP, varMapMap);
}
// Create a variable map, if it does not exists.
HttpVariableMap variableMap = (HttpVariableMap) varMapMap
.get(application);
if (variableMap == null) {
variableMap = new HttpVariableMap();
varMapMap.put(application, variableMap);
}
return variableMap;
}
/** Get the current application URL from request */
private URL getApplicationUrl(HttpServletRequest request)
throws MalformedURLException {
URL applicationUrl;
try {
URL reqURL = new URL((request.isSecure() ? "https://" : "http://")
+ request.getServerName() + ":" + request.getServerPort()
+ request.getRequestURI());
String servletPath = request.getContextPath()
+ request.getServletPath();
if (servletPath.length() == 0
|| servletPath.charAt(servletPath.length() - 1) != '/')
servletPath = servletPath + "/";
applicationUrl = new URL(reqURL, servletPath);
} catch (MalformedURLException e) {
Log.error("Error constructing application url "
+ request.getRequestURI() + " (" + e + ")");
throw e;
}
return applicationUrl;
}
/**
* Get the existing application for given request. Looks for application
* instance for given request based on the requested URL.
*
* @param request
* HTTP request
* @return Application instance, or null if the URL does not map to valid
* application.
*/
private Application getApplication(HttpServletRequest request)
throws MalformedURLException {
// Ensure that the session is still valid
HttpSession session = request.getSession(false);
if (session == null)
return null;
// Get application list for the session.
LinkedList applications = (LinkedList) session
.getAttribute(SESSION_ATTR_APPS);
if (applications == null)
return null;
// Search for the application (using the application URI) from the list
Application application = null;
for (Iterator i = applications.iterator(); i.hasNext()
&& application == null;) {
Application a = (Application) i.next();
String aPath = a.getURL().getPath();
String servletPath = request.getContextPath()
+ request.getServletPath();
if (servletPath.length() < aPath.length())
servletPath += "/";
if (servletPath.equals(aPath))
application = a;
}
// Remove stopped applications from the list
if (application != null && !application.isRunning()) {
applications.remove(application);
application = null;
}
return application;
}
/**
* Create a new application.
*
* @return New application instance
* @throws SAXException
* @throws LicenseViolation
* @throws InvalidLicenseFile
* @throws LicenseSignatureIsInvalid
* @throws LicenseFileHasNotBeenRead
*/
private Application createApplication(HttpServletRequest request)
throws MalformedURLException, InstantiationException,
IllegalAccessException, LicenseFileHasNotBeenRead,
LicenseSignatureIsInvalid, InvalidLicenseFile, LicenseViolation,
SAXException {
Application application = null;
// Get the application url
URL applicationUrl = getApplicationUrl(request);
// Get application list.
HttpSession session = request.getSession();
if (session == null)
return null;
LinkedList applications = (LinkedList) session
.getAttribute(SESSION_ATTR_APPS);
if (applications == null) {
applications = new LinkedList();
session.setAttribute(SESSION_ATTR_APPS, applications);
HttpSessionBindingListener sessionBindingListener = new SessionBindingListener(
applications);
session.setAttribute(SESSION_BINDING_LISTENER,
sessionBindingListener);
}
// Create new application and start it
try {
application = (Application) this.applicationClass.newInstance();
applications.add(application);
// Listen to window add/removes (for web mode)
application.addListener((Application.WindowAttachListener) this);
application.addListener((Application.WindowDetachListener) this);
// Set localte
application.setLocale(request.getLocale());
// Get application context for this session
WebApplicationContext context = (WebApplicationContext) session
.getAttribute(SESSION_ATTR_CONTEXT);
if (context == null) {
context = new WebApplicationContext(session);
session.setAttribute(SESSION_ATTR_CONTEXT, context);
}
// Start application and check license
initializeLicense(application);
application.start(applicationUrl, this.applicationProperties,
context);
checkLicense(application);
} catch (IllegalAccessException e) {
Log.error("Illegal access to application class "
+ this.applicationClass.getName());
throw e;
} catch (InstantiationException e) {
Log.error("Failed to instantiate application class: "
+ this.applicationClass.getName());
throw e;
}
return application;
}
private void initializeLicense(Application application) {
License license = (License) licenseForApplicationClass.get(application
.getClass());
if (license == null) {
license = new License();
licenseForApplicationClass.put(application.getClass(), license);
}
application.setToolkitLicense(license);
}
private void checkLicense(Application application)
throws LicenseFileHasNotBeenRead, LicenseSignatureIsInvalid,
InvalidLicenseFile, LicenseViolation, SAXException {
License license = application.getToolkitLicense();
if (!license.hasBeenRead()) {
InputStream lis;
try {
lis = getServletContext().getResource(
"/WEB-INF/itmill-toolkit-license.xml").openStream();
license.readLicenseFile(lis);
} catch (MalformedURLException e) {
// This should not happen
throw new RuntimeException(e);
} catch (IOException e) {
// This should not happen
throw new RuntimeException(e);
} catch (LicenseFileHasAlreadyBeenRead e) {
// This should not happen
throw new RuntimeException(e);
}
}
// For each application class, print license description - once
if (!licensePrintedForApplicationClass.contains(applicationClass)) {
licensePrintedForApplicationClass.add(applicationClass);
if (license.shouldLimitsBePrintedOnInit())
System.out.print(license.getDescription());
}
// Check license validity
try {
license.check(applicationClass, getNumberOfActiveUsers() + 1,
VERSION_MAJOR, VERSION_MINOR, "IT Mill Toolkit", null);
} catch (LicenseFileHasNotBeenRead e) {
application.close();
throw e;
} catch (LicenseSignatureIsInvalid e) {
application.close();
throw e;
} catch (InvalidLicenseFile e) {
application.close();
throw e;
} catch (LicenseViolation e) {
application.close();
throw e;
}
}
/**
* Get the number of active application-user pairs.
*
* This returns total number of all applications in the server that are
* considered to be active. For an application to be active, it must have
* been accessed less than ACTIVE_USER_REQUEST_INTERVAL ms.
*
* @return Number of active application instances in the server.
*/
private int getNumberOfActiveUsers() {
Set apps = applicationToLastRequestDate.keySet();
int active = 0;
long now = System.currentTimeMillis();
for (Iterator i = apps.iterator(); i.hasNext();) {
Date lastReq = (Date) applicationToLastRequestDate.get(i.next());
if (now - lastReq.getTime() < ACTIVE_USER_REQUEST_INTERVAL)
active++;
}
return active;
}
/** End application */
private void endApplication(HttpServletRequest request,
HttpServletResponse response, Application application)
throws IOException {
String logoutUrl = application.getLogoutURL();
if (logoutUrl == null)
logoutUrl = application.getURL().toString();
HttpSession session = request.getSession();
if (session != null) {
LinkedList applications = (LinkedList) session
.getAttribute(SESSION_ATTR_APPS);
if (applications != null)
applications.remove(application);
}
response.sendRedirect(response.encodeRedirectURL(logoutUrl));
}
/**
* Get the existing application or create a new one. Get a window within an
* application based on the requested URI.
*
* @param request
* HTTP Request.
* @param application
* Application to query for window.
* @return Window mathing the given URI or null if not found.
*/
private Window getApplicationWindow(HttpServletRequest request,
Application application) throws ServletException {
Window window = null;
// Find the window where the request is handled
String path = request.getPathInfo();
// Main window as the URI is empty
if (path == null || path.length() == 0 || path.equals("/"))
window = application.getMainWindow();
// Try to search by window name
else {
String windowName = null;
if (path.charAt(0) == '/')
path = path.substring(1);
int index = path.indexOf('/');
if (index < 0) {
windowName = path;
path = "";
} else {
windowName = path.substring(0, index);
path = path.substring(index + 1);
}
window = application.getWindow(windowName);
if (window == null) {
// If the window has existed, and is now removed
// send a blank page
if (allWindows.contains(windowName))
return null;
// By default, we use main window
window = application.getMainWindow();
} else if (!window.isVisible()) {
// Implicitly painting without actually invoking paint()
window.requestRepaintRequests();
// If the window is invisible send a blank page
return null;
}
}
// Create and open new debug window for application if requested
if (this.debugMode
&& application.getWindow(DebugWindow.WINDOW_NAME) == null)
try {
DebugWindow debugWindow = new DebugWindow(application, request
.getSession(false), this);
debugWindow.setWidth(370);
debugWindow.setHeight(480);
application.addWindow(debugWindow);
} catch (Exception e) {
throw new ServletException(
"Failed to create debug window for application", e);
}
return window;
}
/**
* Get relative location of a theme resource.
*
* @param theme
* Theme name
* @param resource
* Theme resource
* @return External URI specifying the resource
*/
public String getResourceLocation(String theme, ThemeResource resource) {
if (resourcePath == null)
return resource.getResourceId();
return resourcePath + theme + "/" + resource.getResourceId();
}
/**
* Check if web adapter is in debug mode. Extra output is generated to log
* when debug mode is enabled.
*
* @return Debug mode
*/
public boolean isDebugMode() {
return debugMode;
}
/**
* Returns the theme source.
*
* @return ThemeSource
*/
public ThemeSource getThemeSource() {
return themeSource;
}
protected void addDirtyWindow(Application application, Window window) {
synchronized (applicationToDirtyWindowSetMap) {
HashSet dirtyWindows = (HashSet) applicationToDirtyWindowSetMap
.get(application);
if (dirtyWindows == null) {
dirtyWindows = new HashSet();
applicationToDirtyWindowSetMap.put(application, dirtyWindows);
}
dirtyWindows.add(window);
}
}
protected void removeDirtyWindow(Application application, Window window) {
synchronized (applicationToDirtyWindowSetMap) {
HashSet dirtyWindows = (HashSet) applicationToDirtyWindowSetMap
.get(application);
if (dirtyWindows != null)
dirtyWindows.remove(window);
}
}
/**
* @see com.itmill.toolkit.Application.WindowAttachListener#windowAttached(Application.WindowAttachEvent)
*/
public void windowAttached(WindowAttachEvent event) {
Window win = event.getWindow();
win.addListener((Paintable.RepaintRequestListener) this);
// Add to window names
allWindows.add(win.getName());
// Add window to dirty window references if it is visible
// Or request the window to pass on the repaint requests
if (win.isVisible())
addDirtyWindow(event.getApplication(), win);
else
win.requestRepaintRequests();
}
/**
* @see com.itmill.toolkit.Application.WindowDetachListener#windowDetached(Application.WindowDetachEvent)
*/
public void windowDetached(WindowDetachEvent event) {
event.getWindow().removeListener(
(Paintable.RepaintRequestListener) this);
// Add dirty window reference for closing the window
addDirtyWindow(event.getApplication(), event.getWindow());
}
/**
* @see com.itmill.toolkit.terminal.Paintable.RepaintRequestListener#repaintRequested(Paintable.RepaintRequestEvent)
*/
public void repaintRequested(RepaintRequestEvent event) {
Paintable p = event.getPaintable();
Application app = null;
if (p instanceof Window)
app = ((Window) p).getApplication();
if (app != null)
addDirtyWindow(app, ((Window) p));
Object lock = applicationToServerCommandStreamLock.get(app);
if (lock != null)
synchronized (lock) {
lock.notifyAll();
}
}
/** Get the list of dirty windows in application */
protected Set getDirtyWindows(Application app) {
HashSet dirtyWindows;
synchronized (applicationToDirtyWindowSetMap) {
dirtyWindows = (HashSet) applicationToDirtyWindowSetMap.get(app);
}
return dirtyWindows;
}
/** Remove a window from the list of dirty windows */
private void windowPainted(Application app, Window window) {
removeDirtyWindow(app, window);
}
/**
* Generate server commands stream. If the server commands are not
* requested, return false
*/
private boolean handleServerCommands(HttpServletRequest request,
HttpServletResponse response) {
// Server commands are allways requested with certain parameter
if (request.getParameter(SERVER_COMMAND_PARAM) == null)
return false;
// Get the application
Application application;
try {
application = getApplication(request);
} catch (MalformedURLException e) {
return false;
}
if (application == null)
return false;
// Create continuous server commands stream
try {
// Writer for writing the stream
PrintWriter w = new PrintWriter(response.getOutputStream());
// Print necessary http page headers and padding
w.println("<html><head></head><body>");
for (int i = 0; i < SERVER_COMMAND_HEADER_PADDING; i++)
w.print(' ');
// Clock for synchronizing the stream
Object lock = new Object();
synchronized (applicationToServerCommandStreamLock) {
Object oldlock = applicationToServerCommandStreamLock
.get(application);
if (oldlock != null)
synchronized (oldlock) {
oldlock.notifyAll();
}
applicationToServerCommandStreamLock.put(application, lock);
}
while (applicationToServerCommandStreamLock.get(application) == lock
&& application.isRunning()) {
synchronized (application) {
// Session expiration
Date lastRequest = (Date) applicationToLastRequestDate
.get(application);
if (lastRequest != null
&& lastRequest.getTime()
+ request.getSession()
.getMaxInactiveInterval() * 1000 < System
.currentTimeMillis()) {
// Session expired, close application
application.close();
} else {
// Application still alive - keep updating windows
Set dws = getDirtyWindows(application);
if (dws != null && !dws.isEmpty()) {
// For one of the dirty windows (in each
// application)
// request redraw
Window win = (Window) dws.iterator().next();
w
.println("<script>\n"
+ ThemeFunctionLibrary
.getWindowRefreshScript(
application,
win,
WebBrowserProbe
.getTerminalType(request
.getSession()))
+ "</script>");
removeDirtyWindow(application, win);
// Windows that are closed immediately are "painted"
// now
if (win.getApplication() == null
|| !win.isVisible())
win.requestRepaintRequests();
}
}
}
// Send the generated commands and newline immediately to
// browser
w.println(" ");
w.flush();
response.flushBuffer();
synchronized (lock) {
try {
lock.wait(SERVER_COMMAND_STREAM_MAINTAIN_PERIOD);
} catch (InterruptedException ignored) {
}
}
}
} catch (IOException ignore) {
// In case of an Exceptions the server command stream is
// terminated
synchronized (applicationToServerCommandStreamLock) {
if (applicationToServerCommandStreamLock.get(application) == application)
applicationToServerCommandStreamLock.remove(application);
}
}
return true;
}
private class SessionBindingListener implements HttpSessionBindingListener {
private LinkedList applications;
protected SessionBindingListener(LinkedList applications) {
this.applications = applications;
}
/**
* @see javax.servlet.http.HttpSessionBindingListener#valueBound(HttpSessionBindingEvent)
*/
public void valueBound(HttpSessionBindingEvent arg0) {
// We are not interested in bindings
}
/**
* @see javax.servlet.http.HttpSessionBindingListener#valueUnbound(HttpSessionBindingEvent)
*/
public void valueUnbound(HttpSessionBindingEvent event) {
// If the binding listener is unbound from the session, the
// session must be closing
if (event.getName().equals(SESSION_BINDING_LISTENER)) {
// Close all applications
Object[] apps = applications.toArray();
for (int i = 0; i < apps.length; i++) {
if (apps[i] != null) {
// Close app
((Application) apps[i]).close();
// Stop application server commands stream
Object lock = applicationToServerCommandStreamLock
.get(apps[i]);
if (lock != null)
synchronized (lock) {
lock.notifyAll();
}
applicationToServerCommandStreamLock.remove(apps[i]);
// Remove application from applications list
applications.remove(apps[i]);
}
}
}
}
}
/** Implementation of ParameterHandler.ErrorEvent interface. */
public class ParameterHandlerErrorImpl implements
ParameterHandler.ErrorEvent {
private ParameterHandler owner;
private Throwable throwable;
private ParameterHandlerErrorImpl(ParameterHandler owner,
Throwable throwable) {
this.owner = owner;
this.throwable = throwable;
}
/**
* @see com.itmill.toolkit.terminal.Terminal.ErrorEvent#getThrowable()
*/
public Throwable getThrowable() {
return this.throwable;
}
/**
* @see com.itmill.toolkit.terminal.ParameterHandler.ErrorEvent#getParameterHandler()
*/
public ParameterHandler getParameterHandler() {
return this.owner;
}
}
/** Implementation of URIHandler.ErrorEvent interface. */
public class URIHandlerErrorImpl implements URIHandler.ErrorEvent {
private URIHandler owner;
private Throwable throwable;
private URIHandlerErrorImpl(URIHandler owner, Throwable throwable) {
this.owner = owner;
this.throwable = throwable;
}
/**
* @see com.itmill.toolkit.terminal.Terminal.ErrorEvent#getThrowable()
*/
public Throwable getThrowable() {
return this.throwable;
}
/**
* @see com.itmill.toolkit.terminal.URIHandler.ErrorEvent#getURIHandler()
*/
public URIHandler getURIHandler() {
return this.owner;
}
}
/**
* Get AJAX application manager for an application.
*
* If this application has not been running in ajax mode before, new manager
* is created and web adapter stops listening to changes.
*
* @param application
* @return AJAX Application Manager
*/
private AjaxApplicationManager getApplicationManager(Application application) {
AjaxApplicationManager mgr = (AjaxApplicationManager) applicationToAjaxAppMgrMap
.get(application);
// This application is going from Web to AJAX mode, create new manager
if (mgr == null) {
// Create new manager
mgr = new AjaxApplicationManager(application);
applicationToAjaxAppMgrMap.put(application, mgr);
// Stop sending changes to this servlet because manager will take
// control
application.removeListener((Application.WindowAttachListener) this);
application.removeListener((Application.WindowDetachListener) this);
// Manager takes control over the application
mgr.takeControl();
}
return mgr;
}
}
| false | true | protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Transformer and output stream for the result
UIDLTransformer transformer = null;
HttpVariableMap variableMap = null;
OutputStream out = response.getOutputStream();
HashSet currentlyDirtyWindowsForThisApplication = new HashSet();
Application application = null;
try {
// Handle resource requests
if (handleResourceRequest(request, response))
return;
// Handle server commands
if (handleServerCommands(request, response))
return;
// Get the application
application = getApplication(request);
// Create application if it doesn't exist
if (application == null)
application = createApplication(request);
// Set the last application request date
applicationToLastRequestDate.put(application, new Date());
// Invoke context transaction listeners
((WebApplicationContext) application.getContext())
.startTransaction(application, request);
// Is this a download request from application
DownloadStream download = null;
// The rest of the process is synchronized with the application
// in order to guarantee that no parallel variable handling is
// made
synchronized (application) {
// Handle UIDL requests?
String resourceId = request.getPathInfo();
if (resourceId != null && resourceId.startsWith(AJAX_UIDL_URI)) {
getApplicationManager(application).handleUidlRequest(
request, response);
return;
}
// Get the variable map
variableMap = getVariableMap(application, request);
if (variableMap == null)
return;
// Change all variables based on request parameters
Map unhandledParameters = variableMap.handleVariables(request,
application);
// Check/handle client side feature checks
WebBrowserProbe
.handleProbeRequest(request, unhandledParameters);
// Handle the URI if the application is still running
if (application.isRunning())
download = handleURI(application, request, response);
// If this is not a download request
if (download == null) {
// Window renders are not cacheable
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
// Find the window within the application
Window window = null;
if (application.isRunning())
window = getApplicationWindow(request, application);
// Handle the unhandled parameters if the application is
// still running
if (window != null && unhandledParameters != null
&& !unhandledParameters.isEmpty()) {
try {
window.handleParameters(unhandledParameters);
} catch (Throwable t) {
application
.terminalError(new ParameterHandlerErrorImpl(
window, t));
}
}
// Remove application if it has stopped
if (!application.isRunning()) {
endApplication(request, response, application);
return;
}
// Return blank page, if no window found
if (window == null) {
response.setContentType("text/html");
BufferedWriter page = new BufferedWriter(
new OutputStreamWriter(out));
page.write("<html><head><script>");
page
.write(ThemeFunctionLibrary
.generateWindowScript(
null,
application,
this,
WebBrowserProbe
.getTerminalType(request
.getSession())));
page.write("</script></head><body>");
page
.write("The requested window has been removed from application.");
page.write("</body></html>");
page.close();
return;
}
// Get the terminal type for the window
WebBrowser terminalType = (WebBrowser) window.getTerminal();
// Set terminal type for the window, if not already set
if (terminalType == null) {
terminalType = WebBrowserProbe.getTerminalType(request
.getSession());
window.setTerminal(terminalType);
}
// Find theme
Theme theme = themeSource
.getThemeByName(window.getTheme() != null ? window
.getTheme() : DEFAULT_THEME);
if (theme == null)
throw new ServletException("Default theme (named '"
+ DEFAULT_THEME + "') can not be found");
// If UIDL rendering mode is preferred, a page for it is
// rendered
String renderingMode = theme.getPreferredMode(terminalType,
themeSource);
if (Theme.MODE_UIDL.equals(renderingMode)) {
response.setContentType("text/html");
BufferedWriter page = new BufferedWriter(
new OutputStreamWriter(out));
page
.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" "
+ "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
page.write("<html><head>\n<title>"
+ window.getCaption() + "</title>\n");
Theme t = theme;
Vector themes = new Vector();
themes.add(t);
while (t.getParent() != null) {
String parentName = t.getParent();
t = themeSource.getThemeByName(parentName);
themes.add(t);
}
for (int k=themes.size()-1; k>=0; k--) {
t = (Theme) themes.get(k);
Collection files = t.getFileNames(terminalType,
Theme.MODE_UIDL);
for (Iterator i = files.iterator(); i.hasNext();) {
String file = (String) i.next();
if (file.endsWith(".css"))
page
.write("<link rel=\"stylesheet\" href=\""
+ getResourceLocation(t
.getName(),
new ThemeResource(
file))
+ "\" type=\"text/css\" />\n");
else if (file.endsWith(".js"))
page
.write("<script src=\""
+ getResourceLocation(t
.getName(),
new ThemeResource(
file))
+ "\" type=\"text/javascript\"></script>\n");
}
}
page.write("</head><body>\n");
page
.write("<div id=\"ajax-wait\"><div>Loading...</div></div>\n");
page.write("<div id=\"ajax-window\"></div>\n");
page.write("<script language=\"JavaScript\">\n");
page
.write("var client = new ITMillToolkitClient("
+ "document.getElementById('ajax-window'),"
+ "\""
+ getApplicationUrl(request)
+ "/UIDL/"
+ "\",\""
+ resourcePath + ((Theme)themes.get(themes.size()-1)).getName() + "/"
+ "client/\",document.getElementById('ajax-wait'));\n");
// TODO Should we also show debug information?
/*
* var debug =
* document.location.href.split("debug=")[1]; if (debug &&
* debug.split("&")[0] == "1") client.debugEnabled =
* true;
*/
for (int k=themes.size()-1; k>=0; k--) {
t = (Theme) themes.get(k);
String themeObjName = t.getName() + "Theme";
themeObjName = themeObjName.substring(0,1).toUpperCase() + themeObjName.substring(1);
page
.write(" (new "+themeObjName+"(\"" + resourcePath + ((Theme)themes.get(k)).getName() + "/\")).registerTo(client);\n");
}
page.write("client.start();\n");
page.write("</script>\n");
page.write("</body></html>\n");
page.close();
return;
}
// If other than XSLT or UIDL mode is requested
if (!Theme.MODE_XSLT.equals(renderingMode)) {
// TODO More informal message should be given is browser
// is not supported
response.setContentType("text/html");
BufferedWriter page = new BufferedWriter(
new OutputStreamWriter(out));
page.write("<html><head></head><body>");
page.write("Unsupported browser.");
page.write("</body></html>");
page.close();
return;
}
// Initialize Transformer
UIDLTransformerType transformerType = new UIDLTransformerType(
terminalType, theme);
transformer = this.transformerFactory
.getTransformer(transformerType);
// Set the response type
response.setContentType(terminalType.getContentType());
// Create UIDL writer
WebPaintTarget paintTarget = transformer
.getPaintTarget(variableMap);
// Assure that the correspoding debug window will be
// repainted property
// by clearing it before the actual paint.
DebugWindow debugWindow = (DebugWindow) application
.getWindow(DebugWindow.WINDOW_NAME);
if (debugWindow != null && debugWindow != window) {
debugWindow.setWindowUIDL(window, "Painting...");
}
// Paint window
window.paint(paintTarget);
paintTarget.close();
// For exception handling, memorize the current dirty status
Collection dirtyWindows = (Collection) applicationToDirtyWindowSetMap
.get(application);
if (dirtyWindows == null) {
dirtyWindows = new HashSet();
applicationToDirtyWindowSetMap.put(application,
dirtyWindows);
}
currentlyDirtyWindowsForThisApplication
.addAll(dirtyWindows);
// Window is now painted
windowPainted(application, window);
// Debug
if (debugWindow != null && debugWindow != window) {
debugWindow
.setWindowUIDL(window, paintTarget.getUIDL());
}
// Set the function library state for this thread
ThemeFunctionLibrary.setState(application, window,
transformerType.getWebBrowser(), request
.getSession(), this, transformerType
.getTheme().getName());
}
}
// For normal requests, transform the window
if (download == null) {
// Transform and output the result to browser
// Note that the transform and transfer of the result is
// not synchronized with the variable map. This allows
// parallel transfers and transforms for better performance,
// but requires that all calls from the XSL to java are
// thread-safe
transformer.transform(out);
}
// For download request, transfer the downloaded data
else {
handleDownload(download, request, response);
}
} catch (UIDLTransformerException te) {
try {
// Write the error report to client
response.setContentType("text/html");
BufferedWriter err = new BufferedWriter(new OutputStreamWriter(
out));
err
.write("<html><head><title>Application Internal Error</title></head><body>");
err.write("<h1>" + te.getMessage() + "</h1>");
err.write(te.getHTMLDescription());
err.write("</body></html>");
err.close();
} catch (Throwable t) {
Log.except("Failed to write error page: " + t
+ ". Original exception was: ", te);
}
// Add previously dirty windows to dirtyWindowList in order
// to make sure that eventually they are repainted
Application currentApplication = getApplication(request);
for (Iterator iter = currentlyDirtyWindowsForThisApplication
.iterator(); iter.hasNext();) {
Window dirtyWindow = (Window) iter.next();
addDirtyWindow(currentApplication, dirtyWindow);
}
} catch (Throwable e) {
// Re-throw other exceptions
throw new ServletException(e);
} finally {
// Release transformer
if (transformer != null)
transformerFactory.releaseTransformer(transformer);
// Notify transaction end
if (application != null)
((WebApplicationContext) application.getContext())
.endTransaction(application, request);
// Clean the function library state for this thread
// for security reasons
ThemeFunctionLibrary.cleanState();
}
}
| protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Transformer and output stream for the result
UIDLTransformer transformer = null;
HttpVariableMap variableMap = null;
OutputStream out = response.getOutputStream();
HashSet currentlyDirtyWindowsForThisApplication = new HashSet();
Application application = null;
try {
// Handle resource requests
if (handleResourceRequest(request, response))
return;
// Handle server commands
if (handleServerCommands(request, response))
return;
// Get the application
application = getApplication(request);
// Create application if it doesn't exist
if (application == null)
application = createApplication(request);
// Set the last application request date
applicationToLastRequestDate.put(application, new Date());
// Invoke context transaction listeners
((WebApplicationContext) application.getContext())
.startTransaction(application, request);
// Is this a download request from application
DownloadStream download = null;
// The rest of the process is synchronized with the application
// in order to guarantee that no parallel variable handling is
// made
synchronized (application) {
// Handle UIDL requests?
String resourceId = request.getPathInfo();
if (resourceId != null && resourceId.startsWith(AJAX_UIDL_URI)) {
getApplicationManager(application).handleUidlRequest(
request, response);
return;
}
// Get the variable map
variableMap = getVariableMap(application, request);
if (variableMap == null)
return;
// Change all variables based on request parameters
Map unhandledParameters = variableMap.handleVariables(request,
application);
// Check/handle client side feature checks
WebBrowserProbe
.handleProbeRequest(request, unhandledParameters);
// Handle the URI if the application is still running
if (application.isRunning())
download = handleURI(application, request, response);
// If this is not a download request
if (download == null) {
// Window renders are not cacheable
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
// Find the window within the application
Window window = null;
if (application.isRunning())
window = getApplicationWindow(request, application);
// Handle the unhandled parameters if the application is
// still running
if (window != null && unhandledParameters != null
&& !unhandledParameters.isEmpty()) {
try {
window.handleParameters(unhandledParameters);
} catch (Throwable t) {
application
.terminalError(new ParameterHandlerErrorImpl(
window, t));
}
}
// Remove application if it has stopped
if (!application.isRunning()) {
endApplication(request, response, application);
return;
}
// Return blank page, if no window found
if (window == null) {
response.setContentType("text/html");
BufferedWriter page = new BufferedWriter(
new OutputStreamWriter(out));
page.write("<html><head><script>");
page
.write(ThemeFunctionLibrary
.generateWindowScript(
null,
application,
this,
WebBrowserProbe
.getTerminalType(request
.getSession())));
page.write("</script></head><body>");
page
.write("The requested window has been removed from application.");
page.write("</body></html>");
page.close();
return;
}
// Get the terminal type for the window
WebBrowser terminalType = (WebBrowser) window.getTerminal();
// Set terminal type for the window, if not already set
if (terminalType == null) {
terminalType = WebBrowserProbe.getTerminalType(request
.getSession());
window.setTerminal(terminalType);
}
// Find theme
Theme theme = themeSource
.getThemeByName(window.getTheme() != null ? window
.getTheme() : DEFAULT_THEME);
if (theme == null)
throw new ServletException("Default theme (named '"
+ DEFAULT_THEME + "') can not be found");
// If UIDL rendering mode is preferred, a page for it is
// rendered
String renderingMode = theme.getPreferredMode(terminalType,
themeSource);
if (Theme.MODE_UIDL.equals(renderingMode)) {
response.setContentType("text/html");
BufferedWriter page = new BufferedWriter(
new OutputStreamWriter(out));
page
.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" "
+ "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
page.write("<html><head>\n<title>"
+ window.getCaption() + "</title>\n");
Theme t = theme;
Vector themes = new Vector();
themes.add(t);
while (t.getParent() != null) {
String parentName = t.getParent();
t = themeSource.getThemeByName(parentName);
themes.add(t);
}
for (int k=themes.size()-1; k>=0; k--) {
t = (Theme) themes.get(k);
Collection files = t.getFileNames(terminalType,
Theme.MODE_UIDL);
for (Iterator i = files.iterator(); i.hasNext();) {
String file = (String) i.next();
if (file.endsWith(".css"))
page
.write("<link rel=\"stylesheet\" href=\""
+ getResourceLocation(t
.getName(),
new ThemeResource(
file))
+ "\" type=\"text/css\" />\n");
else if (file.endsWith(".js"))
page
.write("<script src=\""
+ getResourceLocation(t
.getName(),
new ThemeResource(
file))
+ "\" type=\"text/javascript\"></script>\n");
}
}
page.write("</head><body>\n");
page
.write("<div id=\"ajax-wait\"><div>Loading...</div></div>\n");
page.write("<div id=\"ajax-window\"></div>\n");
page.write("<script language=\"JavaScript\">\n");
String appUrl = getApplicationUrl(request).toString();
page
.write("var client = new ITMillToolkitClient("
+ "document.getElementById('ajax-window'),"
+ "\""
+ appUrl + (appUrl.endsWith("/") ? "" : "/")
+ "UIDL/"
+ "\",\""
+ resourcePath + ((Theme)themes.get(themes.size()-1)).getName() + "/"
+ "client/\",document.getElementById('ajax-wait'));\n");
// TODO Should we also show debug information?
/*
* var debug =
* document.location.href.split("debug=")[1]; if (debug &&
* debug.split("&")[0] == "1") client.debugEnabled =
* true;
*/
for (int k=themes.size()-1; k>=0; k--) {
t = (Theme) themes.get(k);
String themeObjName = t.getName() + "Theme";
themeObjName = themeObjName.substring(0,1).toUpperCase() + themeObjName.substring(1);
page
.write(" (new "+themeObjName+"(\"" + resourcePath + ((Theme)themes.get(k)).getName() + "/\")).registerTo(client);\n");
}
page.write("client.start();\n");
page.write("</script>\n");
page.write("</body></html>\n");
page.close();
return;
}
// If other than XSLT or UIDL mode is requested
if (!Theme.MODE_XSLT.equals(renderingMode)) {
// TODO More informal message should be given is browser
// is not supported
response.setContentType("text/html");
BufferedWriter page = new BufferedWriter(
new OutputStreamWriter(out));
page.write("<html><head></head><body>");
page.write("Unsupported browser.");
page.write("</body></html>");
page.close();
return;
}
// Initialize Transformer
UIDLTransformerType transformerType = new UIDLTransformerType(
terminalType, theme);
transformer = this.transformerFactory
.getTransformer(transformerType);
// Set the response type
response.setContentType(terminalType.getContentType());
// Create UIDL writer
WebPaintTarget paintTarget = transformer
.getPaintTarget(variableMap);
// Assure that the correspoding debug window will be
// repainted property
// by clearing it before the actual paint.
DebugWindow debugWindow = (DebugWindow) application
.getWindow(DebugWindow.WINDOW_NAME);
if (debugWindow != null && debugWindow != window) {
debugWindow.setWindowUIDL(window, "Painting...");
}
// Paint window
window.paint(paintTarget);
paintTarget.close();
// For exception handling, memorize the current dirty status
Collection dirtyWindows = (Collection) applicationToDirtyWindowSetMap
.get(application);
if (dirtyWindows == null) {
dirtyWindows = new HashSet();
applicationToDirtyWindowSetMap.put(application,
dirtyWindows);
}
currentlyDirtyWindowsForThisApplication
.addAll(dirtyWindows);
// Window is now painted
windowPainted(application, window);
// Debug
if (debugWindow != null && debugWindow != window) {
debugWindow
.setWindowUIDL(window, paintTarget.getUIDL());
}
// Set the function library state for this thread
ThemeFunctionLibrary.setState(application, window,
transformerType.getWebBrowser(), request
.getSession(), this, transformerType
.getTheme().getName());
}
}
// For normal requests, transform the window
if (download == null) {
// Transform and output the result to browser
// Note that the transform and transfer of the result is
// not synchronized with the variable map. This allows
// parallel transfers and transforms for better performance,
// but requires that all calls from the XSL to java are
// thread-safe
transformer.transform(out);
}
// For download request, transfer the downloaded data
else {
handleDownload(download, request, response);
}
} catch (UIDLTransformerException te) {
try {
// Write the error report to client
response.setContentType("text/html");
BufferedWriter err = new BufferedWriter(new OutputStreamWriter(
out));
err
.write("<html><head><title>Application Internal Error</title></head><body>");
err.write("<h1>" + te.getMessage() + "</h1>");
err.write(te.getHTMLDescription());
err.write("</body></html>");
err.close();
} catch (Throwable t) {
Log.except("Failed to write error page: " + t
+ ". Original exception was: ", te);
}
// Add previously dirty windows to dirtyWindowList in order
// to make sure that eventually they are repainted
Application currentApplication = getApplication(request);
for (Iterator iter = currentlyDirtyWindowsForThisApplication
.iterator(); iter.hasNext();) {
Window dirtyWindow = (Window) iter.next();
addDirtyWindow(currentApplication, dirtyWindow);
}
} catch (Throwable e) {
// Re-throw other exceptions
throw new ServletException(e);
} finally {
// Release transformer
if (transformer != null)
transformerFactory.releaseTransformer(transformer);
// Notify transaction end
if (application != null)
((WebApplicationContext) application.getContext())
.endTransaction(application, request);
// Clean the function library state for this thread
// for security reasons
ThemeFunctionLibrary.cleanState();
}
}
|
diff --git a/javasvn/src/org/tmatesoft/svn/core/internal/wc/SVNUpdateEditor.java b/javasvn/src/org/tmatesoft/svn/core/internal/wc/SVNUpdateEditor.java
index 059c32b5b..385c12a8c 100644
--- a/javasvn/src/org/tmatesoft/svn/core/internal/wc/SVNUpdateEditor.java
+++ b/javasvn/src/org/tmatesoft/svn/core/internal/wc/SVNUpdateEditor.java
@@ -1,789 +1,789 @@
package org.tmatesoft.svn.core.internal.wc;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.tmatesoft.svn.core.SVNProperty;
import org.tmatesoft.svn.core.diff.ISVNRAData;
import org.tmatesoft.svn.core.diff.SVNDiffWindow;
import org.tmatesoft.svn.core.internal.ws.fs.SVNRAFileData;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.core.io.SVNCommitInfo;
import org.tmatesoft.svn.core.io.SVNException;
import org.tmatesoft.svn.core.io.SVNNodeKind;
import org.tmatesoft.svn.core.wc.SVNEventAction;
import org.tmatesoft.svn.core.wc.SVNStatusType;
import org.tmatesoft.svn.util.DebugLog;
import org.tmatesoft.svn.util.PathUtil;
public class SVNUpdateEditor implements ISVNEditor {
private String mySwitchURL;
private String myTarget;
private String myTargetURL;
private boolean myIsRecursive;
private SVNWCAccess myWCAccess;
private SVNDirectoryInfo myCurrentDirectory;
private SVNFileInfo myCurrentFile;
private long myTargetRevision;
private boolean myIsRootOpen;
private boolean myIsTargetDeleted;
public SVNUpdateEditor(SVNWCAccess wcAccess, String switchURL, boolean recursive) throws SVNException {
myWCAccess = wcAccess;
myIsRecursive = recursive;
myTarget = wcAccess.getTargetName();
mySwitchURL = switchURL;
myTargetRevision = -1;
SVNEntry entry = wcAccess.getAnchor().getEntries().getEntry("", true);
myTargetURL = entry.getURL();
if (myTarget != null) {
myTargetURL = PathUtil.append(myTargetURL, PathUtil.encode(myTarget));
}
wcAccess.getTarget().getEntries().close();
if ("".equals(myTarget)) {
myTarget = null;
}
}
public void targetRevision(long revision) throws SVNException {
myTargetRevision = revision;
}
public long getTargetRevision() {
return myTargetRevision;
}
public void openRoot(long revision) throws SVNException {
myIsRootOpen = true;
myCurrentDirectory = createDirectoryInfo(null, "", false);
if (myTarget == null) {
SVNEntries entries = myCurrentDirectory.getDirectory().getEntries();
SVNEntry entry = entries.getEntry("", true);
entry.setRevision(myTargetRevision);
entry.setURL(myCurrentDirectory.URL);
entry.setIncomplete(true);
if (mySwitchURL != null) {
clearWCProperty();
}
entries.save(true);
}
}
public void deleteEntry(String path, long revision) throws SVNException {
path = PathUtil.removeLeadingSlash(path);
path = PathUtil.removeTrailingSlash(path);
String name = PathUtil.tail(path);
SVNEntry entry = myCurrentDirectory.getDirectory().getEntries().getEntry(name, true);
DebugLog.log("deleting : " + path);
if (entry == null) {
return;
}
SVNLog log = myCurrentDirectory.getLog(true);
Map attributes = new HashMap();
attributes.put(SVNLog.NAME_ATTR, name);
log.addCommand(SVNLog.DELETE_ENTRY, attributes, false);
SVNNodeKind kind = entry.getKind();
boolean isDeleted = entry.isDeleted();
if (path.equals(myTarget)) {
attributes.put(SVNLog.NAME_ATTR, name);
attributes.put(SVNProperty.shortPropertyName(SVNProperty.KIND), kind == SVNNodeKind.DIR ? SVNProperty.KIND_DIR : SVNProperty.KIND_FILE);
attributes.put(SVNProperty.shortPropertyName(SVNProperty.REVISION), Long.toString(myTargetRevision));
attributes.put(SVNProperty.shortPropertyName(SVNProperty.DELETED), Boolean.TRUE.toString());
log.addCommand(SVNLog.MODIFY_ENTRY, attributes, false);
myIsTargetDeleted = true;
}
if (mySwitchURL != null && kind == SVNNodeKind.DIR) {
myCurrentDirectory.getDirectory().destroy(name, true);
}
log.save();
myCurrentDirectory.runLogs();
if (isDeleted) {
// entry was deleted, but it was already deleted, no need to make a notification.
return;
}
myWCAccess.handleEvent(SVNEventFactory.createUpdateDeleteEvent(myWCAccess, myCurrentDirectory.getDirectory(), name));
}
public void addDir(String path, String copyFromPath, long copyFromRevision) throws SVNException {
path = PathUtil.removeLeadingSlash(path);
path = PathUtil.removeTrailingSlash(path);
SVNDirectory parentDir = myCurrentDirectory.getDirectory();
myCurrentDirectory = createDirectoryInfo(myCurrentDirectory, path, true);
String name = PathUtil.tail(path);
File file = parentDir.getFile(name, false);
if (file.exists()) {
SVNErrorManager.error("svn: Failed to add directory '" + path + "': object of the same name already exists");
} else if (".svn".equals(name)) {
SVNErrorManager.error("svn: Failed to add directory '" + path + "': object of the same name as the administrative directory");
}
SVNEntry entry = parentDir.getEntries().getEntry(name, true);
if (entry != null) {
if (entry.isScheduledForAddition()) {
SVNErrorManager.error(0, null);
}
} else {
entry = parentDir.getEntries().addEntry(name);
}
entry.setKind(SVNNodeKind.DIR);
entry.setAbsent(false);
entry.setDeleted(false);
parentDir.getEntries().save(true);
SVNDirectory dir = parentDir.createChildDirectory(name, myCurrentDirectory.URL, myTargetRevision);
if (dir == null) {
SVNErrorManager.error(0, null);
}
dir.lock();
myWCAccess.handleEvent(SVNEventFactory.createUpdateAddEvent(myWCAccess, parentDir, SVNNodeKind.DIR, entry));
}
public void openDir(String path, long revision) throws SVNException {
path = PathUtil.removeLeadingSlash(path);
path = PathUtil.removeTrailingSlash(path);
myCurrentDirectory = createDirectoryInfo(myCurrentDirectory, path, false);
SVNEntries entries = myCurrentDirectory.getDirectory().getEntries();
SVNEntry entry = entries.getEntry("", true);
entry.setRevision(myTargetRevision);
entry.setURL(myCurrentDirectory.URL);
entry.setIncomplete(true);
if (mySwitchURL != null) {
clearWCProperty();
}
entries.save(true);
}
public void absentDir(String path) throws SVNException {
absentEntry(path, SVNNodeKind.DIR);
}
public void absentFile(String path) throws SVNException {
absentEntry(path, SVNNodeKind.FILE);
}
private void absentEntry(String path, SVNNodeKind kind) throws SVNException {
path = PathUtil.removeLeadingSlash(path);
path = PathUtil.removeTrailingSlash(path);
String name = PathUtil.tail(path);
SVNEntries entries = myCurrentDirectory.getDirectory().getEntries();
SVNEntry entry = entries.getEntry(name, true);
if (entry != null && entry.isScheduledForAddition()) {
SVNErrorManager.error(0, null);
}
if (entry == null) {
entries.addEntry(name);
}
entry.setKind(kind);
entry.setDeleted(false);
entry.setRevision(myTargetRevision);
entry.setAbsent(true);
entries.save(true);
}
public void changeDirProperty(String name, String value) throws SVNException {
myCurrentDirectory.propertyChanged(name, value);
}
private void clearWCProperty() throws SVNException {
if (myCurrentDirectory == null || myCurrentDirectory.getDirectory() == null) {
return;
}
SVNDirectory dir = myCurrentDirectory.getDirectory();
SVNEntries entires = dir.getEntries();
for (Iterator ents = entires.entries(true); ents.hasNext();) {
SVNEntry entry = (SVNEntry) ents.next();
if (entry.isFile() || "".equals(entry.getName())) {
SVNProperties props = dir.getWCProperties(entry.getName());
props.setPropertyValue(SVNProperty.WC_URL, null);
}
}
}
public void closeDir() throws SVNException {
Map modifiedWCProps = myCurrentDirectory.getChangedWCProperties();
Map modifiedEntryProps = myCurrentDirectory.getChangedEntryProperties();
Map modifiedProps = myCurrentDirectory.getChangedProperties();
SVNStatusType propStatus = SVNStatusType.UNCHANGED;
SVNDirectory dir = myCurrentDirectory.getDirectory();
if (modifiedWCProps != null || modifiedEntryProps != null || modifiedProps != null) {
SVNLog log = myCurrentDirectory.getLog(true);
if (modifiedProps != null && !modifiedProps.isEmpty()) {
SVNProperties props = dir.getProperties("", false);
Map locallyModified = dir.getBaseProperties("", false).compareTo(props);
myWCAccess.addExternals(dir, (String) modifiedProps.get(SVNProperty.EXTERNALS));
propStatus = dir.mergeProperties("", modifiedProps, locallyModified, true, log);
if (locallyModified == null || locallyModified.isEmpty()) {
Map command = new HashMap();
command.put(SVNLog.NAME_ATTR, "");
command.put(SVNProperty.shortPropertyName(SVNProperty.PROP_TIME), SVNLog.WC_TIMESTAMP);
log.addCommand(SVNLog.MODIFY_ENTRY, command, false);
}
}
log.logChangedEntryProperties("", modifiedEntryProps);
log.logChangedWCProperties("", modifiedWCProps);
log.save();
}
myCurrentDirectory.runLogs();
completeDirectory(myCurrentDirectory);
if (!myCurrentDirectory.IsAdded && propStatus != SVNStatusType.UNCHANGED) {
myWCAccess.handleEvent(SVNEventFactory.createUpdateModifiedEvent(myWCAccess, dir, "", SVNNodeKind.DIR, SVNEventAction.UPDATE_UPDATE,
null, SVNStatusType.UNCHANGED, propStatus, null));
}
myCurrentDirectory = myCurrentDirectory.Parent;
}
public SVNCommitInfo closeEdit() throws SVNException {
if (myTarget != null && !myWCAccess.getAnchor().getFile(myTarget, false).exists()) {
myCurrentDirectory = createDirectoryInfo(null, "", false);
deleteEntry(myTarget, myTargetRevision);
}
if (!myIsRootOpen) {
completeDirectory(myCurrentDirectory);
}
if (!myIsTargetDeleted) {
bumpDirectories();
}
return null;
}
public void addFile(String path, String copyFromPath, long copyFromRevision) throws SVNException {
path = PathUtil.removeLeadingSlash(path);
path = PathUtil.removeTrailingSlash(path);
myCurrentFile = createFileInfo(myCurrentDirectory, path, true);
}
public void openFile(String path, long revision) throws SVNException {
path = PathUtil.removeLeadingSlash(path);
path = PathUtil.removeTrailingSlash(path);
myCurrentFile = createFileInfo(myCurrentDirectory, path, false);
}
public void changeFileProperty(String commitPath, String name, String value) throws SVNException {
myCurrentFile.propertyChanged(name, value);
if (myWCAccess.getOptions().isUseCommitTimes() && SVNProperty.COMMITTED_DATE.equals(name)) {
myCurrentFile.CommitTime = value;
}
}
public void applyTextDelta(String commitPath, String baseChecksum) throws SVNException {
SVNDirectory dir = myCurrentFile.getDirectory();
SVNEntries entries = dir.getEntries();
SVNEntry entry = entries.getEntry(myCurrentFile.Name, true);
File baseFile = dir.getBaseFile(myCurrentFile.Name, false);
if (entry != null && entry.getChecksum() != null) {
if (baseChecksum == null) {
baseChecksum = entry.getChecksum();
}
String realChecksum = SVNFileUtil.computeChecksum(baseFile);
if (baseChecksum != null && (realChecksum == null || !realChecksum.equals(baseChecksum))) {
SVNErrorManager.error("svn: Checksum mismatch for '" + myCurrentFile.getPath() + "'; expected: '" + baseChecksum +"', actual: '" + realChecksum + "'");
}
}
File baseTmpFile = dir.getBaseFile(myCurrentFile.Name, true);
try {
SVNFileUtil.copy(baseFile, baseTmpFile, false);
if (!baseTmpFile.exists()) {
baseTmpFile.createNewFile();
}
} catch (IOException e) {
SVNErrorManager.error(0, e);
}
}
public OutputStream textDeltaChunk(String commitPath, SVNDiffWindow diffWindow) throws SVNException {
if (myCurrentFile.myDiffWindows == null) {
myCurrentFile.myDiffWindows = new ArrayList();
}
int number = myCurrentFile.myDiffWindows.size();
File file = myCurrentFile.getDirectory().getBaseFile(myCurrentFile.Name + "." + number + ".txtdelta", true);
myCurrentFile.myDiffWindows.add(diffWindow);
try {
return new FileOutputStream(file);
} catch (FileNotFoundException e) {
SVNErrorManager.error(0, e);
}
SVNErrorManager.error(0, null);
return null;
}
public void textDeltaEnd(String commitPath) throws SVNException {
if (myCurrentFile.myDiffWindows == null) {
return;
}
int index = 0;
File baseTmpFile = myCurrentFile.getDirectory().getBaseFile(myCurrentFile.Name, true);
File targetFile = myCurrentFile.getDirectory().getBaseFile(myCurrentFile.Name + ".tmp", true);
ISVNRAData baseData = new SVNRAFileData(baseTmpFile, false);
ISVNRAData target = new SVNRAFileData(targetFile, false);
for (Iterator windows = myCurrentFile.myDiffWindows.iterator(); windows.hasNext();) {
SVNDiffWindow window = (SVNDiffWindow) windows.next();
File dataFile = myCurrentFile.getDirectory().getBaseFile(myCurrentFile.Name + "." + index + ".txtdelta", true);
InputStream data = null;
try {
data = SVNFileUtil.openFileForReading(dataFile);
window.apply(baseData, target, data, target.length());
} finally {
SVNFileUtil.closeFile(data);
}
dataFile.delete();
index++;
}
try {
target.close();
baseData.close();
} catch (IOException e) {
SVNErrorManager.error(0, e);
}
try {
SVNFileUtil.rename(targetFile, baseTmpFile);
} catch (IOException e) {
SVNErrorManager.error(0, e);
}
}
public void closeFile(String commitPath, String textChecksum) throws SVNException {
// check checksum.
String checksum = null;
if (myCurrentFile.myDiffWindows != null && textChecksum != null) {
File baseTmpFile = myCurrentFile.getDirectory().getBaseFile(myCurrentFile.Name, true);
checksum = SVNFileUtil.computeChecksum(baseTmpFile);
if (!textChecksum.equals(checksum)) {
SVNErrorManager.error(0, null);
}
}
SVNDirectory dir = myCurrentFile.getDirectory();
SVNLog log = myCurrentDirectory.getLog(true);
// merge props.
Map modifiedWCProps = myCurrentFile.getChangedWCProperties();
Map modifiedEntryProps = myCurrentFile.getChangedEntryProperties();
Map modifiedProps = myCurrentFile.getChangedProperties();
String name = myCurrentFile.Name;
String commitTime = myCurrentFile.CommitTime;
- boolean lockRemoved = myCurrentFile.getChangedEntryProperties().containsKey(SVNProperty.LOCK_TOKEN);
Map command = new HashMap();
SVNStatusType textStatus = SVNStatusType.UNCHANGED;
SVNStatusType lockStatus = SVNStatusType.LOCK_UNCHANGED;
boolean magicPropsChanged = false;
SVNProperties props = dir.getProperties(name, false);
Map locallyModifiedProps = dir.getBaseProperties(name, false).compareTo(props);
if (modifiedProps != null && !modifiedProps.isEmpty()) {
magicPropsChanged = modifiedProps.containsKey(SVNProperty.EXECUTABLE) ||
modifiedProps.containsKey(SVNProperty.NEEDS_LOCK) ||
modifiedProps.containsKey(SVNProperty.KEYWORDS) ||
modifiedProps.containsKey(SVNProperty.EOL_STYLE) ||
modifiedProps.containsKey(SVNProperty.SPECIAL);
}
SVNStatusType propStatus = dir.mergeProperties(name, modifiedProps, locallyModifiedProps, true, log);
if (modifiedEntryProps != null) {
lockStatus = log.logChangedEntryProperties(name, modifiedEntryProps);
}
// merge contents.
File textTmpBase = dir.getBaseFile(name, true);
String tmpPath = ".svn/tmp/text-base/" + name + ".svn-base";
String basePath = ".svn/text-base/" + name + ".svn-base";
if (!textTmpBase.exists() && magicPropsChanged) {
// only props were changed, but we have to retranslate file.
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNLog.DEST_ATTR, tmpPath);
log.addCommand(SVNLog.COPY_AND_DETRANSLATE, command, false);
command.clear();
command.put(SVNLog.NAME_ATTR, tmpPath);
command.put(SVNLog.DEST_ATTR, name);
log.addCommand(SVNLog.COPY_AND_TRANSLATE, command, false);
command.clear();
}
// update entry.
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNProperty.shortPropertyName(SVNProperty.KIND), SVNProperty.KIND_FILE);
command.put(SVNProperty.shortPropertyName(SVNProperty.REVISION), Long.toString(myTargetRevision));
command.put(SVNProperty.shortPropertyName(SVNProperty.DELETED), Boolean.FALSE.toString());
command.put(SVNProperty.shortPropertyName(SVNProperty.ABSENT), Boolean.FALSE.toString());
command.put(SVNProperty.shortPropertyName(SVNProperty.URL), myCurrentFile.URL);
log.addCommand(SVNLog.MODIFY_ENTRY, command, false);
command.clear();
boolean isLocallyModified = !myCurrentFile.IsAdded && dir.hasTextModifications(name, false);
File workingFile = dir.getFile(name, false);
if (textTmpBase.exists()) {
textStatus = SVNStatusType.CHANGED;
// there is a text replace working copy with.
if (!isLocallyModified || !workingFile.exists()) {
command.put(SVNLog.NAME_ATTR, tmpPath);
command.put(SVNLog.DEST_ATTR, name);
log.addCommand(SVNLog.COPY_AND_TRANSLATE, command, false);
command.clear();
} else {
SVNEntries entries = dir.getEntries();
SVNEntry entry = entries.getEntry(name, true);
String oldRevisionStr = ".r" + entry.getRevision();
String newRevisionStr = ".r" + myTargetRevision;
entries.close();
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNLog.ATTR1, basePath);
command.put(SVNLog.ATTR2, tmpPath);
command.put(SVNLog.ATTR3, oldRevisionStr);
command.put(SVNLog.ATTR4, newRevisionStr);
command.put(SVNLog.ATTR5, ".mine");
log.addCommand(SVNLog.MERGE, command, false);
command.clear();
// do test merge.
textStatus = dir.mergeText(name, basePath, tmpPath, "", "", "", true);
if (textStatus == SVNStatusType.UNCHANGED) {
textStatus = SVNStatusType.MERGED;
}
}
} else if (lockStatus == SVNStatusType.LOCK_UNLOCKED) {
command.put(SVNLog.NAME_ATTR, name);
log.addCommand(SVNLog.MAYBE_READONLY, command, false);
command.clear();
}
if (locallyModifiedProps == null || locallyModifiedProps.isEmpty()) {
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNProperty.shortPropertyName(SVNProperty.PROP_TIME), SVNLog.WC_TIMESTAMP);
log.addCommand(SVNLog.MODIFY_ENTRY, command, false);
command.clear();
}
if (textTmpBase.exists()) {
command.put(SVNLog.NAME_ATTR, tmpPath);
command.put(SVNLog.DEST_ATTR, basePath);
log.addCommand(SVNLog.MOVE, command, false);
command.clear();
command.put(SVNLog.NAME_ATTR, basePath);
log.addCommand(SVNLog.READONLY, command, false);
command.clear();
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNProperty.shortPropertyName(SVNProperty.CHECKSUM), checksum);
log.addCommand(SVNLog.MODIFY_ENTRY, command, false);
command.clear();
}
if (modifiedWCProps != null) {
log.logChangedWCProperties(name, modifiedWCProps);
}
if (!isLocallyModified) {
if (commitTime != null) {
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNLog.TIMESTAMP_ATTR, commitTime);
log.addCommand(SVNLog.SET_TIMESTAMP, command, false);
command.clear();
}
if (textTmpBase.exists() || magicPropsChanged) {
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNProperty.shortPropertyName(SVNProperty.TEXT_TIME), SVNLog.WC_TIMESTAMP);
log.addCommand(SVNLog.MODIFY_ENTRY, command, false);
command.clear();
}
}
// bump.
log.save();
myCurrentFile.myDiffWindows = null;
completeDirectory(myCurrentDirectory);
// notify.
- if (!myCurrentFile.IsAdded && textStatus == SVNStatusType.UNCHANGED && propStatus == SVNStatusType.UNCHANGED && !lockRemoved) {
+ if (!myCurrentFile.IsAdded && textStatus == SVNStatusType.UNCHANGED && propStatus == SVNStatusType.UNCHANGED &&
+ lockStatus == SVNStatusType.LOCK_UNCHANGED) {
// no changes, probably just wcurl switch.
myCurrentFile = null;
return;
}
SVNEventAction action = myCurrentFile.IsAdded ? SVNEventAction.UPDATE_ADD : SVNEventAction.UPDATE_UPDATE;
myWCAccess.handleEvent(SVNEventFactory.createUpdateModifiedEvent(myWCAccess, dir, myCurrentFile.Name, SVNNodeKind.FILE, action, null,
textStatus, propStatus, lockStatus));
myCurrentFile = null;
}
public void abortEdit() throws SVNException {
}
private void bumpDirectories() throws SVNException {
SVNDirectory dir = myWCAccess.getAnchor();
if (myTarget != null){
if (dir.getChildDirectory(myTarget) == null) {
SVNEntry entry = dir.getEntries().getEntry(myTarget, true);
boolean save = bumpEntry(dir.getEntries(), entry, mySwitchURL, myTargetRevision, false);
if (save) {
dir.getEntries().save(true);
} else {
dir.getEntries().close();
}
return;
}
dir = dir.getChildDirectory(myTarget);
}
bumpDirectory(dir, mySwitchURL);
}
private void bumpDirectory(SVNDirectory dir, String url) throws SVNException {
SVNEntries entries = dir.getEntries();
boolean save = bumpEntry(entries, entries.getEntry("", true), url, myTargetRevision, false);
Map childDirectories = new HashMap();
for (Iterator ents = entries.entries(true); ents.hasNext();) {
SVNEntry entry = (SVNEntry) ents.next();
if ("".equals(entry.getName())) {
continue;
}
String childURL = url != null ? PathUtil.append(url, PathUtil.encode(entry.getName())) : null;
if (entry.getKind() == SVNNodeKind.FILE) {
save |= bumpEntry(entries, entry, childURL, myTargetRevision, true);
} else if (myIsRecursive && entry.getKind() == SVNNodeKind.DIR) {
SVNDirectory childDirectory = dir.getChildDirectory(entry.getName());
if (!entry.isScheduledForAddition() && (childDirectory == null || !childDirectory.isVersioned())) {
DebugLog.log("missing dir remains after update: entry deleted");
myWCAccess.handleEvent(SVNEventFactory.createUpdateDeleteEvent(myWCAccess, dir, entry));
entries.deleteEntry(entry.getName());
save = true;
} else {
// schedule for recursion, map of dir->url
childDirectories.put(childDirectory, childURL);
}
}
}
if (save) {
entries.save(true);
}
for (Iterator children = childDirectories.keySet().iterator(); children.hasNext();) {
SVNDirectory child = (SVNDirectory) children.next();
String childURL = (String) childDirectories.get(child);
bumpDirectory(child, childURL);
}
}
private static boolean bumpEntry(SVNEntries entries, SVNEntry entry, String url, long revision, boolean delete) {
if (entry == null) {
return false;
}
boolean save = false;
if (url != null) {
save |= entry.setURL(url);
}
if (revision >=0 && !entry.isScheduledForAddition() && !entry.isScheduledForReplacement()) {
save |= entry.setRevision(revision);
}
if (delete && (entry.isDeleted() || (entry.isAbsent() && entry.getRevision() != revision))) {
entries.deleteEntry(entry.getName());
save = true;
}
return save;
}
private void completeDirectory(SVNDirectoryInfo info) throws SVNException {
while(info != null) {
info.RefCount--;
if (info.RefCount > 0) {
return;
}
if (info.Parent == null && myTarget != null) {
return;
}
SVNEntries entries = info.getDirectory().getEntries();
if (entries.getEntry("", true) == null) {
SVNErrorManager.error(0, null);
}
for (Iterator ents = entries.entries(true); ents.hasNext();) {
SVNEntry entry = (SVNEntry) ents.next();
if ("".equals(entry.getName())) {
entry.setIncomplete(false);
continue;
}
if (entry.isDeleted()) {
if (!entry.isScheduledForAddition()) {
entries.deleteEntry(entry.getName());
} else {
entry.setDeleted(false);
}
} else if (entry.isAbsent() && entry.getRevision() != myTargetRevision) {
entries.deleteEntry(entry.getName());
} else if (entry.getKind() == SVNNodeKind.DIR) {
SVNDirectory childDirectory = info.getDirectory().getChildDirectory(entry.getName());
if (myIsRecursive && (childDirectory == null || !childDirectory.isVersioned())
&& !entry.isAbsent() && !entry.isScheduledForAddition()) {
DebugLog.log("missing dir remains after update (2): entry deleted");
myWCAccess.handleEvent(SVNEventFactory.createUpdateDeleteEvent(myWCAccess, info.getDirectory(), entry));
entries.deleteEntry(entry.getName());
}
}
}
entries.save(true);
info = info.Parent;
}
}
private SVNFileInfo createFileInfo(SVNDirectoryInfo parent, String path, boolean added) throws SVNException {
SVNFileInfo info = new SVNFileInfo(parent, path);
info.IsAdded = added;
info.Name = PathUtil.tail(path);
SVNDirectory dir = parent.getDirectory();
if (added && dir.getFile(info.Name, false).exists()) {
SVNErrorManager.error("svn: Failed to add file '" + path + "': object of the same name already exists");
}
SVNEntries entries = null;
try {
entries = dir.getEntries();
SVNEntry entry = entries.getEntry(info.Name, true);
if (added && entry != null && entry.isScheduledForAddition()) {
SVNErrorManager.error(0, null);
}
if (!added && entry == null) {
SVNErrorManager.error(0, null);
}
if (mySwitchURL != null || entry == null) {
info.URL = PathUtil.append(parent.URL, PathUtil.encode(info.Name));
} else if (entry != null) {
info.URL = entry.getURL();
}
} finally {
if (entries != null) {
entries.close();
}
}
parent.RefCount++;
return info;
}
private SVNDirectoryInfo createDirectoryInfo(SVNDirectoryInfo parent, String path, boolean added) throws SVNException {
SVNDirectoryInfo info = new SVNDirectoryInfo(path);
info.Parent = parent;
info.IsAdded = added;
String name = path != null ? PathUtil.tail(path) : "";
if (mySwitchURL == null) {
SVNDirectory dir = added ? null : info.getDirectory();
if (dir != null && dir.getEntries().getEntry("", true) != null) {
info.URL = dir.getEntries().getEntry("", true).getURL();
}
if (info.URL == null && parent != null) {
info.URL = PathUtil.append(parent.URL, PathUtil.encode(name));
} else if (info.URL == null && parent == null) {
info.URL = myTargetURL;
}
} else {
if (parent == null) {
info.URL = myTarget == null ? mySwitchURL : PathUtil.removeTail(mySwitchURL);
} else {
if (myTarget != null && parent.Parent == null) {
info.URL = mySwitchURL;
} else {
info.URL = PathUtil.append(parent.URL, PathUtil.encode(name));
}
}
}
info.RefCount = 1;
if (info.Parent != null) {
info.Parent.RefCount++;
}
return info;
}
private class SVNEntryInfo {
public String URL;
public boolean IsAdded;
public SVNDirectoryInfo Parent;
private String myPath;
private Map myChangedProperties;
private Map myChangedEntryProperties;
private Map myChangedWCProperties;
protected SVNEntryInfo(String path) {
myPath = path;
}
protected String getPath() {
return myPath;
}
public void propertyChanged(String name, String value) {
if (name.startsWith(SVNProperty.SVN_ENTRY_PREFIX)) {
myChangedEntryProperties = myChangedEntryProperties == null ? new HashMap() : myChangedEntryProperties;
myChangedEntryProperties.put(name.substring(SVNProperty.SVN_ENTRY_PREFIX.length()), value);
} else if (name.startsWith(SVNProperty.SVN_WC_PREFIX)) {
myChangedWCProperties = myChangedWCProperties == null ? new HashMap() : myChangedWCProperties;
myChangedWCProperties.put(name, value);
} else {
myChangedProperties = myChangedProperties == null ? new HashMap() : myChangedProperties;
myChangedProperties.put(name, value);
}
}
public Map getChangedWCProperties() {
return myChangedWCProperties;
}
public Map getChangedEntryProperties() {
return myChangedEntryProperties;
}
public Map getChangedProperties() {
return myChangedProperties;
}
}
private class SVNFileInfo extends SVNEntryInfo {
public String Name;
public String CommitTime;
public Collection myDiffWindows;
public SVNFileInfo(SVNDirectoryInfo parent, String path) {
super(path);
this.Parent = parent;
}
public SVNDirectory getDirectory() {
return Parent.getDirectory();
}
}
private class SVNDirectoryInfo extends SVNEntryInfo {
public int RefCount;
private int myLogCount;
public SVNDirectoryInfo(String path) {
super(path);
}
public SVNDirectory getDirectory() {
return myWCAccess.getDirectory(getPath());
}
public SVNLog getLog(boolean increment) {
SVNLog log = getDirectory().getLog(myLogCount);
if (increment) {
myLogCount++;
}
return log;
}
public void runLogs() throws SVNException {
getDirectory().runLogs();
myLogCount = 0;
}
}
}
| false | true | public void closeFile(String commitPath, String textChecksum) throws SVNException {
// check checksum.
String checksum = null;
if (myCurrentFile.myDiffWindows != null && textChecksum != null) {
File baseTmpFile = myCurrentFile.getDirectory().getBaseFile(myCurrentFile.Name, true);
checksum = SVNFileUtil.computeChecksum(baseTmpFile);
if (!textChecksum.equals(checksum)) {
SVNErrorManager.error(0, null);
}
}
SVNDirectory dir = myCurrentFile.getDirectory();
SVNLog log = myCurrentDirectory.getLog(true);
// merge props.
Map modifiedWCProps = myCurrentFile.getChangedWCProperties();
Map modifiedEntryProps = myCurrentFile.getChangedEntryProperties();
Map modifiedProps = myCurrentFile.getChangedProperties();
String name = myCurrentFile.Name;
String commitTime = myCurrentFile.CommitTime;
boolean lockRemoved = myCurrentFile.getChangedEntryProperties().containsKey(SVNProperty.LOCK_TOKEN);
Map command = new HashMap();
SVNStatusType textStatus = SVNStatusType.UNCHANGED;
SVNStatusType lockStatus = SVNStatusType.LOCK_UNCHANGED;
boolean magicPropsChanged = false;
SVNProperties props = dir.getProperties(name, false);
Map locallyModifiedProps = dir.getBaseProperties(name, false).compareTo(props);
if (modifiedProps != null && !modifiedProps.isEmpty()) {
magicPropsChanged = modifiedProps.containsKey(SVNProperty.EXECUTABLE) ||
modifiedProps.containsKey(SVNProperty.NEEDS_LOCK) ||
modifiedProps.containsKey(SVNProperty.KEYWORDS) ||
modifiedProps.containsKey(SVNProperty.EOL_STYLE) ||
modifiedProps.containsKey(SVNProperty.SPECIAL);
}
SVNStatusType propStatus = dir.mergeProperties(name, modifiedProps, locallyModifiedProps, true, log);
if (modifiedEntryProps != null) {
lockStatus = log.logChangedEntryProperties(name, modifiedEntryProps);
}
// merge contents.
File textTmpBase = dir.getBaseFile(name, true);
String tmpPath = ".svn/tmp/text-base/" + name + ".svn-base";
String basePath = ".svn/text-base/" + name + ".svn-base";
if (!textTmpBase.exists() && magicPropsChanged) {
// only props were changed, but we have to retranslate file.
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNLog.DEST_ATTR, tmpPath);
log.addCommand(SVNLog.COPY_AND_DETRANSLATE, command, false);
command.clear();
command.put(SVNLog.NAME_ATTR, tmpPath);
command.put(SVNLog.DEST_ATTR, name);
log.addCommand(SVNLog.COPY_AND_TRANSLATE, command, false);
command.clear();
}
// update entry.
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNProperty.shortPropertyName(SVNProperty.KIND), SVNProperty.KIND_FILE);
command.put(SVNProperty.shortPropertyName(SVNProperty.REVISION), Long.toString(myTargetRevision));
command.put(SVNProperty.shortPropertyName(SVNProperty.DELETED), Boolean.FALSE.toString());
command.put(SVNProperty.shortPropertyName(SVNProperty.ABSENT), Boolean.FALSE.toString());
command.put(SVNProperty.shortPropertyName(SVNProperty.URL), myCurrentFile.URL);
log.addCommand(SVNLog.MODIFY_ENTRY, command, false);
command.clear();
boolean isLocallyModified = !myCurrentFile.IsAdded && dir.hasTextModifications(name, false);
File workingFile = dir.getFile(name, false);
if (textTmpBase.exists()) {
textStatus = SVNStatusType.CHANGED;
// there is a text replace working copy with.
if (!isLocallyModified || !workingFile.exists()) {
command.put(SVNLog.NAME_ATTR, tmpPath);
command.put(SVNLog.DEST_ATTR, name);
log.addCommand(SVNLog.COPY_AND_TRANSLATE, command, false);
command.clear();
} else {
SVNEntries entries = dir.getEntries();
SVNEntry entry = entries.getEntry(name, true);
String oldRevisionStr = ".r" + entry.getRevision();
String newRevisionStr = ".r" + myTargetRevision;
entries.close();
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNLog.ATTR1, basePath);
command.put(SVNLog.ATTR2, tmpPath);
command.put(SVNLog.ATTR3, oldRevisionStr);
command.put(SVNLog.ATTR4, newRevisionStr);
command.put(SVNLog.ATTR5, ".mine");
log.addCommand(SVNLog.MERGE, command, false);
command.clear();
// do test merge.
textStatus = dir.mergeText(name, basePath, tmpPath, "", "", "", true);
if (textStatus == SVNStatusType.UNCHANGED) {
textStatus = SVNStatusType.MERGED;
}
}
} else if (lockStatus == SVNStatusType.LOCK_UNLOCKED) {
command.put(SVNLog.NAME_ATTR, name);
log.addCommand(SVNLog.MAYBE_READONLY, command, false);
command.clear();
}
if (locallyModifiedProps == null || locallyModifiedProps.isEmpty()) {
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNProperty.shortPropertyName(SVNProperty.PROP_TIME), SVNLog.WC_TIMESTAMP);
log.addCommand(SVNLog.MODIFY_ENTRY, command, false);
command.clear();
}
if (textTmpBase.exists()) {
command.put(SVNLog.NAME_ATTR, tmpPath);
command.put(SVNLog.DEST_ATTR, basePath);
log.addCommand(SVNLog.MOVE, command, false);
command.clear();
command.put(SVNLog.NAME_ATTR, basePath);
log.addCommand(SVNLog.READONLY, command, false);
command.clear();
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNProperty.shortPropertyName(SVNProperty.CHECKSUM), checksum);
log.addCommand(SVNLog.MODIFY_ENTRY, command, false);
command.clear();
}
if (modifiedWCProps != null) {
log.logChangedWCProperties(name, modifiedWCProps);
}
if (!isLocallyModified) {
if (commitTime != null) {
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNLog.TIMESTAMP_ATTR, commitTime);
log.addCommand(SVNLog.SET_TIMESTAMP, command, false);
command.clear();
}
if (textTmpBase.exists() || magicPropsChanged) {
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNProperty.shortPropertyName(SVNProperty.TEXT_TIME), SVNLog.WC_TIMESTAMP);
log.addCommand(SVNLog.MODIFY_ENTRY, command, false);
command.clear();
}
}
// bump.
log.save();
myCurrentFile.myDiffWindows = null;
completeDirectory(myCurrentDirectory);
// notify.
if (!myCurrentFile.IsAdded && textStatus == SVNStatusType.UNCHANGED && propStatus == SVNStatusType.UNCHANGED && !lockRemoved) {
// no changes, probably just wcurl switch.
myCurrentFile = null;
return;
}
SVNEventAction action = myCurrentFile.IsAdded ? SVNEventAction.UPDATE_ADD : SVNEventAction.UPDATE_UPDATE;
myWCAccess.handleEvent(SVNEventFactory.createUpdateModifiedEvent(myWCAccess, dir, myCurrentFile.Name, SVNNodeKind.FILE, action, null,
textStatus, propStatus, lockStatus));
myCurrentFile = null;
}
| public void closeFile(String commitPath, String textChecksum) throws SVNException {
// check checksum.
String checksum = null;
if (myCurrentFile.myDiffWindows != null && textChecksum != null) {
File baseTmpFile = myCurrentFile.getDirectory().getBaseFile(myCurrentFile.Name, true);
checksum = SVNFileUtil.computeChecksum(baseTmpFile);
if (!textChecksum.equals(checksum)) {
SVNErrorManager.error(0, null);
}
}
SVNDirectory dir = myCurrentFile.getDirectory();
SVNLog log = myCurrentDirectory.getLog(true);
// merge props.
Map modifiedWCProps = myCurrentFile.getChangedWCProperties();
Map modifiedEntryProps = myCurrentFile.getChangedEntryProperties();
Map modifiedProps = myCurrentFile.getChangedProperties();
String name = myCurrentFile.Name;
String commitTime = myCurrentFile.CommitTime;
Map command = new HashMap();
SVNStatusType textStatus = SVNStatusType.UNCHANGED;
SVNStatusType lockStatus = SVNStatusType.LOCK_UNCHANGED;
boolean magicPropsChanged = false;
SVNProperties props = dir.getProperties(name, false);
Map locallyModifiedProps = dir.getBaseProperties(name, false).compareTo(props);
if (modifiedProps != null && !modifiedProps.isEmpty()) {
magicPropsChanged = modifiedProps.containsKey(SVNProperty.EXECUTABLE) ||
modifiedProps.containsKey(SVNProperty.NEEDS_LOCK) ||
modifiedProps.containsKey(SVNProperty.KEYWORDS) ||
modifiedProps.containsKey(SVNProperty.EOL_STYLE) ||
modifiedProps.containsKey(SVNProperty.SPECIAL);
}
SVNStatusType propStatus = dir.mergeProperties(name, modifiedProps, locallyModifiedProps, true, log);
if (modifiedEntryProps != null) {
lockStatus = log.logChangedEntryProperties(name, modifiedEntryProps);
}
// merge contents.
File textTmpBase = dir.getBaseFile(name, true);
String tmpPath = ".svn/tmp/text-base/" + name + ".svn-base";
String basePath = ".svn/text-base/" + name + ".svn-base";
if (!textTmpBase.exists() && magicPropsChanged) {
// only props were changed, but we have to retranslate file.
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNLog.DEST_ATTR, tmpPath);
log.addCommand(SVNLog.COPY_AND_DETRANSLATE, command, false);
command.clear();
command.put(SVNLog.NAME_ATTR, tmpPath);
command.put(SVNLog.DEST_ATTR, name);
log.addCommand(SVNLog.COPY_AND_TRANSLATE, command, false);
command.clear();
}
// update entry.
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNProperty.shortPropertyName(SVNProperty.KIND), SVNProperty.KIND_FILE);
command.put(SVNProperty.shortPropertyName(SVNProperty.REVISION), Long.toString(myTargetRevision));
command.put(SVNProperty.shortPropertyName(SVNProperty.DELETED), Boolean.FALSE.toString());
command.put(SVNProperty.shortPropertyName(SVNProperty.ABSENT), Boolean.FALSE.toString());
command.put(SVNProperty.shortPropertyName(SVNProperty.URL), myCurrentFile.URL);
log.addCommand(SVNLog.MODIFY_ENTRY, command, false);
command.clear();
boolean isLocallyModified = !myCurrentFile.IsAdded && dir.hasTextModifications(name, false);
File workingFile = dir.getFile(name, false);
if (textTmpBase.exists()) {
textStatus = SVNStatusType.CHANGED;
// there is a text replace working copy with.
if (!isLocallyModified || !workingFile.exists()) {
command.put(SVNLog.NAME_ATTR, tmpPath);
command.put(SVNLog.DEST_ATTR, name);
log.addCommand(SVNLog.COPY_AND_TRANSLATE, command, false);
command.clear();
} else {
SVNEntries entries = dir.getEntries();
SVNEntry entry = entries.getEntry(name, true);
String oldRevisionStr = ".r" + entry.getRevision();
String newRevisionStr = ".r" + myTargetRevision;
entries.close();
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNLog.ATTR1, basePath);
command.put(SVNLog.ATTR2, tmpPath);
command.put(SVNLog.ATTR3, oldRevisionStr);
command.put(SVNLog.ATTR4, newRevisionStr);
command.put(SVNLog.ATTR5, ".mine");
log.addCommand(SVNLog.MERGE, command, false);
command.clear();
// do test merge.
textStatus = dir.mergeText(name, basePath, tmpPath, "", "", "", true);
if (textStatus == SVNStatusType.UNCHANGED) {
textStatus = SVNStatusType.MERGED;
}
}
} else if (lockStatus == SVNStatusType.LOCK_UNLOCKED) {
command.put(SVNLog.NAME_ATTR, name);
log.addCommand(SVNLog.MAYBE_READONLY, command, false);
command.clear();
}
if (locallyModifiedProps == null || locallyModifiedProps.isEmpty()) {
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNProperty.shortPropertyName(SVNProperty.PROP_TIME), SVNLog.WC_TIMESTAMP);
log.addCommand(SVNLog.MODIFY_ENTRY, command, false);
command.clear();
}
if (textTmpBase.exists()) {
command.put(SVNLog.NAME_ATTR, tmpPath);
command.put(SVNLog.DEST_ATTR, basePath);
log.addCommand(SVNLog.MOVE, command, false);
command.clear();
command.put(SVNLog.NAME_ATTR, basePath);
log.addCommand(SVNLog.READONLY, command, false);
command.clear();
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNProperty.shortPropertyName(SVNProperty.CHECKSUM), checksum);
log.addCommand(SVNLog.MODIFY_ENTRY, command, false);
command.clear();
}
if (modifiedWCProps != null) {
log.logChangedWCProperties(name, modifiedWCProps);
}
if (!isLocallyModified) {
if (commitTime != null) {
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNLog.TIMESTAMP_ATTR, commitTime);
log.addCommand(SVNLog.SET_TIMESTAMP, command, false);
command.clear();
}
if (textTmpBase.exists() || magicPropsChanged) {
command.put(SVNLog.NAME_ATTR, name);
command.put(SVNProperty.shortPropertyName(SVNProperty.TEXT_TIME), SVNLog.WC_TIMESTAMP);
log.addCommand(SVNLog.MODIFY_ENTRY, command, false);
command.clear();
}
}
// bump.
log.save();
myCurrentFile.myDiffWindows = null;
completeDirectory(myCurrentDirectory);
// notify.
if (!myCurrentFile.IsAdded && textStatus == SVNStatusType.UNCHANGED && propStatus == SVNStatusType.UNCHANGED &&
lockStatus == SVNStatusType.LOCK_UNCHANGED) {
// no changes, probably just wcurl switch.
myCurrentFile = null;
return;
}
SVNEventAction action = myCurrentFile.IsAdded ? SVNEventAction.UPDATE_ADD : SVNEventAction.UPDATE_UPDATE;
myWCAccess.handleEvent(SVNEventFactory.createUpdateModifiedEvent(myWCAccess, dir, myCurrentFile.Name, SVNNodeKind.FILE, action, null,
textStatus, propStatus, lockStatus));
myCurrentFile = null;
}
|
diff --git a/src/framework/java/com/flexive/shared/structure/FxPropertyAssignment.java b/src/framework/java/com/flexive/shared/structure/FxPropertyAssignment.java
index c79df4ff..2d65400b 100644
--- a/src/framework/java/com/flexive/shared/structure/FxPropertyAssignment.java
+++ b/src/framework/java/com/flexive/shared/structure/FxPropertyAssignment.java
@@ -1,431 +1,431 @@
/***************************************************************
* This file is part of the [fleXive](R) framework.
*
* Copyright (c) 1999-2008
* UCS - unique computing solutions gmbh (http://www.ucs.at)
* All rights reserved
*
* The [fleXive](R) project is free software; you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public
* License version 2.1 or higher as published by the Free Software Foundation.
*
* The GNU Lesser General Public License can be found at
* http://www.gnu.org/licenses/lgpl.html.
* A copy is found in the textfile LGPL.txt and important notices to the
* license from the author are found in LICENSE.txt distributed with
* these libraries.
*
* 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 General Public License for more details.
*
* For further information about UCS - unique computing solutions gmbh,
* please see the company website: http://www.ucs.at
*
* For further information about [fleXive](R), please see the
* project website: http://www.flexive.org
*
*
* This copyright notice MUST APPEAR in all copies of the file!
***************************************************************/
package com.flexive.shared.structure;
import com.flexive.shared.FxLanguage;
import com.flexive.shared.XPathElement;
import com.flexive.shared.content.FxData;
import com.flexive.shared.content.FxGroupData;
import com.flexive.shared.content.FxPropertyData;
import com.flexive.shared.exceptions.FxCreateException;
import com.flexive.shared.exceptions.FxRuntimeException;
import com.flexive.shared.exceptions.FxContentExceptionCause;
import com.flexive.shared.security.ACL;
import com.flexive.shared.value.FxString;
import com.flexive.shared.value.FxValue;
import java.io.Serializable;
import java.util.List;
import java.util.Random;
import java.util.ArrayList;
/**
* Assignment of a property to a type or group
*
* @author Markus Plesser ([email protected]), UCS - unique computing solutions gmbh (http://www.ucs.at)
*/
public class FxPropertyAssignment extends FxAssignment implements Serializable {
private static final long serialVersionUID = -4825188658392104371L;
/**
* The property assigned
*/
protected FxProperty property;
/**
* Overridden ACL (if the embedded property permits)
*/
protected ACL ACL;
protected FxValue defaultValue;
protected long defaultLang;
protected FxFlatStorageMapping flatStorageMapping;
/**
* Constructor
*
* @param assignmentId internal id of this assignment
* @param enabled is this assignment enabled?
* @param assignedType the FxType this assignment belongs to
* @param alias an optional alias, if <code>null</code> the original name will be used
* @param xpath XPath relative to the assigned FxType
* @param position position within the same XPath hierarchy
* @param multiplicity multiplicity (will only be used if the embedded property allows overriding)
* @param defaultMultiplicity default multiplicity
* @param parentGroupAssignment (optional) parent FxGroupAssignment this property assignment belongs to
* @param baseAssignment base assignment (if derived the parent, if not the root assignment, if its a root assignment FxAssignment.ROOT_BASE)
* @param label (optional) label
* @param hint (optional) hint
* @param defaultValue (optional) default value
* @param property the assigned property
* @param ACL the embedded property's ACL (will only be used if the embedded property allows overriding)
* @param defaultLang default language if multilingual (if 0==SYSTEM then not set)
* @param options options
* @param flatStorageMapping flat storage mapping for this property assignment or <code>null</code>
*/
public FxPropertyAssignment(long assignmentId, boolean enabled, FxType assignedType, String alias, String xpath, int position,
FxMultiplicity multiplicity, int defaultMultiplicity, FxGroupAssignment parentGroupAssignment,
long baseAssignment, FxString label, FxString hint, FxValue defaultValue,
FxProperty property, ACL ACL, long defaultLang, List<FxStructureOption> options, FxFlatStorageMapping flatStorageMapping) {
super(assignmentId, enabled, assignedType, alias, xpath, position, multiplicity, defaultMultiplicity, parentGroupAssignment,
baseAssignment, label, hint, options);
this.defaultValue = defaultValue;
this.property = property;
if (alias == null || alias.trim().length() == 0)
this.alias = property.getName();
this.defaultLang = defaultLang;
this.ACL = ACL;
this.flatStorageMapping = flatStorageMapping;
}
/**
* Get the property this assignment relates to
*
* @return property this assignment relates to
*/
public FxProperty getProperty() {
return property;
}
/**
* Is this property assignment stored in a flat storage?
*
* @return property assignment stored in a flat storage?
*/
public boolean isFlatStorageEntry() {
return this.flatStorageMapping != null;
}
/**
* Get the flat storage mapping for this property assignment
*
* @return flat storage mapping or <code>null</code> if not located in the flat storage
*/
public FxFlatStorageMapping getFlatStorageMapping() {
return flatStorageMapping;
}
/**
* Is an explicit default value set for this assignment or is it taken from the property?
*
* @return if an explicit default value set for this assignment or is it taken from the property
*/
public boolean hasAssignmentDefaultValue() {
return this.defaultValue != null;
}
/**
* Get the ACL of the embedded property. If the property does not allow overriding
* ACL the original property ACL will be returned
*
* @return the ACL
*/
public ACL getACL() {
return (getProperty().mayOverrideACL() && this.ACL != null ? this.ACL : getProperty().getACL());
}
/**
* Check if an ACL is defined for this assignment which overrides the properties ACL
*
* @return <code>true</code> if an ACL is defined for this assignment which overrides the properties ACL
*/
public boolean isOverridingPropertyACL() {
return this.ACL != null && getProperty().mayOverrideACL();
}
/**
* Get the multiplicity of this assignment.
* Depending on if the assigned element allows overriding of its base multiplicity the base
* elements multiplicity is returned or the multiplicity of the assignment
*
* @return multiplicity of this assignment
*/
@Override
public FxMultiplicity getMultiplicity() {
return (getProperty().mayOverrideBaseMultiplicity() && this.multiplicity != null ? this.multiplicity : getProperty().getMultiplicity());
}
/**
* Check if a multiplicity is defined for this assignment which overrides the properties multiplicity
*
* @return <code>true</code> if a multiplicity is defined for this assignment which overrides the properties multiplicity
*/
public boolean isOverridingPropertyMultiplicity() {
return this.multiplicity != null && getProperty().mayOverrideBaseMultiplicity();
}
/**
* {@inheritDoc}
*/
@Override
public FxStructureOption getOption(String key) {
FxStructureOption pOpt = property.getOption(key);
if (!pOpt.isSet())
return super.getOption(key);
if (!pOpt.isOverrideable())
return pOpt;
if (super.hasOption(key))
return super.getOption(key);
return pOpt;
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasOption(String key) {
return super.hasOption(key) || property.hasOption(key);
}
public boolean isMultiLang() {
return getOption(FxStructureOption.OPTION_MULTILANG).isValueTrue();
}
public boolean isSearchable() {
return getOption(FxStructureOption.OPTION_SEARCHABLE).isValueTrue();
}
public boolean isInOverview() {
return getOption(FxStructureOption.OPTION_SHOW_OVERVIEW).isValueTrue();
}
public boolean isUseHTMLEditor() {
return getOption(FxStructureOption.OPTION_HTML_EDITOR).isValueTrue();
}
/**
* Shortcut to determine if a max. input length has been set
*
* @return has a max. input length been set?
*/
public boolean hasMaxLength() {
return hasOption(FxStructureOption.OPTION_MAXLENGTH);
}
/**
* Shortcut to get the maximum input length
*
* @return maximum input length. If not set, 0 is returned.
*/
public int getMaxLength() {
return getOption(FxStructureOption.OPTION_MAXLENGTH).getIntValue();
}
/**
* Show as multiple lines in editors?
*
* @return if this property appears in multiple lines
*/
public boolean isMultiLine() {
FxStructureOption opt = getOption(FxStructureOption.OPTION_MULTILINE);
if (opt.isSet()) {
try {
return opt.getIntValue() > 0;
} catch (Exception e) {
return false;
}
}
return false;
}
/**
* Get the number of multilines to display or 0 if multiline is not set
*
* @return number of multilines to display or 0 if multiline is not set
*/
public int getMultiLines() {
FxStructureOption opt = getOption(FxStructureOption.OPTION_MULTILINE);
if (opt.isSet()) {
try {
return opt.getIntValue();
} catch (Exception e) {
return 0;
}
}
return 0;
}
/**
* Get the default value for this assignment. If not set
* a copy of the property default value is returned.
*
* @return FxValue
*/
public FxValue getDefaultValue() {
if (defaultValue == null) {
//if default value is not set, return
//a synchronized copy of the property default value
if (property.isDefaultValueSet()) {
final FxValue copy = property.getDefaultValue();
copy.setXPath(this.getXPath());
property.updateEnvironmentData(copy);
return copy;
} else
return null;
}
final FxValue copy = defaultValue.copy();
copy.setXPath(this.getXPath());
property.updateEnvironmentData(copy);
return copy;
}
/**
* Get an empty FxValue object for this assignment
*
* @return empty FxValue object
*/
public FxValue getEmptyValue() {
FxValue value;
if (hasDefaultLanguage())
value = this.getProperty().getEmptyValue(this.isMultiLang(), this.getDefaultLanguage()).setXPath(getXPath());
else
value = this.getProperty().getEmptyValue(this.isMultiLang()).setXPath(getXPath());
if (this.getDefaultValue() != null && value.isMultiLanguage() == this.getDefaultValue().isMultiLanguage() && !this.getDefaultValue().isEmpty())
value = this.getDefaultValue().copy();
if (this.hasMaxLength()) {
value.setMaxInputLength(this.getMaxLength());
if (this.getProperty().getDataType() == FxDataType.String1024 && value.getMaxInputLength() > 1024)
value.setMaxInputLength(1024);
} else if (this.getProperty().getDataType() == FxDataType.String1024)
value.setMaxInputLength(1024);
property.updateEnvironmentData(value);
return value;
}
/**
* {@inheritDoc}
*/
@Override
public FxData createEmptyData(FxGroupData parent, int index) {
String XPathFull = (this.hasParentGroupAssignment() && parent != null ? parent.getXPathFull() : "") + "/" + this.getAlias();
String XPath = (this.hasParentGroupAssignment() && parent != null ? parent.getXPath() : "") + "/" + this.getAlias();
if (!this.getMultiplicity().isValid(index))
//noinspection ThrowableInstanceNeverThrown
throw new FxCreateException("ex.content.xpath.index.invalid", index, this.getMultiplicity(), this.getXPath()).
setAffectedXPath(parent != null ? parent.getXPathFull() : this.getXPath(), FxContentExceptionCause.InvalidIndex).asRuntimeException();
final FxPropertyData data = new FxPropertyData(parent == null ? "" : parent.getXPathPrefix(), this.getAlias(), index, XPath, XPathElement.toXPathMult(XPathFull),
XPathElement.getIndices(XPathFull), this.getId(), this.getProperty().getId(), this.getMultiplicity(),
this.getPosition(), parent, this.getEmptyValue(), this.isSystemInternal(), this.getOption(FxStructureOption.OPTION_MAXLENGTH));
//Flag if the value is set from the assignments default value
data.setContainsDefaultValue(!data.getValue().isEmpty());
return data;
}
/**
* {@inheritDoc}
*/
@Override
public FxData createRandomData(Random rnd, FxEnvironment env, FxGroupData parent, int index, int maxMultiplicity) {
String XPathFull = (this.hasParentGroupAssignment() && parent != null ? parent.getXPathFull() : "") + "/" + this.getAlias();
String XPath = (this.hasParentGroupAssignment() && parent != null ? parent.getXPath() : "") + "/" + this.getAlias();
if (!this.getMultiplicity().isValid(index))
//noinspection ThrowableInstanceNeverThrown
throw new FxCreateException("ex.content.xpath.index.invalid", index, this.getMultiplicity(), this.getXPath()).
setAffectedXPath(parent != null ? parent.getXPathFull() : this.getXPath(), FxContentExceptionCause.InvalidIndex).asRuntimeException();
return new FxPropertyData(parent == null ? "" : parent.getXPathPrefix(), this.getAlias(), index, XPath, XPathElement.toXPathMult(XPathFull),
XPathElement.getIndices(XPathFull), this.getId(), this.getProperty().getId(), this.getMultiplicity(),
this.getPosition(), parent, this.getProperty().getDataType().getRandomValue(rnd, this), this.isSystemInternal(), this.getOption(FxStructureOption.OPTION_MAXLENGTH));
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValid(Object value) {
// TODO: add assignment-based validation here
return property.getDataType().isValid(value);
}
/**
* Is a default language defined for this property assignment?
*
* @return if a default language is defined for this property assignment
*/
public boolean hasDefaultLanguage() {
return defaultLang != FxLanguage.SYSTEM_ID && isMultiLang();
}
/**
* Get the default language for this property assignment (if set)
*
* @return default language for this property assignment (if set)
*/
public long getDefaultLanguage() {
return defaultLang;
}
/**
* Get this FxPropertyAssignment as editable
*
* @return FxPropertyAssignmentEdit
*/
public FxPropertyAssignmentEdit asEditable() {
return new FxPropertyAssignmentEdit(this);
}
/**
* Return a list of all assignments that were derived from this one (i.e. all assignments of
* subtypes with the same base assignment ID). An assignment can be inherited at most once in a
* type, since changing the (unique) alias breaks the inheritance chain.
*
* @param environment the environment
* @return a list of all derived assignments
* @since 3.1
*/
public List<FxPropertyAssignment> getDerivedAssignments(FxEnvironment environment) {
final List<FxPropertyAssignment> result = new ArrayList<FxPropertyAssignment>();
// get the base assignment ID, i.e. the assignment ID that will be used for derived types
final long baseAssignmentId =
baseAssignment != ROOT_BASE
? baseAssignment
: getId();
// check for reusage of our assignment
for (FxType derivedType : getAssignedType().getDerivedTypes(true)) {
try {
- final FxAssignment derivedAssignment = derivedType.getAssignment("/" + alias);
+ final FxAssignment derivedAssignment = derivedType.getAssignment(getXPath());
if (derivedAssignment.isDerivedFrom(environment, baseAssignmentId)) {
result.add((FxPropertyAssignment) derivedAssignment);
}
} catch (FxRuntimeException e) {
// assignment not derived
}
}
return result;
}
}
| true | true | public List<FxPropertyAssignment> getDerivedAssignments(FxEnvironment environment) {
final List<FxPropertyAssignment> result = new ArrayList<FxPropertyAssignment>();
// get the base assignment ID, i.e. the assignment ID that will be used for derived types
final long baseAssignmentId =
baseAssignment != ROOT_BASE
? baseAssignment
: getId();
// check for reusage of our assignment
for (FxType derivedType : getAssignedType().getDerivedTypes(true)) {
try {
final FxAssignment derivedAssignment = derivedType.getAssignment("/" + alias);
if (derivedAssignment.isDerivedFrom(environment, baseAssignmentId)) {
result.add((FxPropertyAssignment) derivedAssignment);
}
} catch (FxRuntimeException e) {
// assignment not derived
}
}
return result;
}
| public List<FxPropertyAssignment> getDerivedAssignments(FxEnvironment environment) {
final List<FxPropertyAssignment> result = new ArrayList<FxPropertyAssignment>();
// get the base assignment ID, i.e. the assignment ID that will be used for derived types
final long baseAssignmentId =
baseAssignment != ROOT_BASE
? baseAssignment
: getId();
// check for reusage of our assignment
for (FxType derivedType : getAssignedType().getDerivedTypes(true)) {
try {
final FxAssignment derivedAssignment = derivedType.getAssignment(getXPath());
if (derivedAssignment.isDerivedFrom(environment, baseAssignmentId)) {
result.add((FxPropertyAssignment) derivedAssignment);
}
} catch (FxRuntimeException e) {
// assignment not derived
}
}
return result;
}
|
diff --git a/activemq-core/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTest.java b/activemq-core/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTest.java
index 6507dd0f3..1ca616c6e 100644
--- a/activemq-core/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTest.java
+++ b/activemq-core/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTest.java
@@ -1,132 +1,132 @@
/**
* 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.activemq.broker.ft;
import java.io.File;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import javax.jms.MessageConsumer;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.JmsTopicSendReceiveWithTwoConnectionsTest;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.xbean.BrokerFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
/**
* Test failover for Queues
*/
public class QueueMasterSlaveTest extends JmsTopicSendReceiveWithTwoConnectionsTest {
private static final transient Logger LOG = LoggerFactory.getLogger(QueueMasterSlaveTest.class);
protected BrokerService master;
protected AtomicReference<BrokerService> slave = new AtomicReference<BrokerService>();
protected CountDownLatch slaveStarted = new CountDownLatch(1);
protected int inflightMessageCount;
protected int failureCount = 50;
protected String uriString = "failover://(tcp://localhost:62001,tcp://localhost:62002)?randomize=false";
protected void setUp() throws Exception {
if (System.getProperty("basedir") == null) {
File file = new File(".");
System.setProperty("basedir", file.getAbsolutePath());
}
super.messageCount = 500;
failureCount = super.messageCount / 2;
super.topic = isTopic();
createMaster();
createSlave();
// wait for thing to connect
Thread.sleep(1000);
super.setUp();
}
protected String getSlaveXml() {
return "org/apache/activemq/broker/ft/slave.xml";
}
protected String getMasterXml() {
return "org/apache/activemq/broker/ft/master.xml";
}
protected void tearDown() throws Exception {
super.tearDown();
slaveStarted.await(5, TimeUnit.SECONDS);
BrokerService brokerService = slave.get();
if( brokerService!=null ) {
brokerService.stop();
}
master.stop();
}
protected ActiveMQConnectionFactory createConnectionFactory() throws Exception {
return new ActiveMQConnectionFactory(uriString);
}
protected void messageSent() throws Exception {
if (++inflightMessageCount == failureCount) {
Thread.sleep(1000);
LOG.error("MASTER STOPPED!@!!!!");
master.stop();
}
}
protected boolean isTopic() {
return false;
}
protected void createMaster() throws Exception {
BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(getMasterXml()));
brokerFactory.afterPropertiesSet();
master = brokerFactory.getBroker();
master.start();
}
protected void createSlave() throws Exception {
BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(getSlaveXml()));
brokerFactory.afterPropertiesSet();
BrokerService broker = brokerFactory.getBroker();
broker.start();
slave.set(broker);
slaveStarted.countDown();
}
public void testVirtualTopicFailover() throws Exception {
- MessageConsumer qConsumer = createConsumer(session, new ActiveMQQueue("Consumer.A.VirtualTopic.TA1"));
+ MessageConsumer qConsumer = session.createConsumer(new ActiveMQQueue("Consumer.A.VirtualTopic.TA1"));
assertNull("No message there yet", qConsumer.receive(1000));
qConsumer.close();
master.stop();
assertTrue("slave started", slaveStarted.await(10, TimeUnit.SECONDS));
final String text = "ForUWhenSlaveKicksIn";
producer.send(new ActiveMQTopic("VirtualTopic.TA1"), session.createTextMessage(text));
- qConsumer = createConsumer(session, new ActiveMQQueue("Consumer.A.VirtualTopic.TA1"));
+ qConsumer = session.createConsumer(new ActiveMQQueue("Consumer.A.VirtualTopic.TA1"));
javax.jms.Message message = qConsumer.receive(4000);
assertNotNull("Get message after failover", message);
assertEquals("correct message", text, ((TextMessage)message).getText());
}
}
| false | true | public void testVirtualTopicFailover() throws Exception {
MessageConsumer qConsumer = createConsumer(session, new ActiveMQQueue("Consumer.A.VirtualTopic.TA1"));
assertNull("No message there yet", qConsumer.receive(1000));
qConsumer.close();
master.stop();
assertTrue("slave started", slaveStarted.await(10, TimeUnit.SECONDS));
final String text = "ForUWhenSlaveKicksIn";
producer.send(new ActiveMQTopic("VirtualTopic.TA1"), session.createTextMessage(text));
qConsumer = createConsumer(session, new ActiveMQQueue("Consumer.A.VirtualTopic.TA1"));
javax.jms.Message message = qConsumer.receive(4000);
assertNotNull("Get message after failover", message);
assertEquals("correct message", text, ((TextMessage)message).getText());
}
| public void testVirtualTopicFailover() throws Exception {
MessageConsumer qConsumer = session.createConsumer(new ActiveMQQueue("Consumer.A.VirtualTopic.TA1"));
assertNull("No message there yet", qConsumer.receive(1000));
qConsumer.close();
master.stop();
assertTrue("slave started", slaveStarted.await(10, TimeUnit.SECONDS));
final String text = "ForUWhenSlaveKicksIn";
producer.send(new ActiveMQTopic("VirtualTopic.TA1"), session.createTextMessage(text));
qConsumer = session.createConsumer(new ActiveMQQueue("Consumer.A.VirtualTopic.TA1"));
javax.jms.Message message = qConsumer.receive(4000);
assertNotNull("Get message after failover", message);
assertEquals("correct message", text, ((TextMessage)message).getText());
}
|
diff --git a/src/xmpp/extensions/IqPing.java b/src/xmpp/extensions/IqPing.java
index a653900a..c12043f9 100644
--- a/src/xmpp/extensions/IqPing.java
+++ b/src/xmpp/extensions/IqPing.java
@@ -1,110 +1,110 @@
/*
* IqPing.java
* Copyright (c) 2006-2008, Daniel Apatin (ad), http://apatin.net.ru
*
* 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.
*
* You can also redistribute and/or modify this program under the
* terms of the Psi License, specified in the accompanied COPYING
* file, as published by the Psi Project; either dated January 1st,
* 2005, 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package xmpp.extensions;
import Client.Contact;
import Client.Msg;
import Client.Roster;
import Client.StaticData;
import com.alsutton.jabber.JabberBlockListener;
import com.alsutton.jabber.JabberDataBlock;
import com.alsutton.jabber.datablocks.*;
import locale.SR;
import ui.Time;
public class IqPing implements JabberBlockListener {
public IqPing(){};
private final static String PING="ping";
private final static String _PING_="_ping_";
public static JabberDataBlock query(String to, String id) {
String newId=(id==null)?_PING_+Time.utcTimeMillis():id;
JabberDataBlock result=new Iq(to, Iq.TYPE_GET, newId);
result.addChildNs(PING, "urn:xmpp:ping");
return result;
}
public int blockArrived(JabberDataBlock data) {
if (!(data instanceof Iq))
return BLOCK_REJECTED;
String type=data.getTypeAttribute();
String from=data.getAttribute("from");
String id=data.getAttribute("id");
- if (type.equals("get") || type.equals("error")) {
+ if (type.equals("result") || type.equals("error")) {
if (id.equals(PING)) {
StaticData.getInstance().roster.theStream.pingSent=false;
return BLOCK_PROCESSED;
}
}
if (type.equals("get")) {
JabberDataBlock ping=data.getChildBlock(PING);
if (ping!=null) {
if (ping.getAttribute("xmlns").equals("urn:xmpp:ping")) {
Iq reply=new Iq(from, Iq.TYPE_RESULT, id);
StaticData.getInstance().roster.theStream.send(reply);
return BLOCK_PROCESSED;
}
}
}
if (type.equals("result")) {
if (id.startsWith(_PING_)) {
Roster roster=StaticData.getInstance().roster;
Contact c=roster.getContact(from, false);
String pong = pingToString(id.substring(6));
roster.querysign=false;
if (pong!=null) {
Msg m=new Msg(Msg.MESSAGE_TYPE_SYSTEM, "pong", SR.MS_PING, pong);
roster.messageStore(c, m);
roster.redraw();
}
return BLOCK_PROCESSED;
}
}
return BLOCK_REJECTED;
}
private String pingToString(String time) {
String timePing=Long.toString((Time.utcTimeMillis()-Long.parseLong(time))/10);
int dotpos=timePing.length()-2;
String first = (dotpos==0)? "0":timePing.substring(0, dotpos);
String second = timePing.substring(dotpos);
StringBuffer s=new StringBuffer(first)
.append('.')
.append(second)
.append(' ')
.append(Time.goodWordForm (Integer.parseInt(second), 0));
return s.toString();
}
}
| true | true | public int blockArrived(JabberDataBlock data) {
if (!(data instanceof Iq))
return BLOCK_REJECTED;
String type=data.getTypeAttribute();
String from=data.getAttribute("from");
String id=data.getAttribute("id");
if (type.equals("get") || type.equals("error")) {
if (id.equals(PING)) {
StaticData.getInstance().roster.theStream.pingSent=false;
return BLOCK_PROCESSED;
}
}
if (type.equals("get")) {
JabberDataBlock ping=data.getChildBlock(PING);
if (ping!=null) {
if (ping.getAttribute("xmlns").equals("urn:xmpp:ping")) {
Iq reply=new Iq(from, Iq.TYPE_RESULT, id);
StaticData.getInstance().roster.theStream.send(reply);
return BLOCK_PROCESSED;
}
}
}
if (type.equals("result")) {
if (id.startsWith(_PING_)) {
Roster roster=StaticData.getInstance().roster;
Contact c=roster.getContact(from, false);
String pong = pingToString(id.substring(6));
roster.querysign=false;
if (pong!=null) {
Msg m=new Msg(Msg.MESSAGE_TYPE_SYSTEM, "pong", SR.MS_PING, pong);
roster.messageStore(c, m);
roster.redraw();
}
return BLOCK_PROCESSED;
}
}
return BLOCK_REJECTED;
}
| public int blockArrived(JabberDataBlock data) {
if (!(data instanceof Iq))
return BLOCK_REJECTED;
String type=data.getTypeAttribute();
String from=data.getAttribute("from");
String id=data.getAttribute("id");
if (type.equals("result") || type.equals("error")) {
if (id.equals(PING)) {
StaticData.getInstance().roster.theStream.pingSent=false;
return BLOCK_PROCESSED;
}
}
if (type.equals("get")) {
JabberDataBlock ping=data.getChildBlock(PING);
if (ping!=null) {
if (ping.getAttribute("xmlns").equals("urn:xmpp:ping")) {
Iq reply=new Iq(from, Iq.TYPE_RESULT, id);
StaticData.getInstance().roster.theStream.send(reply);
return BLOCK_PROCESSED;
}
}
}
if (type.equals("result")) {
if (id.startsWith(_PING_)) {
Roster roster=StaticData.getInstance().roster;
Contact c=roster.getContact(from, false);
String pong = pingToString(id.substring(6));
roster.querysign=false;
if (pong!=null) {
Msg m=new Msg(Msg.MESSAGE_TYPE_SYSTEM, "pong", SR.MS_PING, pong);
roster.messageStore(c, m);
roster.redraw();
}
return BLOCK_PROCESSED;
}
}
return BLOCK_REJECTED;
}
|
diff --git a/src/main/java/org/mybatis/spring/mapper/MapperScannerConfigurer.java b/src/main/java/org/mybatis/spring/mapper/MapperScannerConfigurer.java
index eb2f0846..57187500 100644
--- a/src/main/java/org/mybatis/spring/mapper/MapperScannerConfigurer.java
+++ b/src/main/java/org/mybatis/spring/mapper/MapperScannerConfigurer.java
@@ -1,449 +1,447 @@
/*
* Copyright 2010-2012 The MyBatis Team
*
* 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.mybatis.spring.mapper;
import static org.springframework.util.Assert.notNull;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.Set;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyResourceConfigurer;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.StringUtils;
/**
* BeanDefinitionRegistryPostProcessor that searches recursively starting from a base package for
* interfaces and registers them as {@code MapperFactoryBean}. Note that only interfaces with at
* least one method will be registered; concrete classes will be ignored.
* <p>
* The {@code basePackage} property can contain more than one package name, separated by either
* commas or semicolons.
* <p>
* This class supports filtering the mappers created by either specifying a marker interface or an
* annotation. The {@code annotationClass} property specifies an annotation to search for. The
* {@code markerInterface} property specifies a parent interface to search for. If both properties
* are specified, mappers are added for interfaces that match <em>either</em> criteria. By default,
* these two properties are null, so all interfaces in the given {@code basePackage} are added as
* mappers.
* <p>
* This configurer is usually used with autowire enabled so all the beans it creates are
* automatically autowired with the proper {@code SqlSessionFactory} or {@code SqlSessionTemplate}.
* If there is more than one {@code SqlSessionFactory} in the application, however, autowiring
* cannot be used. In this case you must explicitly specify either an {@code SqlSessionFactory} or
* an {@code SqlSessionTemplate} to use via the <em>bean name</em> properties. Bean names are used
* rather than actual objects because Spring does not initialize property placeholders until after
* this class is processed. Passing in an actual object which may require placeholders (i.e. DB user
* / password) will fail. Using bean names defers actual object creation until later in the startup
* process, after all placeholder substituation is completed. However, note that this configurer
* does support property placeholders of its <em>own</em> properties. The <code>basePackage</code>
* and bean name properties all support <code>${property}</code> style substitution.
* <p>
* Configuration sample:
* <p>
*
* <pre class="code">
* {@code
* <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
* <property name="basePackage" value="org.mybatis.spring.sample.mapper" />
* <!-- optional unless there are multiple session factories defined -->
* <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
* </bean>
* }
* </pre>
*
* @see MapperFactoryBean
* @version $Id$
*/
public class MapperScannerConfigurer implements BeanDefinitionRegistryPostProcessor, InitializingBean, ApplicationContextAware, BeanNameAware {
private String basePackage;
private boolean addToConfig = true;
private SqlSessionFactory sqlSessionFactory;
private SqlSessionTemplate sqlSessionTemplate;
private String sqlSessionTemplateBeanName;
private String sqlSessionFactoryBeanName;
private Class<? extends Annotation> annotationClass;
private Class<?> markerInterface;
private ApplicationContext applicationContext;
private String beanName;
/**
* This property lets you set the base package for your mapper interface files.
* <p>
* You can set more than one package by using a semicolon or comma as a separator.
* <p>
* Mappers will be searched for recursively starting in the specified package(s).
*
* @param basePackage base package name
*/
public void setBasePackage(String basePackage) {
this.basePackage = basePackage;
}
/**
* Same as {@code MapperFactoryBean#setAddToConfig(boolean)}
*
* @param addToConfig
* @see MapperFactoryBean#setAddToConfig(boolean)
*/
public void setAddToConfig(boolean addToConfig) {
this.addToConfig = addToConfig;
}
/**
* This property specifies the annotation that the scanner will search for.
* <p>
* The scanner will register all interfaces in the base package that also have the
* specified annotation.
* <p>
* Note this can be combined with markerInterface.
*
* @param annotationClass annotation class
*/
public void setAnnotationClass(Class<? extends Annotation> annotationClass) {
this.annotationClass = annotationClass;
}
/**
* This property specifies the parent that the scanner will search for.
* <p>
* The scanner will register all interfaces in the base package that also have the
* specified interface class as a parent.
* <p>
* Note this can be combined with annotationClass.
*
* @param superClass parent class
*/
public void setMarkerInterface(Class<?> superClass) {
this.markerInterface = superClass;
}
/**
* Specifies which {@code SqlSessionTemplate} to use in the case that there is
* more than one in the spring context. Usually this is only needed when you
* have more than one datasource.
* <p>
* Use {@link #setSqlSessionTemplateBeanName(String)} instead
*
* @param sqlSessionTemplate
*/
@Deprecated
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
/**
* Specifies which {@code SqlSessionTemplate} to use in the case that there is
* more than one in the spring context. Usually this is only needed when you
* have more than one datasource.
* <p>
* Note bean names are used, not bean references. This is because the scanner
* loads early during the start process and it is too early to build mybatis
* object instances.
*
* @since 1.1.0
*
* @param sqlSessionTemplateName Bean name of the {@code SqlSessionTemplate}
*/
public void setSqlSessionTemplateBeanName(String sqlSessionTemplateName) {
this.sqlSessionTemplateBeanName = sqlSessionTemplateName;
}
/**
* Specifies which {@code SqlSessionFactory} to use in the case that there is
* more than one in the spring context. Usually this is only needed when you
* have more than one datasource.
* <p>
* Use {@link #setSqlSessionFactoryBeanName(String)} instead.
*
* @param sqlSessionFactory
*/
@Deprecated
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
/**
* Specifies which {@code SqlSessionFactory} to use in the case that there is
* more than one in the spring context. Usually this is only needed when you
* have more than one datasource.
* <p>
* Note bean names are used, not bean references. This is because the scanner
* loads early during the start process and it is too early to build mybatis
* object instances.
*
* @since 1.1.0
*
* @param sqlSessionFactoryName Bean name of the {@code SqlSessionFactory}
*/
public void setSqlSessionFactoryBeanName(String sqlSessionFactoryName) {
this.sqlSessionFactoryBeanName = sqlSessionFactoryName;
}
/**
* {@inheritDoc}
*/
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
/**
* {@inheritDoc}
*/
public void setBeanName(String name) {
this.beanName = name;
}
/**
* {@inheritDoc}
*/
public void afterPropertiesSet() throws Exception {
notNull(this.basePackage, "Property 'basePackage' is required");
}
/**
* {@inheritDoc}
*/
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}
/**
* {@inheritDoc}
*/
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
processPropertyPlaceHolders();
Scanner scanner = new Scanner(beanDefinitionRegistry);
scanner.setResourceLoader(this.applicationContext);
scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
}
/*
* BeanDefinitionRegistries are called early in application startup, before
* BeanFactoryPostProcessors. This means that PropertyResourceConfigurers will not have been
* loaded and any property substitution of this class' properties will fail. To avoid this, find
* any PropertyResourceConfigurers defined in the context and run them on this class' bean
* definition. Then update the values.
*/
private void processPropertyPlaceHolders() {
Map<String, PropertyResourceConfigurer> prcs = applicationContext.getBeansOfType(PropertyResourceConfigurer.class);
if (!prcs.isEmpty() && applicationContext instanceof GenericApplicationContext) {
BeanDefinition mapperScannerBean = ((GenericApplicationContext) applicationContext)
.getBeanFactory().getBeanDefinition(beanName);
// PropertyResourceConfigurer does not expose any methods to explicitly perform
// property placeholder substitution. Instead, create a BeanFactory that just
// contains this mapper scanner and post process the factory.
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition(beanName, mapperScannerBean);
for (PropertyResourceConfigurer prc : prcs.values()) {
prc.postProcessBeanFactory(factory);
}
PropertyValues values = mapperScannerBean.getPropertyValues();
this.basePackage = updatePropertyValue("basePackage", values);
this.sqlSessionFactoryBeanName = updatePropertyValue("sqlSessionFactoryBeanName", values);
this.sqlSessionTemplateBeanName = updatePropertyValue("sqlSessionTemplateBeanName", values);
}
}
private String updatePropertyValue(String propertyName, PropertyValues values) {
PropertyValue property = values.getPropertyValue(propertyName);
if (property == null) {
return null;
}
Object value = property.getValue();
if (value == null) {
return null;
} else if (value instanceof String) {
return value.toString();
} else if (value instanceof TypedStringValue) {
return ((TypedStringValue) value).getValue();
} else {
return null;
}
}
private final class Scanner extends ClassPathBeanDefinitionScanner {
public Scanner(BeanDefinitionRegistry registry) {
super(registry);
}
/**
* Configures parent scanner to search for the right interfaces. It can search for all
* interfaces or just for those that extends a markerInterface or/and those annotated with
* the annotationClass
*/
@Override
protected void registerDefaultFilters() {
boolean acceptAllInterfaces = true;
// if specified, use the given annotation and / or marker interface
if (MapperScannerConfigurer.this.annotationClass != null) {
addIncludeFilter(new AnnotationTypeFilter(MapperScannerConfigurer.this.annotationClass));
acceptAllInterfaces = false;
}
// override AssignableTypeFilter to ignore matches on the actual marker interface
if (MapperScannerConfigurer.this.markerInterface != null) {
addIncludeFilter(new AssignableTypeFilter(MapperScannerConfigurer.this.markerInterface) {
@Override
protected boolean matchClassName(String className) {
return false;
}
});
acceptAllInterfaces = false;
}
if (acceptAllInterfaces) {
// default include filter that accepts all classes
addIncludeFilter(new TypeFilter() {
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
return true;
}
});
}
// exclude package-info.java
addExcludeFilter(new TypeFilter() {
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
String className = metadataReader.getClassMetadata().getClassName();
return className.endsWith("package-info");
}
});
}
/**
* Calls the parent search that will search and register all the candidates. Then the
* registered objects are post processed to set them as MapperFactoryBeans
*/
@Override
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
if (beanDefinitions.isEmpty()) {
logger.warn("No MyBatis mapper was found in '" + MapperScannerConfigurer.this.basePackage
+ "' package. Please check your configuration.");
} else {
for (BeanDefinitionHolder holder : beanDefinitions) {
GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition();
if (logger.isDebugEnabled()) {
logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName()
+ "' and '" + definition.getBeanClassName() + "' mapperInterface");
}
// the mapper interface is the original class of the bean
// but, the actual class of the bean is MapperFactoryBean
definition.getPropertyValues().add("mapperInterface", definition.getBeanClassName());
definition.setBeanClass(MapperFactoryBean.class);
definition.getPropertyValues().add("addToConfig", MapperScannerConfigurer.this.addToConfig);
boolean explicitFactoryUsed = false;
if (StringUtils.hasLength(MapperScannerConfigurer.this.sqlSessionFactoryBeanName)) {
definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(MapperScannerConfigurer.this.sqlSessionFactoryBeanName));
- definition.getPropertyValues().add("sqlSessionTemplate", null);
explicitFactoryUsed = true;
} else if (MapperScannerConfigurer.this.sqlSessionFactory != null) {
definition.getPropertyValues().add("sqlSessionFactory", MapperScannerConfigurer.this.sqlSessionFactory);
- definition.getPropertyValues().add("sqlSessionTemplate", null);
explicitFactoryUsed = true;
}
if (StringUtils.hasLength(MapperScannerConfigurer.this.sqlSessionTemplateBeanName)) {
if (explicitFactoryUsed) {
logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
}
definition.getPropertyValues().add("sqlSessionTemplate", new RuntimeBeanReference(MapperScannerConfigurer.this.sqlSessionTemplateBeanName));
definition.getPropertyValues().add("sqlSessionFactory", null);
} else if (MapperScannerConfigurer.this.sqlSessionTemplate != null) {
if (explicitFactoryUsed) {
logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
}
definition.getPropertyValues().add("sqlSessionTemplate", MapperScannerConfigurer.this.sqlSessionTemplate);
definition.getPropertyValues().add("sqlSessionFactory", null);
}
}
}
return beanDefinitions;
}
@Override
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
return (beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().isIndependent());
}
@Override
protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition) throws IllegalStateException {
if (super.checkCandidate(beanName, beanDefinition)) {
return true;
} else {
logger.warn("Skipping MapperFactoryBean with name '" + beanName
+ "' and '" + beanDefinition.getBeanClassName() + "' mapperInterface"
+ ". Bean already defined with the same name!");
return false;
}
}
}
}
| false | true | protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
if (beanDefinitions.isEmpty()) {
logger.warn("No MyBatis mapper was found in '" + MapperScannerConfigurer.this.basePackage
+ "' package. Please check your configuration.");
} else {
for (BeanDefinitionHolder holder : beanDefinitions) {
GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition();
if (logger.isDebugEnabled()) {
logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName()
+ "' and '" + definition.getBeanClassName() + "' mapperInterface");
}
// the mapper interface is the original class of the bean
// but, the actual class of the bean is MapperFactoryBean
definition.getPropertyValues().add("mapperInterface", definition.getBeanClassName());
definition.setBeanClass(MapperFactoryBean.class);
definition.getPropertyValues().add("addToConfig", MapperScannerConfigurer.this.addToConfig);
boolean explicitFactoryUsed = false;
if (StringUtils.hasLength(MapperScannerConfigurer.this.sqlSessionFactoryBeanName)) {
definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(MapperScannerConfigurer.this.sqlSessionFactoryBeanName));
definition.getPropertyValues().add("sqlSessionTemplate", null);
explicitFactoryUsed = true;
} else if (MapperScannerConfigurer.this.sqlSessionFactory != null) {
definition.getPropertyValues().add("sqlSessionFactory", MapperScannerConfigurer.this.sqlSessionFactory);
definition.getPropertyValues().add("sqlSessionTemplate", null);
explicitFactoryUsed = true;
}
if (StringUtils.hasLength(MapperScannerConfigurer.this.sqlSessionTemplateBeanName)) {
if (explicitFactoryUsed) {
logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
}
definition.getPropertyValues().add("sqlSessionTemplate", new RuntimeBeanReference(MapperScannerConfigurer.this.sqlSessionTemplateBeanName));
definition.getPropertyValues().add("sqlSessionFactory", null);
} else if (MapperScannerConfigurer.this.sqlSessionTemplate != null) {
if (explicitFactoryUsed) {
logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
}
definition.getPropertyValues().add("sqlSessionTemplate", MapperScannerConfigurer.this.sqlSessionTemplate);
definition.getPropertyValues().add("sqlSessionFactory", null);
}
}
}
return beanDefinitions;
}
| protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
if (beanDefinitions.isEmpty()) {
logger.warn("No MyBatis mapper was found in '" + MapperScannerConfigurer.this.basePackage
+ "' package. Please check your configuration.");
} else {
for (BeanDefinitionHolder holder : beanDefinitions) {
GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition();
if (logger.isDebugEnabled()) {
logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName()
+ "' and '" + definition.getBeanClassName() + "' mapperInterface");
}
// the mapper interface is the original class of the bean
// but, the actual class of the bean is MapperFactoryBean
definition.getPropertyValues().add("mapperInterface", definition.getBeanClassName());
definition.setBeanClass(MapperFactoryBean.class);
definition.getPropertyValues().add("addToConfig", MapperScannerConfigurer.this.addToConfig);
boolean explicitFactoryUsed = false;
if (StringUtils.hasLength(MapperScannerConfigurer.this.sqlSessionFactoryBeanName)) {
definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(MapperScannerConfigurer.this.sqlSessionFactoryBeanName));
explicitFactoryUsed = true;
} else if (MapperScannerConfigurer.this.sqlSessionFactory != null) {
definition.getPropertyValues().add("sqlSessionFactory", MapperScannerConfigurer.this.sqlSessionFactory);
explicitFactoryUsed = true;
}
if (StringUtils.hasLength(MapperScannerConfigurer.this.sqlSessionTemplateBeanName)) {
if (explicitFactoryUsed) {
logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
}
definition.getPropertyValues().add("sqlSessionTemplate", new RuntimeBeanReference(MapperScannerConfigurer.this.sqlSessionTemplateBeanName));
definition.getPropertyValues().add("sqlSessionFactory", null);
} else if (MapperScannerConfigurer.this.sqlSessionTemplate != null) {
if (explicitFactoryUsed) {
logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
}
definition.getPropertyValues().add("sqlSessionTemplate", MapperScannerConfigurer.this.sqlSessionTemplate);
definition.getPropertyValues().add("sqlSessionFactory", null);
}
}
}
return beanDefinitions;
}
|
diff --git a/src/org/wikipedia/NearMePlugin.java b/src/org/wikipedia/NearMePlugin.java
index 03a720d..549df20 100644
--- a/src/org/wikipedia/NearMePlugin.java
+++ b/src/org/wikipedia/NearMePlugin.java
@@ -1,43 +1,47 @@
package org.wikipedia;
import org.json.JSONArray;
import android.content.Intent;
import android.util.Log;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
public class NearMePlugin extends Plugin {
public static int GET_GEONAME_URL = 0;
public static int RESULT_OK = 0;
private String callbackId;
@Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult result = null;
this.callbackId = callbackId;
if(action.compareTo("startNearMeActivity") == 0) {
- Intent intent = new Intent(ctx, NearMeActivity.class);
- ctx.startActivityForResult((Plugin) this, intent, GET_GEONAME_URL);
- result = new PluginResult(PluginResult.Status.NO_RESULT);
- result.setKeepCallback(true);
+ try {
+ Intent intent = new Intent(ctx, Class.forName("org.wikipedia.NearMeActivity"));
+ ctx.startActivityForResult((Plugin) this, intent, GET_GEONAME_URL);
+ result = new PluginResult(PluginResult.Status.NO_RESULT);
+ result.setKeepCallback(true);
+ } catch (ClassNotFoundException e) {
+ result = new PluginResult(PluginResult.Status.CLASS_NOT_FOUND_EXCEPTION);
+ }
}
return result;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == GET_GEONAME_URL && intent != null) {
if(resultCode == RESULT_OK) {
Log.d("NearMePlugin", intent.getExtras().getString("wikipediaUrl"));
this.success(new PluginResult(PluginResult.Status.OK, intent.getExtras().getString("wikipediaUrl")), callbackId);
}
} else {
this.success(new PluginResult(PluginResult.Status.NO_RESULT), callbackId);
}
}
}
| true | true | public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult result = null;
this.callbackId = callbackId;
if(action.compareTo("startNearMeActivity") == 0) {
Intent intent = new Intent(ctx, NearMeActivity.class);
ctx.startActivityForResult((Plugin) this, intent, GET_GEONAME_URL);
result = new PluginResult(PluginResult.Status.NO_RESULT);
result.setKeepCallback(true);
}
return result;
}
| public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult result = null;
this.callbackId = callbackId;
if(action.compareTo("startNearMeActivity") == 0) {
try {
Intent intent = new Intent(ctx, Class.forName("org.wikipedia.NearMeActivity"));
ctx.startActivityForResult((Plugin) this, intent, GET_GEONAME_URL);
result = new PluginResult(PluginResult.Status.NO_RESULT);
result.setKeepCallback(true);
} catch (ClassNotFoundException e) {
result = new PluginResult(PluginResult.Status.CLASS_NOT_FOUND_EXCEPTION);
}
}
return result;
}
|
diff --git a/test/src/com/redhat/ceylon/compiler/java/test/statement/StatementTest.java b/test/src/com/redhat/ceylon/compiler/java/test/statement/StatementTest.java
index ad9fbe69c..569e50d7d 100755
--- a/test/src/com/redhat/ceylon/compiler/java/test/statement/StatementTest.java
+++ b/test/src/com/redhat/ceylon/compiler/java/test/statement/StatementTest.java
@@ -1,719 +1,719 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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 distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.test.statement;
import org.junit.Ignore;
import org.junit.Test;
import com.redhat.ceylon.compiler.java.test.CompilerError;
import com.redhat.ceylon.compiler.java.test.CompilerTest;
public class StatementTest extends CompilerTest {
//
// Method attributes and variables
@Test
public void testAtrMethodAttribute(){
compareWithJavaSource("attribute/MethodAttribute");
}
@Test
public void testAtrMethodAttributeWithInitializer(){
compareWithJavaSource("attribute/MethodAttributeWithInitializer");
}
@Test
public void testAtrMethodAttributeWithLateInitializer(){
compareWithJavaSource("attribute/MethodAttributeWithLateInitializer");
}
@Test
public void testAtrMethodVariable(){
compareWithJavaSource("attribute/MethodVariable");
}
@Test
public void testAtrMethodVariableWithInitializer(){
compareWithJavaSource("attribute/MethodVariableWithInitializer");
}
@Test
public void testAtrMethodVariableWithLateInitializer(){
compareWithJavaSource("attribute/MethodVariableWithLateInitializer");
}
//
// if/else
@Test
public void testConInitializerIf(){
compareWithJavaSource("conditional/InitializerIf");
}
@Test
public void testConInitializerIfElse(){
compareWithJavaSource("conditional/InitializerIfElse");
}
@Test
public void testConInitializerIfElseIf(){
compareWithJavaSource("conditional/InitializerIfElseIf");
}
@Test
public void testConMethodIf(){
compareWithJavaSource("conditional/MethodIf");
}
@Test
public void testConMethodIfElse(){
compareWithJavaSource("conditional/MethodIfElse");
}
@Test
public void testConMethodIfElseIf(){
compareWithJavaSource("conditional/MethodIfElseIf");
}
@Test
public void testConMethodIfTrue(){
compareWithJavaSource("conditional/MethodIfTrue");
}
@Test
public void testConMethodIfTrueElse(){
compareWithJavaSource("conditional/MethodIfTrueElse");
}
@Test
public void testConMethodIfFalse(){
compareWithJavaSource("conditional/MethodIfFalse");
}
@Test
public void testConMethodIfFalseElse(){
compareWithJavaSource("conditional/MethodIfFalseElse");
}
@Test
public void testConMethodIfExists(){
compareWithJavaSource("conditional/MethodIfExists");
}
@Test
public void testConMethodIfExistsSequence(){
compareWithJavaSource("conditional/MethodIfExistsSequence");
}
@Test
public void testConMethodIfExistsWithMethod(){
compareWithJavaSource("conditional/MethodIfExistsWithMethod");
}
@Test
public void testConMethodIfExists2dArray(){
compareWithJavaSource("conditional/MethodIfExists2dArray");
}
@Test
public void testConMethodIfIsFoo(){
compile("conditional/FooBar.ceylon");
compareWithJavaSource("conditional/MethodIfIsFoo");
}
@Test
public void testConMethodIfIsVoidSeq(){
compareWithJavaSource("conditional/MethodIfIsVoidSeq");
}
@Test
public void testConMethodIfIsNotNull(){
compareWithJavaSource("conditional/MethodIfIsNotNull");
}
@Test
public void testConMethodIfIsNotObject(){
compareWithJavaSource("conditional/MethodIfIsNotObject");
}
@Test
public void testConMethodIfIsNullUnion(){
compareWithJavaSource("conditional/MethodIfIsNullUnion");
}
@Test
public void testConMethodIfIsWithIntersection(){
compile("conditional/FooBar.ceylon");
compareWithJavaSource("conditional/MethodIfIsWithIntersection");
}
@Test
public void testConMethodIfIsWithMethod(){
compile("conditional/FooBar.ceylon");
compareWithJavaSource("conditional/MethodIfIsWithMethod");
}
@Test
public void testConMethodIfIsWithUnion(){
compile("conditional/FooBar.ceylon");
compareWithJavaSource("conditional/MethodIfIsWithUnion");
}
@Test
public void testConMethodIfIsNull2(){
compareWithJavaSource("conditional/MethodIfIsNull2");
}
@Test
public void testConMethodIfIsNull(){
compareWithJavaSource("conditional/MethodIfIsNull");
}
@Test
@Ignore("M5: requires reified generics")
public void testConMethodIfIsGeneric(){
compareWithJavaSource("conditional/MethodIfIsGeneric");
}
@Test
@Ignore("M5: requires support from spec for satisfies conditions (reified generics)")
public void testConMethodIfSatisfies(){
compareWithJavaSource("conditional/MethodIfSatisfies");
}
@Test
@Ignore("M5: requires support from spec for satisfies conditions (reified generics)")
public void testConMethodIfSatisfiesMultiple(){
compareWithJavaSource("conditional/MethodIfSatisfiesMultiple");
}
@Test
public void testConMethodIfNonEmptySequence(){
compareWithJavaSource("conditional/MethodIfNonEmptySequence");
}
@Test
public void testConMethodIfConditionListBoolBool(){
compareWithJavaSource("conditional/MethodIfConditionListBoolBool");
}
@Test
public void testConMethodIfConditionListIsIs(){
compareWithJavaSource("conditional/MethodIfConditionListIsIs");
}
@Test
public void testConMethodIfConditionListBoolBoolIs(){
compareWithJavaSource("conditional/MethodIfConditionListBoolBoolIs");
}
@Test
public void testConMethodIfConditionListBoolIsBool(){
compareWithJavaSource("conditional/MethodIfConditionListBoolIsBool");
}
@Test
public void testConMethodIfConditionListExistsIsBool(){
compareWithJavaSource("conditional/MethodIfConditionListExistsIsBool");
}
@Test
public void testConMethodIfConditionListIsBool(){
compareWithJavaSource("conditional/MethodIfConditionListIsBool");
}
@Test
public void testConMethodIfConditionListIsBoolBool(){
compareWithJavaSource("conditional/MethodIfConditionListIsBoolBool");
}
@Test
public void testConMethodIfConditionListNonemptyIsBool(){
compareWithJavaSource("conditional/MethodIfConditionListNonemptyIsBool");
}
//
// for
@Test
public void testLopMethodForRange(){
compareWithJavaSource("loop/MethodForRange");
}
@Test
public void testLopMethodForIterator(){
compareWithJavaSource("loop/MethodForIterator");
}
@Test
public void testLopMethodForDoubleIterator(){
compareWithJavaSource("loop/MethodForDoubleIterator");
}
@Test
public void testLopMethodForElse(){
compareWithJavaSource("loop/MethodForElse");
}
@Test
public void testLopMethodForBreakElse(){
compileAndRun("com.redhat.ceylon.compiler.java.test.statement.loop.methodForBreakElse",
"loop/MethodForBreakElse.ceylon");
}
@Test
public void testLopRangeOpIterationOptimization(){
compareWithJavaSource("loop/RangeOpIterationOptimization");
}
@Test
public void testLopRangeOpIterationOptimizationCorrect(){
compileAndRun("com.redhat.ceylon.compiler.java.test.statement.loop.rangeOpIterationOptimizationCorrect",
"loop/RangeOpIterationOptimizationCorrect.ceylon");
}
//
// [do] while
@Test
public void testLopMethodWhile(){
compareWithJavaSource("loop/MethodWhile");
}
@Test
public void testLopMethodWhileTrue(){
compareWithJavaSource("loop/MethodWhileTrue");
}
@Test
public void testLopMethodWhileConditionList(){
compareWithJavaSource("loop/MethodWhileConditionList");
}
@Test
public void testConMethodWhileExists(){
compareWithJavaSource("loop/MethodWhileExists");
}
@Test
public void testConMethodWhileExistsSequence(){
compareWithJavaSource("loop/MethodWhileExistsSequence");
}
@Test
public void testConMethodWhileExistsWithMethod(){
compareWithJavaSource("loop/MethodWhileExistsWithMethod");
}
@Test
public void testConMethodWhileExists2dArray(){
compareWithJavaSource("loop/MethodWhileExists2dArray");
}
@Test
public void testConMethodWhileIsFoo(){
compile("loop/FooBar.ceylon");
compareWithJavaSource("loop/MethodWhileIsFoo");
}
@Test
public void testConMethodWhileIsNotNull(){
compareWithJavaSource("loop/MethodWhileIsNotNull");
}
@Test
public void testConMethodWhileIsNotObject(){
compareWithJavaSource("loop/MethodWhileIsNotObject");
}
@Test
public void testConMethodWhileIsNullUnion(){
compareWithJavaSource("loop/MethodWhileIsNullUnion");
}
@Test
public void testConMethodWhileIsWithIntersection(){
compile("loop/FooBar.ceylon");
compareWithJavaSource("loop/MethodWhileIsWithIntersection");
}
@Test
public void testConMethodWhileIsWithMethod(){
compile("loop/FooBar.ceylon");
compareWithJavaSource("loop/MethodWhileIsWithMethod");
}
@Test
public void testConMethodWhileIsWithUnion(){
compile("loop/FooBar.ceylon");
compareWithJavaSource("loop/MethodWhileIsWithUnion");
}
@Test
public void testConMethodWhileIsNull2(){
compareWithJavaSource("loop/MethodWhileIsNull2");
}
@Test
public void testConMethodWhileIsNull(){
compareWithJavaSource("loop/MethodWhileIsNull");
}
@Test
@Ignore("M5: requires reified generics")
public void testConMethodWhileIsGeneric(){
compareWithJavaSource("loop/MethodWhileIsGeneric");
}
@Test
@Ignore("M5: requires support from spec for satisfies conditions (reified generics)")
public void testConMethodWhileSatisfies(){
compareWithJavaSource("loop/MethodWhileSatisfies");
}
@Test
@Ignore("M5: requires support from spec for satisfies conditions (reified generics)")
public void testConMethodWhileSatisfiesMultiple(){
compareWithJavaSource("loop/MethodWhileSatisfiesMultiple");
}
@Test
public void testConMethodWhileNonEmptySequence(){
compareWithJavaSource("loop/MethodWhileNonEmptySequence");
}
@Test
public void testConMethodWhileConditionListBoolBool(){
compareWithJavaSource("loop/MethodWhileConditionListBoolBool");
}
@Test
public void testConMethodWhileConditionListIsIs(){
compareWithJavaSource("loop/MethodWhileConditionListIsIs");
}
@Test
public void testConMethodWhileConditionListBoolBoolIs(){
compareWithJavaSource("loop/MethodWhileConditionListBoolBoolIs");
}
@Test
public void testConMethodWhileConditionListBoolIsBool(){
compareWithJavaSource("loop/MethodWhileConditionListBoolIsBool");
}
@Test
public void testConMethodWhileConditionListExistsIsBool(){
compareWithJavaSource("loop/MethodWhileConditionListExistsIsBool");
}
@Test
public void testConMethodWhileConditionListIsBool(){
compareWithJavaSource("loop/MethodWhileConditionListIsBool");
}
@Test
public void testConMethodWhileConditionListIsBoolBool(){
compareWithJavaSource("loop/MethodWhileConditionListIsBoolBool");
}
@Test
public void testConMethodWhileConditionListNonemptyIsBool(){
compareWithJavaSource("loop/MethodWhileConditionListNonemptyIsBool");
}
//
// Locals (value / function)
@Test
public void testLocValueKeyword(){
compareWithJavaSource("local/ValueKeyword");
}
@Test
public void testLocFunctionKeyword(){
compareWithJavaSource("local/FunctionKeyword");
}
@Test
public void testLocFunctionAndValueKeyword(){
compareWithJavaSource("local/FunctionAndValueKeyword");
}
@Test
public void testTryExceptionAttr(){
compareWithJavaSource("trycatch/ExceptionAttr");
}
@Test
public void testTryExceptionAttributes(){
compareWithJavaSource("trycatch/ExceptionAttributes");
}
@Test
public void testTryBareThrow(){
compareWithJavaSource("trycatch/Throw");
}
@Test
public void testTryThrowException(){
compareWithJavaSource("trycatch/ThrowException");
}
@Test
public void testTryThrowExceptionNamedArgs(){
compareWithJavaSource("trycatch/ThrowExceptionNamedArgs");
}
@Test
public void testTryThrowExceptionSubclass(){
compareWithJavaSource("trycatch/ThrowExceptionSubclass");
}
@Test
public void testTryThrowMethodResult(){
compareWithJavaSource("trycatch/ThrowMethodResult");
}
@Test
public void testTryThrowThrowable(){
compareWithJavaSource("trycatch/ThrowThrowable");
}
@Test
public void testTryThrowNpe(){
compareWithJavaSource("trycatch/ThrowNpe");
}
@Test
public void testTryTryFinally(){
compareWithJavaSource("trycatch/TryFinally");
}
@Test
public void testTryTryCatch(){
compareWithJavaSource("trycatch/TryCatch");
}
@Test
public void testTryTryCatchFinally(){
compareWithJavaSource("trycatch/TryCatchFinally");
}
@Test
public void testTryTryCatchSubclass(){
compareWithJavaSource("trycatch/TryCatchSubclass");
}
@Test
public void testTryTryCatchUnion(){
compareWithJavaSource("trycatch/TryCatchUnion");
}
@Test
public void testTryTryWithResource(){
compareWithJavaSource("trycatch/TryWithResource");
}
@Test
public void testTryReplaceExceptionAtJavaCallSite(){
compareWithJavaSource("trycatch/WrapExceptionAtJavaCallSite");
}
@Test
public void testSwitchIsExhaustive(){
compareWithJavaSource("swtch/SwitchIsExhaustive");
}
@Test
public void testSwitchIsEnumeratedPrimitives(){
compareWithJavaSource("swtch/SwitchIsEnumeratedPrimitives");
}
@Test
public void testSwitchIsNonExhaustive(){
compareWithJavaSource("swtch/SwitchIsNonExhaustive");
}
@Test
public void testSwitchIsVarSubst(){
compareWithJavaSource("swtch/SwitchIsVarSubst");
}
@Test
public void testSwitchMatch(){
compareWithJavaSource("swtch/SwitchMatch");
}
@Test
public void testReturnAnonFunction(){
compareWithJavaSource("retrn/ReturnAnonFunction");
}
@Test
public void testAssertSimple() {
compareWithJavaSource("conditional/AssertionSimple");
}
@Test
public void testAssertSpecial() {
compareWithJavaSource("conditional/AssertionSpecial");
}
@Test
public void testAssertConditionList() {
compareWithJavaSource("conditional/AssertionConditionList");
}
@Test
public void testConAssertExists(){
compareWithJavaSource("conditional/AssertExists");
}
@Test
public void testConAssertExistsSequence(){
compareWithJavaSource("conditional/AssertExistsSequence");
}
@Test
public void testConAssertExistsWithMethod(){
compareWithJavaSource("conditional/AssertExistsWithMethod");
}
@Test
public void testConAssertExists2dArray(){
compareWithJavaSource("conditional/AssertExists2dArray");
}
@Test
public void testConAssertIsFoo(){
compile("conditional/FooBar.ceylon");
compareWithJavaSource("conditional/AssertIsFoo");
}
@Test
public void testConAssertIsNotNull(){
compareWithJavaSource("conditional/AssertIsNotNull");
}
@Test
public void testConAssertIsNotObject(){
compareWithJavaSource("conditional/AssertIsNotObject");
}
@Test
public void testConAssertIsNullUnion(){
compareWithJavaSource("conditional/AssertIsNullUnion");
}
@Test
public void testConAssertIsWithIntersection(){
compile("conditional/FooBar.ceylon");
compareWithJavaSource("conditional/AssertIsWithIntersection");
}
@Test
public void testConAssertIsWithMethod(){
compile("conditional/FooBar.ceylon");
compareWithJavaSource("conditional/AssertIsWithMethod");
}
@Test
public void testConAssertIsWithUnion(){
compile("conditional/FooBar.ceylon");
compareWithJavaSource("conditional/AssertIsWithUnion");
}
@Test
public void testConAssertIsNull2(){
compareWithJavaSource("conditional/AssertIsNull2");
}
@Test
public void testConAssertIsNull(){
compareWithJavaSource("conditional/AssertIsNull");
}
@Test
@Ignore("M5: requires reified generics")
public void testConAssertIsGeneric(){
compareWithJavaSource("conditional/AssertIsGeneric");
}
@Test
@Ignore("M5: requires support from spec for satisfies conditions (reified generics)")
public void testConAssertSatisfies(){
compareWithJavaSource("conditional/AssertSatisfies");
}
@Test
@Ignore("M5: requires support from spec for satisfies conditions (reified generics)")
public void testConAssertSatisfiesMultiple(){
compareWithJavaSource("conditional/AssertSatisfiesMultiple");
}
@Test
public void testConAssertNonEmptySequence(){
compareWithJavaSource("conditional/AssertNonEmptySequence");
}
@Test
public void testConAssertConditionListBoolBool(){
compareWithJavaSource("conditional/AssertConditionListBoolBool");
}
@Test
public void testConAssertConditionListIsIs(){
compareWithJavaSource("conditional/AssertConditionListIsIs");
}
@Test
public void testConAssertConditionListBoolBoolIs(){
compareWithJavaSource("conditional/AssertConditionListBoolBoolIs");
}
@Test
public void testConAssertConditionListBoolIsBool(){
compareWithJavaSource("conditional/AssertConditionListBoolIsBool");
}
@Test
public void testConAssertConditionListExistsIsBool(){
compareWithJavaSource("conditional/AssertConditionListExistsIsBool");
}
@Test
public void testConAssertConditionListIsBool(){
compareWithJavaSource("conditional/AssertConditionListIsBool");
}
@Test
public void testConAssertConditionListIsBoolBool(){
compareWithJavaSource("conditional/AssertConditionListIsBoolBool");
}
@Test
public void testConAssertConditionListNonemptyIsBool(){
compareWithJavaSource("conditional/AssertConditionListNonemptyIsBool");
}
@Test
public void testConAssertVariableScopes(){
compareWithJavaSource("conditional/AssertVariableScopes");
}
@Test
public void testConAssertFalse(){
compareWithJavaSource("conditional/AssertFalse");
}
//
// Dynamic blocks
@Test
public void testDynBlock(){
assertErrors("dynamic/Dynamic",
new CompilerError(22, "Dynamic not yet supported on the JVM"),
- new CompilerError(25, "Dynamic not yet supported on the JVM"));
+ new CompilerError(26, "value type could not be inferred"));
}
}
| true | true | public void testDynBlock(){
assertErrors("dynamic/Dynamic",
new CompilerError(22, "Dynamic not yet supported on the JVM"),
new CompilerError(25, "Dynamic not yet supported on the JVM"));
}
| public void testDynBlock(){
assertErrors("dynamic/Dynamic",
new CompilerError(22, "Dynamic not yet supported on the JVM"),
new CompilerError(26, "value type could not be inferred"));
}
|
diff --git a/test/src/com/rabbitmq/client/test/functional/UnexpectedFrames.java b/test/src/com/rabbitmq/client/test/functional/UnexpectedFrames.java
index ca7e1db1f..30b1d6811 100644
--- a/test/src/com/rabbitmq/client/test/functional/UnexpectedFrames.java
+++ b/test/src/com/rabbitmq/client/test/functional/UnexpectedFrames.java
@@ -1,125 +1,123 @@
package com.rabbitmq.client.test.functional;
import com.rabbitmq.client.*;
import com.rabbitmq.client.impl.*;
import com.rabbitmq.client.test.BrokerTestCase;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
/**
* Test that the server correctly handles us when we send it bad frames
*/
public class UnexpectedFrames extends BrokerTestCase {
private interface Confuser {
public Frame confuse(Frame frame) throws IOException;
}
public void testMissingHeader() throws IOException {
expectUnexpectedFrameError(new Confuser() {
public Frame confuse(Frame frame) {
if (frame.type == AMQP.FRAME_HEADER) {
return null;
}
return frame;
}
});
}
public void testMissingMethod() throws IOException {
expectUnexpectedFrameError(new Confuser() {
public Frame confuse(Frame frame) {
if (frame.type == AMQP.FRAME_METHOD) {
// We can't just skip the method as that will lead us to
// send 0 bytes and hang waiting for a response.
frame.type = AMQP.FRAME_HEADER;
}
return frame;
}
});
}
public void testMissingBody() throws IOException {
expectUnexpectedFrameError(new Confuser() {
public Frame confuse(Frame frame) {
if (frame.type == AMQP.FRAME_BODY) {
return null;
}
return frame;
}
});
}
public void testWrongClassInHeader() throws IOException {
expectUnexpectedFrameError(new Confuser() {
public Frame confuse(Frame frame) throws IOException {
if (frame.type == AMQP.FRAME_HEADER) {
byte[] payload = frame.accumulator.toByteArray();
// First two bytes = class ID, must match class ID from
// method.
payload[0] = 12;
payload[1] = 34;
frame.accumulator = new ByteArrayOutputStream();
frame.accumulator.write(payload, 0, payload.length);
}
return frame;
}
});
}
private void expectUnexpectedFrameError(Confuser confuser) throws IOException {
ConnectionFactory factory = new ConnectionFactory();
Socket socket = factory.getSocketFactory().createSocket("localhost",
AMQP.PROTOCOL.PORT);
ConfusedFrameHandler handler = new ConfusedFrameHandler(socket);
AMQConnection connection = new AMQConnection(factory, handler);
try {
connection.start(false);
} catch (RedirectException e) {}
Channel channel = connection.createChannel();
handler.confuser = confuser;
try {
String queue = channel.queueDeclare().getQueue();
channel.basicPublish("", queue, null, "Hello".getBytes());
GetResponse result = channel.basicGet(queue, false);
channel.basicAck(result.getEnvelope().getDeliveryTag(), false);
fail("We should have seen an UNEXPECTED_FRAME by now");
}
catch (IOException e) {
- // todo: use AMQP.UNEXPECTED_FRAME as soon as
- // 0.9.1 codegen becomes available
- checkShutdownSignal(505, e);
+ checkShutdownSignal(AMQP.UNEXPECTED_FRAME, e);
}
}
private static class ConfusedFrameHandler extends SocketFrameHandler {
public ConfusedFrameHandler(Socket socket) throws IOException {
super(socket);
}
@Override
public void writeFrame(Frame frame) throws IOException {
Frame confusedFrame = new Frame();
confusedFrame.accumulator = frame.accumulator;
confusedFrame.channel = frame.channel;
confusedFrame.type = frame.type;
confusedFrame = confuser.confuse(confusedFrame);
if (confusedFrame != null) {
super.writeFrame(confusedFrame);
}
}
public Confuser confuser = new Confuser() {
public Frame confuse(Frame frame) {
// Do nothing to start with, we need to negotiate before the
// server will send us unexpected_frame errors
return frame;
}
};
}
}
| true | true | private void expectUnexpectedFrameError(Confuser confuser) throws IOException {
ConnectionFactory factory = new ConnectionFactory();
Socket socket = factory.getSocketFactory().createSocket("localhost",
AMQP.PROTOCOL.PORT);
ConfusedFrameHandler handler = new ConfusedFrameHandler(socket);
AMQConnection connection = new AMQConnection(factory, handler);
try {
connection.start(false);
} catch (RedirectException e) {}
Channel channel = connection.createChannel();
handler.confuser = confuser;
try {
String queue = channel.queueDeclare().getQueue();
channel.basicPublish("", queue, null, "Hello".getBytes());
GetResponse result = channel.basicGet(queue, false);
channel.basicAck(result.getEnvelope().getDeliveryTag(), false);
fail("We should have seen an UNEXPECTED_FRAME by now");
}
catch (IOException e) {
// todo: use AMQP.UNEXPECTED_FRAME as soon as
// 0.9.1 codegen becomes available
checkShutdownSignal(505, e);
}
}
| private void expectUnexpectedFrameError(Confuser confuser) throws IOException {
ConnectionFactory factory = new ConnectionFactory();
Socket socket = factory.getSocketFactory().createSocket("localhost",
AMQP.PROTOCOL.PORT);
ConfusedFrameHandler handler = new ConfusedFrameHandler(socket);
AMQConnection connection = new AMQConnection(factory, handler);
try {
connection.start(false);
} catch (RedirectException e) {}
Channel channel = connection.createChannel();
handler.confuser = confuser;
try {
String queue = channel.queueDeclare().getQueue();
channel.basicPublish("", queue, null, "Hello".getBytes());
GetResponse result = channel.basicGet(queue, false);
channel.basicAck(result.getEnvelope().getDeliveryTag(), false);
fail("We should have seen an UNEXPECTED_FRAME by now");
}
catch (IOException e) {
checkShutdownSignal(AMQP.UNEXPECTED_FRAME, e);
}
}
|
diff --git a/components/bio-formats/src/loci/formats/in/SlidebookReader.java b/components/bio-formats/src/loci/formats/in/SlidebookReader.java
index d8f6cb4de..46bb01be7 100644
--- a/components/bio-formats/src/loci/formats/in/SlidebookReader.java
+++ b/components/bio-formats/src/loci/formats/in/SlidebookReader.java
@@ -1,755 +1,758 @@
//
// SlidebookReader.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 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 loci.formats.in;
import java.io.EOFException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Vector;
import loci.common.RandomAccessInputStream;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
/**
* SlidebookReader is the file format reader for 3I Slidebook files.
* The strategies employed by this reader are highly suboptimal, as we
* have very little information on the Slidebook format.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://dev.loci.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/SlidebookReader.java">Trac</a>,
* <a href="http://dev.loci.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/SlidebookReader.java">SVN</a></dd></dl>
*
* @author Melissa Linkert melissa at glencoesoftware.com
*/
public class SlidebookReader extends FormatReader {
// -- Constants --
public static final long SLD_MAGIC_BYTES_1 = 0x6c000001L;
public static final long SLD_MAGIC_BYTES_2 = 0xf5010201L;
public static final long SLD_MAGIC_BYTES_3 = 0xf6010101L;
// -- Fields --
private Vector<Long> metadataOffsets;
private Vector<Long> pixelOffsets;
private Vector<Long> pixelLengths;
private Vector<Double> ndFilters;
private long[][] planeOffset;
private boolean adjust = true;
private boolean isSpool;
private Hashtable<Integer, Integer> metadataInPlanes;
// -- Constructor --
/** Constructs a new Slidebook reader. */
public SlidebookReader() {
super("Olympus Slidebook", new String[] {"sld", "spl"});
domains = new String[] {FormatTools.LM_DOMAIN};
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = 8;
if (!FormatTools.validStream(stream, blockLen, false)) return false;
long magicBytes = stream.readInt();
return magicBytes == SLD_MAGIC_BYTES_1 || magicBytes == SLD_MAGIC_BYTES_2;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
long offset = planeOffset[getSeries()][no];
in.seek(offset);
// if this is a spool file, there may be an extra metadata block here
if (isSpool) {
Integer[] keys = metadataInPlanes.keySet().toArray(new Integer[0]);
Arrays.sort(keys);
for (int key : keys) {
if (key < no) {
in.skipBytes(256);
}
}
in.order(false);
long magicBytes = (long) in.readInt() & 0xffffffffL;
in.order(isLittleEndian());
if (magicBytes == SLD_MAGIC_BYTES_3 && !metadataInPlanes.contains(no)) {
metadataInPlanes.put(no, 0);
in.skipBytes(252);
}
else in.seek(in.getFilePointer() - 4);
}
readPlane(in, x, y, w, h, buf);
return buf;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
metadataOffsets = pixelOffsets = pixelLengths = null;
ndFilters = null;
isSpool = false;
metadataInPlanes = null;
adjust = true;
planeOffset = null;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
isSpool = checkSuffix(id, "spl");
if (isSpool) {
metadataInPlanes = new Hashtable<Integer, Integer>();
}
LOGGER.info("Finding offsets to pixel data");
// Slidebook files appear to be comprised of four types of blocks:
// variable length pixel data blocks, 512 byte metadata blocks,
// 128 byte metadata blocks, and variable length metadata blocks.
//
// Fixed-length metadata blocks begin with a 2 byte identifier,
// e.g. 'i' or 'h'.
// Following this are two unknown bytes (usually 256), then a 2 byte
// endianness identifier - II or MM, for little or big endian, respectively.
// Presumably these blocks contain useful information, but for the most
// part we aren't sure what it is or how to extract it.
//
// Variable length metadata blocks begin with 0xffff and are
// (as far as I know) always between two fixed-length metadata blocks.
// These appear to be a relatively new addition to the format - they are
// only present in files received on/after March 30, 2008.
//
// Each pixel data block corresponds to one series.
// The first 'i' metadata block after each pixel data block contains
// the width and height of the planes in that block - this can (and does)
// vary between blocks.
//
// Z, C, and T sizes are computed heuristically based on the number of
// metadata blocks of a specific type.
in.skipBytes(4);
core[0].littleEndian = in.read() == 0x49;
in.order(isLittleEndian());
metadataOffsets = new Vector<Long>();
pixelOffsets = new Vector<Long>();
pixelLengths = new Vector<Long>();
ndFilters = new Vector<Double>();
in.seek(0);
// gather offsets to metadata and pixel data blocks
while (in.getFilePointer() < in.length() - 8) {
LOGGER.debug("Looking for block at {}", in.getFilePointer());
in.skipBytes(4);
int checkOne = in.read();
int checkTwo = in.read();
if ((checkOne == 'I' && checkTwo == 'I') ||
(checkOne == 'M' && checkTwo == 'M'))
{
LOGGER.debug("Found metadata offset: {}", (in.getFilePointer() - 6));
metadataOffsets.add(new Long(in.getFilePointer() - 6));
in.skipBytes(in.readShort() - 8);
}
else if (checkOne == -1 && checkTwo == -1) {
boolean foundBlock = false;
byte[] block = new byte[8192];
in.read(block);
while (!foundBlock) {
for (int i=0; i<block.length-2; i++) {
if ((block[i] == 'M' && block[i + 1] == 'M') ||
(block[i] == 'I' && block[i + 1] == 'I'))
{
foundBlock = true;
in.seek(in.getFilePointer() - block.length + i - 2);
LOGGER.debug("Found metadata offset: {}",
(in.getFilePointer() - 2));
metadataOffsets.add(new Long(in.getFilePointer() - 2));
in.skipBytes(in.readShort() - 5);
break;
}
}
if (!foundBlock) {
block[0] = block[block.length - 2];
block[1] = block[block.length - 1];
in.read(block, 2, block.length - 2);
}
}
}
else {
String s = null;
long fp = in.getFilePointer() - 6;
in.seek(fp);
int len = in.read();
if (len > 0 && len <= 32) {
s = in.readString(len);
}
if (s != null && s.indexOf("Annotation") != -1) {
if (s.equals("CTimelapseAnnotation")) {
in.skipBytes(41);
if (in.read() == 0) in.skipBytes(10);
else in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CIntensityBarAnnotation")) {
in.skipBytes(56);
int n = in.read();
while (n == 0 || n < 6 || n > 0x80) n = in.read();
in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CCubeAnnotation")) {
in.skipBytes(66);
int n = in.read();
if (n != 0) in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CScaleBarAnnotation")) {
in.skipBytes(38);
int extra = in.read();
if (extra <= 16) in.skipBytes(3 + extra);
else in.skipBytes(2);
}
}
else if (s != null && s.indexOf("Decon") != -1) {
in.seek(fp);
while (in.read() != ']');
}
else {
if ((fp % 2) == 1) fp -= 2;
in.seek(fp);
// make sure there isn't another block nearby
String checkString = in.readString(64);
if (checkString.indexOf("II") != -1 ||
checkString.indexOf("MM") != -1)
{
int index = checkString.indexOf("II");
if (index == -1) index = checkString.indexOf("MM");
in.seek(fp + index - 4);
continue;
}
else in.seek(fp);
LOGGER.debug("Found pixel offset at {}", fp);
pixelOffsets.add(new Long(fp));
try {
byte[] buf = new byte[8192];
boolean found = false;
int n = in.read(buf);
while (!found && in.getFilePointer() < in.length()) {
for (int i=0; i<n-6; i++) {
if ((buf[i + 4] == 'I' && buf[i + 5] == 'I') ||
(buf[i + 4] == 'M' && buf[i + 5] == 'M'))
{
if (((buf[i] == 'h' || buf[i] == 'i') && buf[i + 1] == 0) ||
(buf[i] == 0 && (buf[i + 1] == 'h' || buf[i + 1] == 'i')))
{
found = true;
in.seek(in.getFilePointer() - n + i - 20);
if (buf[i] == 'i' || buf[i + 1] == 'i') {
pixelOffsets.remove(pixelOffsets.size() - 1);
}
break;
}
else if (((buf[i] == 'j' || buf[i] == 'k' || buf[i] == 'n') &&
buf[i + 1] == 0) || (buf[i] == 0 && (buf[i + 1] == 'j' ||
buf[i + 1] == 'k' || buf[i + 1] == 'n')))
{
found = true;
pixelOffsets.remove(pixelOffsets.size() - 1);
break;
}
}
}
if (!found) {
byte[] tmp = buf;
buf = new byte[8192];
System.arraycopy(tmp, tmp.length - 20, buf, 0, 20);
n = in.read(buf, 20, buf.length - 20);
}
}
if (in.getFilePointer() <= in.length()) {
if (pixelOffsets.size() > pixelLengths.size()) {
long length = in.getFilePointer() - fp;
if (((length / 2) % 2) == 1) {
pixelOffsets.setElementAt(fp + 2, pixelOffsets.size() - 1);
length -= 2;
}
if (length >= 1024) {
pixelLengths.add(new Long(length));
}
else pixelOffsets.remove(pixelOffsets.size() - 1);
}
}
else pixelOffsets.remove(pixelOffsets.size() - 1);
}
catch (EOFException e) {
pixelOffsets.remove(pixelOffsets.size() - 1);
}
}
}
}
Vector<Long> orderedSeries = new Vector<Long>();
Hashtable<Long, Vector<Integer>> uniqueSeries =
new Hashtable<Long, Vector<Integer>>();
for (int i=0; i<pixelOffsets.size(); i++) {
long length = pixelLengths.get(i).longValue();
long offset = pixelOffsets.get(i).longValue();
int padding = isSpool ? 0 : 7;
if (length + offset + padding > in.length()) {
pixelOffsets.remove(i);
pixelLengths.remove(i);
i--;
}
else {
Vector<Integer> v = uniqueSeries.get(length);
if (v == null) {
orderedSeries.add(length);
v = new Vector<Integer>();
}
v.add(i);
uniqueSeries.put(length, v);
}
}
if (pixelOffsets.size() > 1) {
boolean little = isLittleEndian();
core = new CoreMetadata[uniqueSeries.size()];
for (int i=0; i<getSeriesCount(); i++) {
core[i] = new CoreMetadata();
core[i].littleEndian = little;
}
}
LOGGER.info("Determining dimensions");
// determine total number of pixel bytes
Vector<Float> pixelSize = new Vector<Float>();
String objective = null;
Vector<Double> pixelSizeZ = new Vector<Double>();
long pixelBytes = 0;
for (int i=0; i<pixelLengths.size(); i++) {
pixelBytes += pixelLengths.get(i).longValue();
}
String[] imageNames = new String[getSeriesCount()];
Vector<String> channelNames = new Vector<String>();
int nextName = 0;
int[] sizeX = new int[pixelOffsets.size()];
int[] sizeY = new int[pixelOffsets.size()];
int[] sizeZ = new int[pixelOffsets.size()];
int[] sizeC = new int[pixelOffsets.size()];
// try to find the width and height
int iCount = 0;
int hCount = 0;
int uCount = 0;
int prevSeries = -1;
int prevSeriesU = -1;
int nextChannel = 0;
for (int i=0; i<metadataOffsets.size(); i++) {
long off = metadataOffsets.get(i).longValue();
in.seek(off);
long next = i == metadataOffsets.size() - 1 ? in.length() :
metadataOffsets.get(i + 1).longValue();
int totalBlocks = (int) ((next - off) / 128);
// if there are more than 100 blocks, we probably found a pixel block
// by accident (but we'll check the first block anyway)
//if (totalBlocks > 100) totalBlocks = 100;
for (int q=0; q<totalBlocks; q++) {
if (withinPixels(off + q * 128)) {
continue;
}
in.seek(off + q * 128);
char n = (char) in.readShort();
while (n == 0 && in.getFilePointer() < off + (q + 1) * 128) {
n = (char) in.readShort();
}
if (in.getFilePointer() >= in.length() - 2) break;
if (n == 'i') {
iCount++;
in.skipBytes(94);
pixelSizeZ.add(new Double(in.readFloat()));
in.seek(in.getFilePointer() - 20);
for (int j=0; j<pixelOffsets.size(); j++) {
long end = j == pixelOffsets.size() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
if (sizeX[j] == 0) {
sizeX[j] = in.readShort();
sizeY[j] = in.readShort();
/* debug */ System.out.println("@440, X = " + sizeX[j] + ", Y = " + sizeY[j]);
int checkX = in.readShort();
int checkY = in.readShort();
int div = in.readShort();
sizeX[j] /= (div == 0 ? 1 : div);
div = in.readShort();
sizeY[j] /= (div == 0 ? 1 : div);
/* debug */ System.out.println("@447, X = " + sizeX[j] + ", Y = " + sizeY[j]);
}
if (prevSeries != j) {
iCount = 1;
}
prevSeries = j;
sizeC[j] = iCount;
break;
}
}
}
else if (n == 'u') {
uCount++;
for (int j=0; j<getSeriesCount(); j++) {
long end = j == getSeriesCount() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
if (prevSeriesU != j) {
uCount = 1;
}
prevSeriesU = j;
sizeZ[j] = uCount;
break;
}
}
}
else if (n == 'h') hCount++;
else if (n == 'j') {
in.skipBytes(2);
String check = in.readString(2);
if (check.equals("II") || check.equals("MM")) {
long pointer = in.getFilePointer();
// this block should contain an image name
in.skipBytes(10);
if (nextName < imageNames.length) {
imageNames[nextName++] = in.readCString().trim();
}
long fp = in.getFilePointer();
if ((in.getFilePointer() % 2) == 1) in.skipBytes(1);
while (in.readShort() == 0);
in.skipBytes(18);
if (in.getFilePointer() - fp > 123 && (fp % 2) == 0) {
in.seek(fp + 123);
}
int x = in.readInt();
int y = in.readInt();
int div = in.readShort();
x /= (div == 0 ? 1 : div);
div = in.readShort();
y /= (div == 0 ? 1 : div);
if (x > 16 && (x < sizeX[nextName - 1] ||
sizeX[nextName - 1] == 0) && y > 16 &&
(y < sizeY[nextName - 1] || sizeY[nextName - 1] == 0))
{
sizeX[nextName - 1] = x;
sizeY[nextName - 1] = y;
/* debug */ System.out.println("@505, X = " + sizeX[nextName - 1] + ", Y = " + sizeY[nextName - 1]);
adjust = false;
}
in.seek(pointer + 214);
int validBits = in.readShort();
if (core[nextName - 1].bitsPerPixel == 0 && validBits <= 16) {
core[nextName - 1].bitsPerPixel = validBits;
}
}
}
else if (n == 'm') {
// this block should contain a channel name
if (in.getFilePointer() > pixelOffsets.get(0).longValue()) {
in.skipBytes(14);
channelNames.add(in.readCString().trim());
}
}
else if (n == 'd') {
// objective info and pixel size X/Y
in.skipBytes(6);
long fp = in.getFilePointer();
objective = in.readCString();
in.seek(fp + 144);
pixelSize.add(in.readFloat());
}
else if (n == 'e') {
in.skipBytes(174);
ndFilters.add(new Double(in.readFloat()));
in.skipBytes(40);
if (nextName < getSeriesCount()) {
setSeries(nextName);
addSeriesMeta("channel " + ndFilters.size() + " intensification",
in.readShort());
}
}
else if (n == 'k') {
in.skipBytes(14);
if (nextName > 0) setSeries(nextName - 1);
addSeriesMeta("Mag. changer", in.readCString());
}
else if (isSpool) {
// spool files don't necessarily have block identifiers
for (int j=0; j<pixelOffsets.size(); j++) {
long end = j == pixelOffsets.size() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
in.skipBytes(16);
int x = in.readShort();
int y = in.readShort();
- if (x != 0) sizeX[j] = x;
- if (y != 0) sizeY[j] = y;
+ if (x > 16 && y > 16) {
+ sizeX[j] = x;
+ sizeY[j] = y;
+ }
/* debug */ System.out.println("@555, X = " + sizeX[j] + ", Y = " + sizeY[j]);
adjust = false;
break;
}
}
}
}
}
planeOffset = new long[getSeriesCount()][];
for (int i=0; i<getSeriesCount(); i++) {
+ /* debug */ System.out.println("*** SERIES #" + i + " ***");
setSeries(i);
Vector<Integer> pixelIndexes = uniqueSeries.get(orderedSeries.get(i));
int index = pixelIndexes.get(0);
long pixels = pixelLengths.get(index).longValue() / 2;
boolean x = true;
/* debug */ System.out.println("pixels = " + pixels);
core[i].sizeX = sizeX[index];
core[i].sizeY = sizeY[index];
core[i].sizeC = sizeC[index];
core[i].sizeZ = sizeZ[index];
if (getSizeC() == 0) core[i].sizeC = 1;
if (getSizeZ() == 0) core[i].sizeZ = 1;
/* debug */
System.out.println("Z = " + getSizeZ());
System.out.println("C = " + getSizeC());
/* end debug */
long plane = pixels / (getSizeC() * getSizeZ());
if (getSizeX() * getSizeY() == pixels) {
core[i].sizeC = 1;
core[i].sizeZ = 1;
}
else if (getSizeX() * getSizeY() * getSizeZ() == pixels) {
core[i].sizeC = 1;
core[i].sizeZ = (int) (pixels / (getSizeX() * getSizeY()));
}
else if (getSizeX() * getSizeY() * getSizeC() == pixels) {
core[i].sizeC = (int) (pixels / (getSizeX() * getSizeY()));
core[i].sizeZ = 1;
}
else {
long p = pixels / (getSizeX() * getSizeY());
if (p * getSizeX() * getSizeY() == pixels &&
p != getSizeC() * getSizeZ())
{
core[i].sizeC = 1;
core[i].sizeZ = (int) p;
}
}
plane = pixels / (getSizeC() * getSizeZ());
/* debug */
System.out.println("plane = " + plane);
System.out.println("check = " + (getSizeX() * getSizeY()));
System.out.println("adjust = " + adjust);
System.out.println("sizeX = " + core[i].sizeX);
System.out.println("sizeY = " + core[i].sizeY);
/* end debug */
if (adjust) {
boolean widthGreater = getSizeX() > getSizeY();
while (getSizeX() * getSizeY() > plane) {
if (x) core[i].sizeX /= 2;
else core[i].sizeY /= 2;
x = !x;
}
while (getSizeX() * getSizeY() < plane ||
(getSizeX() < getSizeY() && widthGreater))
{
core[i].sizeX++;
core[i].sizeY = (int) (plane / getSizeX());
}
}
if ((long) getSizeX() * getSizeY() > plane) {
core[i].sizeX = (int) Math.sqrt(plane);
core[i].sizeY = getSizeX();
}
int nPlanes = getSizeZ() * getSizeC();
core[i].sizeT = (int) (pixels / (getSizeX() * getSizeY() * nPlanes));
while (getSizeX() * getSizeY() * nPlanes * getSizeT() > pixels) {
core[i].sizeT--;
}
if (getSizeT() == 0) core[i].sizeT = 1;
int nBlocks = uniqueSeries.get(orderedSeries.get(i)).size();
core[i].sizeT *= nBlocks;
core[i].imageCount = nPlanes * getSizeT();
core[i].pixelType = FormatTools.UINT16;
core[i].dimensionOrder = nBlocks > 1 ? "XYZCT" : "XYZTC";
core[i].indexed = false;
core[i].falseColor = false;
core[i].metadataComplete = true;
planeOffset[i] = new long[getImageCount()];
int nextImage = 0;
for (Integer pixelIndex : pixelIndexes) {
long offset = pixelOffsets.get(pixelIndex);
long length = pixelLengths.get(pixelIndex);
int planeSize = getSizeX() * getSizeY() * 2;
int planes = (int) (length / planeSize);
for (int p=0; p<planes; p++, nextImage++) {
if (nextImage < planeOffset[i].length) {
planeOffset[i][nextImage] = offset + p * planeSize;
}
}
}
}
setSeries(0);
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
// populate Image data
for (int i=0; i<getSeriesCount(); i++) {
if (imageNames[i] != null) store.setImageName(imageNames[i], i);
MetadataTools.setDefaultCreationDate(store, id, i);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// link Instrument and Image
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
store.setImageInstrumentRef(instrumentID, 0);
int index = 0;
// populate Objective data
store.setObjectiveModel(objective, 0, 0);
store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
// link Objective to Image
String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
store.setObjectiveID(objectiveID, 0, 0);
store.setImageObjectiveSettingsID(objectiveID, 0);
// populate Dimensions data
for (int i=0; i<getSeriesCount(); i++) {
if (i < pixelSize.size()) {
store.setPixelsPhysicalSizeX(new Double(pixelSize.get(i)), i);
store.setPixelsPhysicalSizeY(new Double(pixelSize.get(i)), i);
}
int idx = 0;
for (int q=0; q<i; q++) {
idx += core[q].sizeC;
}
if (idx < pixelSizeZ.size() && pixelSizeZ.get(idx) != null) {
store.setPixelsPhysicalSizeZ(pixelSizeZ.get(idx), i);
}
}
// populate LogicalChannel data
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
for (int c=0; c<getSizeC(); c++) {
if (index < channelNames.size() && channelNames.get(index) != null) {
store.setChannelName(channelNames.get(index), i, c);
addSeriesMeta("channel " + c, channelNames.get(index));
}
if (index < ndFilters.size() && ndFilters.get(index) != null) {
store.setChannelNDFilter(ndFilters.get(index), i, c);
addSeriesMeta("channel " + c + " Neutral density",
ndFilters.get(index));
}
index++;
}
}
setSeries(0);
}
}
// -- Helper methods --
private boolean withinPixels(long offset) {
for (int i=0; i<pixelOffsets.size(); i++) {
long pixelOffset = pixelOffsets.get(i).longValue();
long pixelLength = pixelLengths.get(i).longValue();
if (offset >= pixelOffset && offset < (pixelOffset + pixelLength)) {
return true;
}
}
return false;
}
}
| false | true | protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
isSpool = checkSuffix(id, "spl");
if (isSpool) {
metadataInPlanes = new Hashtable<Integer, Integer>();
}
LOGGER.info("Finding offsets to pixel data");
// Slidebook files appear to be comprised of four types of blocks:
// variable length pixel data blocks, 512 byte metadata blocks,
// 128 byte metadata blocks, and variable length metadata blocks.
//
// Fixed-length metadata blocks begin with a 2 byte identifier,
// e.g. 'i' or 'h'.
// Following this are two unknown bytes (usually 256), then a 2 byte
// endianness identifier - II or MM, for little or big endian, respectively.
// Presumably these blocks contain useful information, but for the most
// part we aren't sure what it is or how to extract it.
//
// Variable length metadata blocks begin with 0xffff and are
// (as far as I know) always between two fixed-length metadata blocks.
// These appear to be a relatively new addition to the format - they are
// only present in files received on/after March 30, 2008.
//
// Each pixel data block corresponds to one series.
// The first 'i' metadata block after each pixel data block contains
// the width and height of the planes in that block - this can (and does)
// vary between blocks.
//
// Z, C, and T sizes are computed heuristically based on the number of
// metadata blocks of a specific type.
in.skipBytes(4);
core[0].littleEndian = in.read() == 0x49;
in.order(isLittleEndian());
metadataOffsets = new Vector<Long>();
pixelOffsets = new Vector<Long>();
pixelLengths = new Vector<Long>();
ndFilters = new Vector<Double>();
in.seek(0);
// gather offsets to metadata and pixel data blocks
while (in.getFilePointer() < in.length() - 8) {
LOGGER.debug("Looking for block at {}", in.getFilePointer());
in.skipBytes(4);
int checkOne = in.read();
int checkTwo = in.read();
if ((checkOne == 'I' && checkTwo == 'I') ||
(checkOne == 'M' && checkTwo == 'M'))
{
LOGGER.debug("Found metadata offset: {}", (in.getFilePointer() - 6));
metadataOffsets.add(new Long(in.getFilePointer() - 6));
in.skipBytes(in.readShort() - 8);
}
else if (checkOne == -1 && checkTwo == -1) {
boolean foundBlock = false;
byte[] block = new byte[8192];
in.read(block);
while (!foundBlock) {
for (int i=0; i<block.length-2; i++) {
if ((block[i] == 'M' && block[i + 1] == 'M') ||
(block[i] == 'I' && block[i + 1] == 'I'))
{
foundBlock = true;
in.seek(in.getFilePointer() - block.length + i - 2);
LOGGER.debug("Found metadata offset: {}",
(in.getFilePointer() - 2));
metadataOffsets.add(new Long(in.getFilePointer() - 2));
in.skipBytes(in.readShort() - 5);
break;
}
}
if (!foundBlock) {
block[0] = block[block.length - 2];
block[1] = block[block.length - 1];
in.read(block, 2, block.length - 2);
}
}
}
else {
String s = null;
long fp = in.getFilePointer() - 6;
in.seek(fp);
int len = in.read();
if (len > 0 && len <= 32) {
s = in.readString(len);
}
if (s != null && s.indexOf("Annotation") != -1) {
if (s.equals("CTimelapseAnnotation")) {
in.skipBytes(41);
if (in.read() == 0) in.skipBytes(10);
else in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CIntensityBarAnnotation")) {
in.skipBytes(56);
int n = in.read();
while (n == 0 || n < 6 || n > 0x80) n = in.read();
in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CCubeAnnotation")) {
in.skipBytes(66);
int n = in.read();
if (n != 0) in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CScaleBarAnnotation")) {
in.skipBytes(38);
int extra = in.read();
if (extra <= 16) in.skipBytes(3 + extra);
else in.skipBytes(2);
}
}
else if (s != null && s.indexOf("Decon") != -1) {
in.seek(fp);
while (in.read() != ']');
}
else {
if ((fp % 2) == 1) fp -= 2;
in.seek(fp);
// make sure there isn't another block nearby
String checkString = in.readString(64);
if (checkString.indexOf("II") != -1 ||
checkString.indexOf("MM") != -1)
{
int index = checkString.indexOf("II");
if (index == -1) index = checkString.indexOf("MM");
in.seek(fp + index - 4);
continue;
}
else in.seek(fp);
LOGGER.debug("Found pixel offset at {}", fp);
pixelOffsets.add(new Long(fp));
try {
byte[] buf = new byte[8192];
boolean found = false;
int n = in.read(buf);
while (!found && in.getFilePointer() < in.length()) {
for (int i=0; i<n-6; i++) {
if ((buf[i + 4] == 'I' && buf[i + 5] == 'I') ||
(buf[i + 4] == 'M' && buf[i + 5] == 'M'))
{
if (((buf[i] == 'h' || buf[i] == 'i') && buf[i + 1] == 0) ||
(buf[i] == 0 && (buf[i + 1] == 'h' || buf[i + 1] == 'i')))
{
found = true;
in.seek(in.getFilePointer() - n + i - 20);
if (buf[i] == 'i' || buf[i + 1] == 'i') {
pixelOffsets.remove(pixelOffsets.size() - 1);
}
break;
}
else if (((buf[i] == 'j' || buf[i] == 'k' || buf[i] == 'n') &&
buf[i + 1] == 0) || (buf[i] == 0 && (buf[i + 1] == 'j' ||
buf[i + 1] == 'k' || buf[i + 1] == 'n')))
{
found = true;
pixelOffsets.remove(pixelOffsets.size() - 1);
break;
}
}
}
if (!found) {
byte[] tmp = buf;
buf = new byte[8192];
System.arraycopy(tmp, tmp.length - 20, buf, 0, 20);
n = in.read(buf, 20, buf.length - 20);
}
}
if (in.getFilePointer() <= in.length()) {
if (pixelOffsets.size() > pixelLengths.size()) {
long length = in.getFilePointer() - fp;
if (((length / 2) % 2) == 1) {
pixelOffsets.setElementAt(fp + 2, pixelOffsets.size() - 1);
length -= 2;
}
if (length >= 1024) {
pixelLengths.add(new Long(length));
}
else pixelOffsets.remove(pixelOffsets.size() - 1);
}
}
else pixelOffsets.remove(pixelOffsets.size() - 1);
}
catch (EOFException e) {
pixelOffsets.remove(pixelOffsets.size() - 1);
}
}
}
}
Vector<Long> orderedSeries = new Vector<Long>();
Hashtable<Long, Vector<Integer>> uniqueSeries =
new Hashtable<Long, Vector<Integer>>();
for (int i=0; i<pixelOffsets.size(); i++) {
long length = pixelLengths.get(i).longValue();
long offset = pixelOffsets.get(i).longValue();
int padding = isSpool ? 0 : 7;
if (length + offset + padding > in.length()) {
pixelOffsets.remove(i);
pixelLengths.remove(i);
i--;
}
else {
Vector<Integer> v = uniqueSeries.get(length);
if (v == null) {
orderedSeries.add(length);
v = new Vector<Integer>();
}
v.add(i);
uniqueSeries.put(length, v);
}
}
if (pixelOffsets.size() > 1) {
boolean little = isLittleEndian();
core = new CoreMetadata[uniqueSeries.size()];
for (int i=0; i<getSeriesCount(); i++) {
core[i] = new CoreMetadata();
core[i].littleEndian = little;
}
}
LOGGER.info("Determining dimensions");
// determine total number of pixel bytes
Vector<Float> pixelSize = new Vector<Float>();
String objective = null;
Vector<Double> pixelSizeZ = new Vector<Double>();
long pixelBytes = 0;
for (int i=0; i<pixelLengths.size(); i++) {
pixelBytes += pixelLengths.get(i).longValue();
}
String[] imageNames = new String[getSeriesCount()];
Vector<String> channelNames = new Vector<String>();
int nextName = 0;
int[] sizeX = new int[pixelOffsets.size()];
int[] sizeY = new int[pixelOffsets.size()];
int[] sizeZ = new int[pixelOffsets.size()];
int[] sizeC = new int[pixelOffsets.size()];
// try to find the width and height
int iCount = 0;
int hCount = 0;
int uCount = 0;
int prevSeries = -1;
int prevSeriesU = -1;
int nextChannel = 0;
for (int i=0; i<metadataOffsets.size(); i++) {
long off = metadataOffsets.get(i).longValue();
in.seek(off);
long next = i == metadataOffsets.size() - 1 ? in.length() :
metadataOffsets.get(i + 1).longValue();
int totalBlocks = (int) ((next - off) / 128);
// if there are more than 100 blocks, we probably found a pixel block
// by accident (but we'll check the first block anyway)
//if (totalBlocks > 100) totalBlocks = 100;
for (int q=0; q<totalBlocks; q++) {
if (withinPixels(off + q * 128)) {
continue;
}
in.seek(off + q * 128);
char n = (char) in.readShort();
while (n == 0 && in.getFilePointer() < off + (q + 1) * 128) {
n = (char) in.readShort();
}
if (in.getFilePointer() >= in.length() - 2) break;
if (n == 'i') {
iCount++;
in.skipBytes(94);
pixelSizeZ.add(new Double(in.readFloat()));
in.seek(in.getFilePointer() - 20);
for (int j=0; j<pixelOffsets.size(); j++) {
long end = j == pixelOffsets.size() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
if (sizeX[j] == 0) {
sizeX[j] = in.readShort();
sizeY[j] = in.readShort();
/* debug */ System.out.println("@440, X = " + sizeX[j] + ", Y = " + sizeY[j]);
int checkX = in.readShort();
int checkY = in.readShort();
int div = in.readShort();
sizeX[j] /= (div == 0 ? 1 : div);
div = in.readShort();
sizeY[j] /= (div == 0 ? 1 : div);
/* debug */ System.out.println("@447, X = " + sizeX[j] + ", Y = " + sizeY[j]);
}
if (prevSeries != j) {
iCount = 1;
}
prevSeries = j;
sizeC[j] = iCount;
break;
}
}
}
else if (n == 'u') {
uCount++;
for (int j=0; j<getSeriesCount(); j++) {
long end = j == getSeriesCount() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
if (prevSeriesU != j) {
uCount = 1;
}
prevSeriesU = j;
sizeZ[j] = uCount;
break;
}
}
}
else if (n == 'h') hCount++;
else if (n == 'j') {
in.skipBytes(2);
String check = in.readString(2);
if (check.equals("II") || check.equals("MM")) {
long pointer = in.getFilePointer();
// this block should contain an image name
in.skipBytes(10);
if (nextName < imageNames.length) {
imageNames[nextName++] = in.readCString().trim();
}
long fp = in.getFilePointer();
if ((in.getFilePointer() % 2) == 1) in.skipBytes(1);
while (in.readShort() == 0);
in.skipBytes(18);
if (in.getFilePointer() - fp > 123 && (fp % 2) == 0) {
in.seek(fp + 123);
}
int x = in.readInt();
int y = in.readInt();
int div = in.readShort();
x /= (div == 0 ? 1 : div);
div = in.readShort();
y /= (div == 0 ? 1 : div);
if (x > 16 && (x < sizeX[nextName - 1] ||
sizeX[nextName - 1] == 0) && y > 16 &&
(y < sizeY[nextName - 1] || sizeY[nextName - 1] == 0))
{
sizeX[nextName - 1] = x;
sizeY[nextName - 1] = y;
/* debug */ System.out.println("@505, X = " + sizeX[nextName - 1] + ", Y = " + sizeY[nextName - 1]);
adjust = false;
}
in.seek(pointer + 214);
int validBits = in.readShort();
if (core[nextName - 1].bitsPerPixel == 0 && validBits <= 16) {
core[nextName - 1].bitsPerPixel = validBits;
}
}
}
else if (n == 'm') {
// this block should contain a channel name
if (in.getFilePointer() > pixelOffsets.get(0).longValue()) {
in.skipBytes(14);
channelNames.add(in.readCString().trim());
}
}
else if (n == 'd') {
// objective info and pixel size X/Y
in.skipBytes(6);
long fp = in.getFilePointer();
objective = in.readCString();
in.seek(fp + 144);
pixelSize.add(in.readFloat());
}
else if (n == 'e') {
in.skipBytes(174);
ndFilters.add(new Double(in.readFloat()));
in.skipBytes(40);
if (nextName < getSeriesCount()) {
setSeries(nextName);
addSeriesMeta("channel " + ndFilters.size() + " intensification",
in.readShort());
}
}
else if (n == 'k') {
in.skipBytes(14);
if (nextName > 0) setSeries(nextName - 1);
addSeriesMeta("Mag. changer", in.readCString());
}
else if (isSpool) {
// spool files don't necessarily have block identifiers
for (int j=0; j<pixelOffsets.size(); j++) {
long end = j == pixelOffsets.size() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
in.skipBytes(16);
int x = in.readShort();
int y = in.readShort();
if (x != 0) sizeX[j] = x;
if (y != 0) sizeY[j] = y;
/* debug */ System.out.println("@555, X = " + sizeX[j] + ", Y = " + sizeY[j]);
adjust = false;
break;
}
}
}
}
}
planeOffset = new long[getSeriesCount()][];
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
Vector<Integer> pixelIndexes = uniqueSeries.get(orderedSeries.get(i));
int index = pixelIndexes.get(0);
long pixels = pixelLengths.get(index).longValue() / 2;
boolean x = true;
/* debug */ System.out.println("pixels = " + pixels);
core[i].sizeX = sizeX[index];
core[i].sizeY = sizeY[index];
core[i].sizeC = sizeC[index];
core[i].sizeZ = sizeZ[index];
if (getSizeC() == 0) core[i].sizeC = 1;
if (getSizeZ() == 0) core[i].sizeZ = 1;
/* debug */
System.out.println("Z = " + getSizeZ());
System.out.println("C = " + getSizeC());
/* end debug */
long plane = pixels / (getSizeC() * getSizeZ());
if (getSizeX() * getSizeY() == pixels) {
core[i].sizeC = 1;
core[i].sizeZ = 1;
}
else if (getSizeX() * getSizeY() * getSizeZ() == pixels) {
core[i].sizeC = 1;
core[i].sizeZ = (int) (pixels / (getSizeX() * getSizeY()));
}
else if (getSizeX() * getSizeY() * getSizeC() == pixels) {
core[i].sizeC = (int) (pixels / (getSizeX() * getSizeY()));
core[i].sizeZ = 1;
}
else {
long p = pixels / (getSizeX() * getSizeY());
if (p * getSizeX() * getSizeY() == pixels &&
p != getSizeC() * getSizeZ())
{
core[i].sizeC = 1;
core[i].sizeZ = (int) p;
}
}
plane = pixels / (getSizeC() * getSizeZ());
/* debug */
System.out.println("plane = " + plane);
System.out.println("check = " + (getSizeX() * getSizeY()));
System.out.println("adjust = " + adjust);
System.out.println("sizeX = " + core[i].sizeX);
System.out.println("sizeY = " + core[i].sizeY);
/* end debug */
if (adjust) {
boolean widthGreater = getSizeX() > getSizeY();
while (getSizeX() * getSizeY() > plane) {
if (x) core[i].sizeX /= 2;
else core[i].sizeY /= 2;
x = !x;
}
while (getSizeX() * getSizeY() < plane ||
(getSizeX() < getSizeY() && widthGreater))
{
core[i].sizeX++;
core[i].sizeY = (int) (plane / getSizeX());
}
}
if ((long) getSizeX() * getSizeY() > plane) {
core[i].sizeX = (int) Math.sqrt(plane);
core[i].sizeY = getSizeX();
}
int nPlanes = getSizeZ() * getSizeC();
core[i].sizeT = (int) (pixels / (getSizeX() * getSizeY() * nPlanes));
while (getSizeX() * getSizeY() * nPlanes * getSizeT() > pixels) {
core[i].sizeT--;
}
if (getSizeT() == 0) core[i].sizeT = 1;
int nBlocks = uniqueSeries.get(orderedSeries.get(i)).size();
core[i].sizeT *= nBlocks;
core[i].imageCount = nPlanes * getSizeT();
core[i].pixelType = FormatTools.UINT16;
core[i].dimensionOrder = nBlocks > 1 ? "XYZCT" : "XYZTC";
core[i].indexed = false;
core[i].falseColor = false;
core[i].metadataComplete = true;
planeOffset[i] = new long[getImageCount()];
int nextImage = 0;
for (Integer pixelIndex : pixelIndexes) {
long offset = pixelOffsets.get(pixelIndex);
long length = pixelLengths.get(pixelIndex);
int planeSize = getSizeX() * getSizeY() * 2;
int planes = (int) (length / planeSize);
for (int p=0; p<planes; p++, nextImage++) {
if (nextImage < planeOffset[i].length) {
planeOffset[i][nextImage] = offset + p * planeSize;
}
}
}
}
setSeries(0);
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
// populate Image data
for (int i=0; i<getSeriesCount(); i++) {
if (imageNames[i] != null) store.setImageName(imageNames[i], i);
MetadataTools.setDefaultCreationDate(store, id, i);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// link Instrument and Image
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
store.setImageInstrumentRef(instrumentID, 0);
int index = 0;
// populate Objective data
store.setObjectiveModel(objective, 0, 0);
store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
// link Objective to Image
String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
store.setObjectiveID(objectiveID, 0, 0);
store.setImageObjectiveSettingsID(objectiveID, 0);
// populate Dimensions data
for (int i=0; i<getSeriesCount(); i++) {
if (i < pixelSize.size()) {
store.setPixelsPhysicalSizeX(new Double(pixelSize.get(i)), i);
store.setPixelsPhysicalSizeY(new Double(pixelSize.get(i)), i);
}
int idx = 0;
for (int q=0; q<i; q++) {
idx += core[q].sizeC;
}
if (idx < pixelSizeZ.size() && pixelSizeZ.get(idx) != null) {
store.setPixelsPhysicalSizeZ(pixelSizeZ.get(idx), i);
}
}
// populate LogicalChannel data
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
for (int c=0; c<getSizeC(); c++) {
if (index < channelNames.size() && channelNames.get(index) != null) {
store.setChannelName(channelNames.get(index), i, c);
addSeriesMeta("channel " + c, channelNames.get(index));
}
if (index < ndFilters.size() && ndFilters.get(index) != null) {
store.setChannelNDFilter(ndFilters.get(index), i, c);
addSeriesMeta("channel " + c + " Neutral density",
ndFilters.get(index));
}
index++;
}
}
setSeries(0);
}
}
| protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
isSpool = checkSuffix(id, "spl");
if (isSpool) {
metadataInPlanes = new Hashtable<Integer, Integer>();
}
LOGGER.info("Finding offsets to pixel data");
// Slidebook files appear to be comprised of four types of blocks:
// variable length pixel data blocks, 512 byte metadata blocks,
// 128 byte metadata blocks, and variable length metadata blocks.
//
// Fixed-length metadata blocks begin with a 2 byte identifier,
// e.g. 'i' or 'h'.
// Following this are two unknown bytes (usually 256), then a 2 byte
// endianness identifier - II or MM, for little or big endian, respectively.
// Presumably these blocks contain useful information, but for the most
// part we aren't sure what it is or how to extract it.
//
// Variable length metadata blocks begin with 0xffff and are
// (as far as I know) always between two fixed-length metadata blocks.
// These appear to be a relatively new addition to the format - they are
// only present in files received on/after March 30, 2008.
//
// Each pixel data block corresponds to one series.
// The first 'i' metadata block after each pixel data block contains
// the width and height of the planes in that block - this can (and does)
// vary between blocks.
//
// Z, C, and T sizes are computed heuristically based on the number of
// metadata blocks of a specific type.
in.skipBytes(4);
core[0].littleEndian = in.read() == 0x49;
in.order(isLittleEndian());
metadataOffsets = new Vector<Long>();
pixelOffsets = new Vector<Long>();
pixelLengths = new Vector<Long>();
ndFilters = new Vector<Double>();
in.seek(0);
// gather offsets to metadata and pixel data blocks
while (in.getFilePointer() < in.length() - 8) {
LOGGER.debug("Looking for block at {}", in.getFilePointer());
in.skipBytes(4);
int checkOne = in.read();
int checkTwo = in.read();
if ((checkOne == 'I' && checkTwo == 'I') ||
(checkOne == 'M' && checkTwo == 'M'))
{
LOGGER.debug("Found metadata offset: {}", (in.getFilePointer() - 6));
metadataOffsets.add(new Long(in.getFilePointer() - 6));
in.skipBytes(in.readShort() - 8);
}
else if (checkOne == -1 && checkTwo == -1) {
boolean foundBlock = false;
byte[] block = new byte[8192];
in.read(block);
while (!foundBlock) {
for (int i=0; i<block.length-2; i++) {
if ((block[i] == 'M' && block[i + 1] == 'M') ||
(block[i] == 'I' && block[i + 1] == 'I'))
{
foundBlock = true;
in.seek(in.getFilePointer() - block.length + i - 2);
LOGGER.debug("Found metadata offset: {}",
(in.getFilePointer() - 2));
metadataOffsets.add(new Long(in.getFilePointer() - 2));
in.skipBytes(in.readShort() - 5);
break;
}
}
if (!foundBlock) {
block[0] = block[block.length - 2];
block[1] = block[block.length - 1];
in.read(block, 2, block.length - 2);
}
}
}
else {
String s = null;
long fp = in.getFilePointer() - 6;
in.seek(fp);
int len = in.read();
if (len > 0 && len <= 32) {
s = in.readString(len);
}
if (s != null && s.indexOf("Annotation") != -1) {
if (s.equals("CTimelapseAnnotation")) {
in.skipBytes(41);
if (in.read() == 0) in.skipBytes(10);
else in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CIntensityBarAnnotation")) {
in.skipBytes(56);
int n = in.read();
while (n == 0 || n < 6 || n > 0x80) n = in.read();
in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CCubeAnnotation")) {
in.skipBytes(66);
int n = in.read();
if (n != 0) in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CScaleBarAnnotation")) {
in.skipBytes(38);
int extra = in.read();
if (extra <= 16) in.skipBytes(3 + extra);
else in.skipBytes(2);
}
}
else if (s != null && s.indexOf("Decon") != -1) {
in.seek(fp);
while (in.read() != ']');
}
else {
if ((fp % 2) == 1) fp -= 2;
in.seek(fp);
// make sure there isn't another block nearby
String checkString = in.readString(64);
if (checkString.indexOf("II") != -1 ||
checkString.indexOf("MM") != -1)
{
int index = checkString.indexOf("II");
if (index == -1) index = checkString.indexOf("MM");
in.seek(fp + index - 4);
continue;
}
else in.seek(fp);
LOGGER.debug("Found pixel offset at {}", fp);
pixelOffsets.add(new Long(fp));
try {
byte[] buf = new byte[8192];
boolean found = false;
int n = in.read(buf);
while (!found && in.getFilePointer() < in.length()) {
for (int i=0; i<n-6; i++) {
if ((buf[i + 4] == 'I' && buf[i + 5] == 'I') ||
(buf[i + 4] == 'M' && buf[i + 5] == 'M'))
{
if (((buf[i] == 'h' || buf[i] == 'i') && buf[i + 1] == 0) ||
(buf[i] == 0 && (buf[i + 1] == 'h' || buf[i + 1] == 'i')))
{
found = true;
in.seek(in.getFilePointer() - n + i - 20);
if (buf[i] == 'i' || buf[i + 1] == 'i') {
pixelOffsets.remove(pixelOffsets.size() - 1);
}
break;
}
else if (((buf[i] == 'j' || buf[i] == 'k' || buf[i] == 'n') &&
buf[i + 1] == 0) || (buf[i] == 0 && (buf[i + 1] == 'j' ||
buf[i + 1] == 'k' || buf[i + 1] == 'n')))
{
found = true;
pixelOffsets.remove(pixelOffsets.size() - 1);
break;
}
}
}
if (!found) {
byte[] tmp = buf;
buf = new byte[8192];
System.arraycopy(tmp, tmp.length - 20, buf, 0, 20);
n = in.read(buf, 20, buf.length - 20);
}
}
if (in.getFilePointer() <= in.length()) {
if (pixelOffsets.size() > pixelLengths.size()) {
long length = in.getFilePointer() - fp;
if (((length / 2) % 2) == 1) {
pixelOffsets.setElementAt(fp + 2, pixelOffsets.size() - 1);
length -= 2;
}
if (length >= 1024) {
pixelLengths.add(new Long(length));
}
else pixelOffsets.remove(pixelOffsets.size() - 1);
}
}
else pixelOffsets.remove(pixelOffsets.size() - 1);
}
catch (EOFException e) {
pixelOffsets.remove(pixelOffsets.size() - 1);
}
}
}
}
Vector<Long> orderedSeries = new Vector<Long>();
Hashtable<Long, Vector<Integer>> uniqueSeries =
new Hashtable<Long, Vector<Integer>>();
for (int i=0; i<pixelOffsets.size(); i++) {
long length = pixelLengths.get(i).longValue();
long offset = pixelOffsets.get(i).longValue();
int padding = isSpool ? 0 : 7;
if (length + offset + padding > in.length()) {
pixelOffsets.remove(i);
pixelLengths.remove(i);
i--;
}
else {
Vector<Integer> v = uniqueSeries.get(length);
if (v == null) {
orderedSeries.add(length);
v = new Vector<Integer>();
}
v.add(i);
uniqueSeries.put(length, v);
}
}
if (pixelOffsets.size() > 1) {
boolean little = isLittleEndian();
core = new CoreMetadata[uniqueSeries.size()];
for (int i=0; i<getSeriesCount(); i++) {
core[i] = new CoreMetadata();
core[i].littleEndian = little;
}
}
LOGGER.info("Determining dimensions");
// determine total number of pixel bytes
Vector<Float> pixelSize = new Vector<Float>();
String objective = null;
Vector<Double> pixelSizeZ = new Vector<Double>();
long pixelBytes = 0;
for (int i=0; i<pixelLengths.size(); i++) {
pixelBytes += pixelLengths.get(i).longValue();
}
String[] imageNames = new String[getSeriesCount()];
Vector<String> channelNames = new Vector<String>();
int nextName = 0;
int[] sizeX = new int[pixelOffsets.size()];
int[] sizeY = new int[pixelOffsets.size()];
int[] sizeZ = new int[pixelOffsets.size()];
int[] sizeC = new int[pixelOffsets.size()];
// try to find the width and height
int iCount = 0;
int hCount = 0;
int uCount = 0;
int prevSeries = -1;
int prevSeriesU = -1;
int nextChannel = 0;
for (int i=0; i<metadataOffsets.size(); i++) {
long off = metadataOffsets.get(i).longValue();
in.seek(off);
long next = i == metadataOffsets.size() - 1 ? in.length() :
metadataOffsets.get(i + 1).longValue();
int totalBlocks = (int) ((next - off) / 128);
// if there are more than 100 blocks, we probably found a pixel block
// by accident (but we'll check the first block anyway)
//if (totalBlocks > 100) totalBlocks = 100;
for (int q=0; q<totalBlocks; q++) {
if (withinPixels(off + q * 128)) {
continue;
}
in.seek(off + q * 128);
char n = (char) in.readShort();
while (n == 0 && in.getFilePointer() < off + (q + 1) * 128) {
n = (char) in.readShort();
}
if (in.getFilePointer() >= in.length() - 2) break;
if (n == 'i') {
iCount++;
in.skipBytes(94);
pixelSizeZ.add(new Double(in.readFloat()));
in.seek(in.getFilePointer() - 20);
for (int j=0; j<pixelOffsets.size(); j++) {
long end = j == pixelOffsets.size() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
if (sizeX[j] == 0) {
sizeX[j] = in.readShort();
sizeY[j] = in.readShort();
/* debug */ System.out.println("@440, X = " + sizeX[j] + ", Y = " + sizeY[j]);
int checkX = in.readShort();
int checkY = in.readShort();
int div = in.readShort();
sizeX[j] /= (div == 0 ? 1 : div);
div = in.readShort();
sizeY[j] /= (div == 0 ? 1 : div);
/* debug */ System.out.println("@447, X = " + sizeX[j] + ", Y = " + sizeY[j]);
}
if (prevSeries != j) {
iCount = 1;
}
prevSeries = j;
sizeC[j] = iCount;
break;
}
}
}
else if (n == 'u') {
uCount++;
for (int j=0; j<getSeriesCount(); j++) {
long end = j == getSeriesCount() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
if (prevSeriesU != j) {
uCount = 1;
}
prevSeriesU = j;
sizeZ[j] = uCount;
break;
}
}
}
else if (n == 'h') hCount++;
else if (n == 'j') {
in.skipBytes(2);
String check = in.readString(2);
if (check.equals("II") || check.equals("MM")) {
long pointer = in.getFilePointer();
// this block should contain an image name
in.skipBytes(10);
if (nextName < imageNames.length) {
imageNames[nextName++] = in.readCString().trim();
}
long fp = in.getFilePointer();
if ((in.getFilePointer() % 2) == 1) in.skipBytes(1);
while (in.readShort() == 0);
in.skipBytes(18);
if (in.getFilePointer() - fp > 123 && (fp % 2) == 0) {
in.seek(fp + 123);
}
int x = in.readInt();
int y = in.readInt();
int div = in.readShort();
x /= (div == 0 ? 1 : div);
div = in.readShort();
y /= (div == 0 ? 1 : div);
if (x > 16 && (x < sizeX[nextName - 1] ||
sizeX[nextName - 1] == 0) && y > 16 &&
(y < sizeY[nextName - 1] || sizeY[nextName - 1] == 0))
{
sizeX[nextName - 1] = x;
sizeY[nextName - 1] = y;
/* debug */ System.out.println("@505, X = " + sizeX[nextName - 1] + ", Y = " + sizeY[nextName - 1]);
adjust = false;
}
in.seek(pointer + 214);
int validBits = in.readShort();
if (core[nextName - 1].bitsPerPixel == 0 && validBits <= 16) {
core[nextName - 1].bitsPerPixel = validBits;
}
}
}
else if (n == 'm') {
// this block should contain a channel name
if (in.getFilePointer() > pixelOffsets.get(0).longValue()) {
in.skipBytes(14);
channelNames.add(in.readCString().trim());
}
}
else if (n == 'd') {
// objective info and pixel size X/Y
in.skipBytes(6);
long fp = in.getFilePointer();
objective = in.readCString();
in.seek(fp + 144);
pixelSize.add(in.readFloat());
}
else if (n == 'e') {
in.skipBytes(174);
ndFilters.add(new Double(in.readFloat()));
in.skipBytes(40);
if (nextName < getSeriesCount()) {
setSeries(nextName);
addSeriesMeta("channel " + ndFilters.size() + " intensification",
in.readShort());
}
}
else if (n == 'k') {
in.skipBytes(14);
if (nextName > 0) setSeries(nextName - 1);
addSeriesMeta("Mag. changer", in.readCString());
}
else if (isSpool) {
// spool files don't necessarily have block identifiers
for (int j=0; j<pixelOffsets.size(); j++) {
long end = j == pixelOffsets.size() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
in.skipBytes(16);
int x = in.readShort();
int y = in.readShort();
if (x > 16 && y > 16) {
sizeX[j] = x;
sizeY[j] = y;
}
/* debug */ System.out.println("@555, X = " + sizeX[j] + ", Y = " + sizeY[j]);
adjust = false;
break;
}
}
}
}
}
planeOffset = new long[getSeriesCount()][];
for (int i=0; i<getSeriesCount(); i++) {
/* debug */ System.out.println("*** SERIES #" + i + " ***");
setSeries(i);
Vector<Integer> pixelIndexes = uniqueSeries.get(orderedSeries.get(i));
int index = pixelIndexes.get(0);
long pixels = pixelLengths.get(index).longValue() / 2;
boolean x = true;
/* debug */ System.out.println("pixels = " + pixels);
core[i].sizeX = sizeX[index];
core[i].sizeY = sizeY[index];
core[i].sizeC = sizeC[index];
core[i].sizeZ = sizeZ[index];
if (getSizeC() == 0) core[i].sizeC = 1;
if (getSizeZ() == 0) core[i].sizeZ = 1;
/* debug */
System.out.println("Z = " + getSizeZ());
System.out.println("C = " + getSizeC());
/* end debug */
long plane = pixels / (getSizeC() * getSizeZ());
if (getSizeX() * getSizeY() == pixels) {
core[i].sizeC = 1;
core[i].sizeZ = 1;
}
else if (getSizeX() * getSizeY() * getSizeZ() == pixels) {
core[i].sizeC = 1;
core[i].sizeZ = (int) (pixels / (getSizeX() * getSizeY()));
}
else if (getSizeX() * getSizeY() * getSizeC() == pixels) {
core[i].sizeC = (int) (pixels / (getSizeX() * getSizeY()));
core[i].sizeZ = 1;
}
else {
long p = pixels / (getSizeX() * getSizeY());
if (p * getSizeX() * getSizeY() == pixels &&
p != getSizeC() * getSizeZ())
{
core[i].sizeC = 1;
core[i].sizeZ = (int) p;
}
}
plane = pixels / (getSizeC() * getSizeZ());
/* debug */
System.out.println("plane = " + plane);
System.out.println("check = " + (getSizeX() * getSizeY()));
System.out.println("adjust = " + adjust);
System.out.println("sizeX = " + core[i].sizeX);
System.out.println("sizeY = " + core[i].sizeY);
/* end debug */
if (adjust) {
boolean widthGreater = getSizeX() > getSizeY();
while (getSizeX() * getSizeY() > plane) {
if (x) core[i].sizeX /= 2;
else core[i].sizeY /= 2;
x = !x;
}
while (getSizeX() * getSizeY() < plane ||
(getSizeX() < getSizeY() && widthGreater))
{
core[i].sizeX++;
core[i].sizeY = (int) (plane / getSizeX());
}
}
if ((long) getSizeX() * getSizeY() > plane) {
core[i].sizeX = (int) Math.sqrt(plane);
core[i].sizeY = getSizeX();
}
int nPlanes = getSizeZ() * getSizeC();
core[i].sizeT = (int) (pixels / (getSizeX() * getSizeY() * nPlanes));
while (getSizeX() * getSizeY() * nPlanes * getSizeT() > pixels) {
core[i].sizeT--;
}
if (getSizeT() == 0) core[i].sizeT = 1;
int nBlocks = uniqueSeries.get(orderedSeries.get(i)).size();
core[i].sizeT *= nBlocks;
core[i].imageCount = nPlanes * getSizeT();
core[i].pixelType = FormatTools.UINT16;
core[i].dimensionOrder = nBlocks > 1 ? "XYZCT" : "XYZTC";
core[i].indexed = false;
core[i].falseColor = false;
core[i].metadataComplete = true;
planeOffset[i] = new long[getImageCount()];
int nextImage = 0;
for (Integer pixelIndex : pixelIndexes) {
long offset = pixelOffsets.get(pixelIndex);
long length = pixelLengths.get(pixelIndex);
int planeSize = getSizeX() * getSizeY() * 2;
int planes = (int) (length / planeSize);
for (int p=0; p<planes; p++, nextImage++) {
if (nextImage < planeOffset[i].length) {
planeOffset[i][nextImage] = offset + p * planeSize;
}
}
}
}
setSeries(0);
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
// populate Image data
for (int i=0; i<getSeriesCount(); i++) {
if (imageNames[i] != null) store.setImageName(imageNames[i], i);
MetadataTools.setDefaultCreationDate(store, id, i);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// link Instrument and Image
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
store.setImageInstrumentRef(instrumentID, 0);
int index = 0;
// populate Objective data
store.setObjectiveModel(objective, 0, 0);
store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
// link Objective to Image
String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
store.setObjectiveID(objectiveID, 0, 0);
store.setImageObjectiveSettingsID(objectiveID, 0);
// populate Dimensions data
for (int i=0; i<getSeriesCount(); i++) {
if (i < pixelSize.size()) {
store.setPixelsPhysicalSizeX(new Double(pixelSize.get(i)), i);
store.setPixelsPhysicalSizeY(new Double(pixelSize.get(i)), i);
}
int idx = 0;
for (int q=0; q<i; q++) {
idx += core[q].sizeC;
}
if (idx < pixelSizeZ.size() && pixelSizeZ.get(idx) != null) {
store.setPixelsPhysicalSizeZ(pixelSizeZ.get(idx), i);
}
}
// populate LogicalChannel data
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
for (int c=0; c<getSizeC(); c++) {
if (index < channelNames.size() && channelNames.get(index) != null) {
store.setChannelName(channelNames.get(index), i, c);
addSeriesMeta("channel " + c, channelNames.get(index));
}
if (index < ndFilters.size() && ndFilters.get(index) != null) {
store.setChannelNDFilter(ndFilters.get(index), i, c);
addSeriesMeta("channel " + c + " Neutral density",
ndFilters.get(index));
}
index++;
}
}
setSeries(0);
}
}
|
diff --git a/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/site/AddSitePage.java b/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/site/AddSitePage.java
index a63ec4bb2..db384bae9 100644
--- a/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/site/AddSitePage.java
+++ b/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/site/AddSitePage.java
@@ -1,716 +1,716 @@
/*
* Dataverse Network - A web application to distribute, share and analyze quantitative data.
* Copyright (C) 2007
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses
* or write to the Free Software Foundation,Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* AddSitePage.java
*
* Created on September 19, 2006, 9:57 AM
*/
package edu.harvard.iq.dvn.core.web.site;
import edu.harvard.iq.dvn.core.admin.RoleServiceLocal;
import edu.harvard.iq.dvn.core.admin.UserServiceLocal;
import edu.harvard.iq.dvn.core.mail.MailServiceLocal;
import edu.harvard.iq.dvn.core.study.StudyFieldServiceLocal;
import edu.harvard.iq.dvn.core.vdc.VDC;
import edu.harvard.iq.dvn.core.vdc.VDCCollectionServiceLocal;
import edu.harvard.iq.dvn.core.vdc.VDCGroupServiceLocal;
import edu.harvard.iq.dvn.core.vdc.VDCNetworkServiceLocal;
import edu.harvard.iq.dvn.core.vdc.VDCServiceLocal;
import edu.harvard.iq.dvn.core.web.common.StatusMessage;
import edu.harvard.iq.dvn.core.web.common.VDCBaseBean;
import java.util.Map;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import com.icesoft.faces.component.ext.HtmlOutputText;
import com.icesoft.faces.component.ext.HtmlOutputLabel;
import com.icesoft.faces.component.ext.HtmlInputText;
import com.icesoft.faces.component.ext.HtmlCommandButton;
import com.icesoft.faces.component.ext.HtmlInputTextarea;
import edu.harvard.iq.dvn.core.admin.VDCUser;
import edu.harvard.iq.dvn.core.web.util.CharacterValidator;
import edu.harvard.iq.dvn.core.util.PropertyUtil;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
/**
* <p>Page bean that corresponds to a similarly named JSP page. This
* class contains component definitions (and initialization code) for
* all components that you have defined on this page, as well as
* lifecycle methods and event handlers where you may add behavior
* to respond to incoming events.</p>
*/
@Named("AddSitePage")
@ViewScoped
public class AddSitePage extends VDCBaseBean implements java.io.Serializable {
// </editor-fold>
private static final Logger logger = Logger.getLogger("edu.harvard.iq.dvn.core.web.site.AddSitePage");
/**
* <p>Construct a new Page bean instance.</p>
*/
public AddSitePage() {
}
@EJB
VDCServiceLocal vdcService;
@EJB
VDCGroupServiceLocal vdcGroupService;
@EJB
VDCCollectionServiceLocal vdcCollectionService;
@EJB
VDCNetworkServiceLocal vdcNetworkService;
@EJB
StudyFieldServiceLocal studyFieldService;
@EJB
UserServiceLocal userService;
@EJB
RoleServiceLocal roleService;
@EJB
MailServiceLocal mailService;
StatusMessage msg;
//private BundleReader messagebundle = new BundleReader("Bundle");
private ResourceBundle messagebundle = ResourceBundle.getBundle("Bundle");
public StatusMessage getMsg() {
return msg;
}
public void setMsg(StatusMessage msg) {
this.msg = msg;
}
// <editor-fold defaultstate="collapsed" desc="Creator-managed Component Definition">
private int __placeholder;
/**
* <p>Automatically managed component initialization. <strong>WARNING:</strong>
* This method is automatically generated, so any user-specified code inserted
* here is subject to being replaced.</p>
*/
public void init() {
super.init();
//check to see if a dataverse type is in request
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
Iterator iterator = request.getParameterMap().keySet().iterator();
while (iterator.hasNext()) {
Object key = (Object) iterator.next();
if (key instanceof String && ((String) key).indexOf("dataverseType") != -1 && !request.getParameter((String) key).equals("")) {
this.setDataverseType(request.getParameter((String) key));
}
}
}
//copied from manageclassificationsPage.java
private boolean result;
//fields from dvrecordsmanager
private ArrayList itemBeans = new ArrayList();
private static String GROUP_INDENT_STYLE_CLASS = "GROUP_INDENT_STYLE_CLASS";
private static String GROUP_ROW_STYLE_CLASS = "groupRow";
private static String CHILD_INDENT_STYLE_CLASS = "CHILD_INDENT_STYLE_CLASS";
private String CHILD_ROW_STYLE_CLASS;
private static String CONTRACT_IMAGE = "tree_nav_top_close_no_siblings.gif";
private static String EXPAND_IMAGE = "tree_nav_top_open_no_siblings.gif";
//these static variables have a dependency on the Network Stats Server e.g.
// they should be held as constants in a constants file ... TODO
private static Long SCHOLAR_ID = new Long("-1");
private static String SCHOLAR_SHORT_DESCRIPTION = new String("A short description for the research scholar group");
private static Long OTHER_ID = new Long("-2");
private static String OTHER_SHORT_DESCRIPTION = new String("A short description for the unclassified dataverses group (other).");
//Manage classification
public boolean getResult() {
return result;
}
//setters
public void setResult(boolean result) {
this.result = result;
}
public ArrayList getItemBeans() {
return itemBeans;
}
/**
* <p>Callback method that is called after the component tree has been
* restored, but before any event processing takes place. This method
* will <strong>only</strong> be called on a postback request that
* is processing a form submit. Customize this method to allocate
* resources that will be required in your event handlers.</p>
*/
public void preprocess() {
}
/**
* <p>Callback method that is called just before rendering takes place.
* This method will <strong>only</strong> be called for the page that
* will actually be rendered (and not, for example, on a page that
* handled a postback and then navigated to a different page). Customize
* this method to allocate resources that will be required for rendering
* this page.</p>
*/
public void prerender() {
}
/**
* <p>Callback method that is called after rendering is completed for
* this request, if <code>init()</code> was called (regardless of whether
* or not this was the page that was actually rendered). Customize this
* method to release resources acquired in the <code>init()</code>,
* <code>preprocess()</code>, or <code>prerender()</code> methods (or
* acquired during execution of an event handler).</p>
*/
public void destroy() {
}
private HtmlOutputLabel componentLabel1 = new HtmlOutputLabel();
public HtmlOutputLabel getComponentLabel1() {
return componentLabel1;
}
public void setComponentLabel1(HtmlOutputLabel hol) {
this.componentLabel1 = hol;
}
private HtmlOutputText componentLabel1Text = new HtmlOutputText();
public HtmlOutputText getComponentLabel1Text() {
return componentLabel1Text;
}
public void setComponentLabel1Text(HtmlOutputText hot) {
this.componentLabel1Text = hot;
}
private HtmlInputText dataverseName = new HtmlInputText();
public HtmlInputText getDataverseName() {
return dataverseName;
}
public void setDataverseName(HtmlInputText hit) {
this.dataverseName = hit;
}
private HtmlOutputLabel componentLabel2 = new HtmlOutputLabel();
public HtmlOutputLabel getComponentLabel2() {
return componentLabel2;
}
public void setComponentLabel2(HtmlOutputLabel hol) {
this.componentLabel2 = hol;
}
private HtmlOutputText componentLabel2Text = new HtmlOutputText();
public HtmlOutputText getComponentLabel2Text() {
return componentLabel2Text;
}
public void setComponentLabel2Text(HtmlOutputText hot) {
this.componentLabel2Text = hot;
}
private HtmlInputText dataverseAlias = new HtmlInputText();
public HtmlInputText getDataverseAlias() {
return dataverseAlias;
}
public void setDataverseAlias(HtmlInputText hit) {
this.dataverseAlias = hit;
}
private HtmlCommandButton button1 = new HtmlCommandButton();
public HtmlCommandButton getButton1() {
return button1;
}
public void setButton1(HtmlCommandButton hcb) {
this.button1 = hcb;
}
private HtmlCommandButton button2 = new HtmlCommandButton();
public HtmlCommandButton getButton2() {
return button2;
}
public void setButton2(HtmlCommandButton hcb) {
this.button2 = hcb;
}
// I'm initializing classificationList below in order to get the page
// to work; otherwise (if it's set to null), the page dies quietly in
// classificationList.getClassificationUIs() (in saveClassifications),
// after creating the new DV.
// I'm still not quite sure how/where this list was initialized before?
ClassificationList classificationList = new ClassificationList();//null;
public ClassificationList getClassificationList() {
return classificationList;
}
public void setClassificationList(ClassificationList classificationList) {
this.classificationList = classificationList;
}
public String create() {
// Long selectedgroup = this.getSelectedGroup();
String dtype = dataverseType;
String name = (String) dataverseName.getValue();
String alias = (String) dataverseAlias.getValue();
String strAffiliation = (String) affiliation.getValue();
String strShortDescription = (String) shortDescription.getValue();
Long userId = getVDCSessionBean().getLoginBean().getUser().getId();
boolean success = true;
if (validateClassificationCheckBoxes()) {
vdcService.create(userId, name, alias, dtype);
VDC createdVDC = vdcService.findByAlias(alias);
saveClassifications(createdVDC);
createdVDC.setDtype(dataverseType);
createdVDC.setDisplayNetworkAnnouncements(getVDCRequestBean().getVdcNetwork().isDisplayAnnouncements());
createdVDC.setDisplayAnnouncements(getVDCRequestBean().getVdcNetwork().isDisplayVDCAnnouncements());
createdVDC.setAnnouncements(getVDCRequestBean().getVdcNetwork().getDefaultVDCAnnouncements());
createdVDC.setDisplayNewStudies(getVDCRequestBean().getVdcNetwork().isDisplayVDCRecentStudies());
createdVDC.setAboutThisDataverse(getVDCRequestBean().getVdcNetwork().getDefaultVDCAboutText());
createdVDC.setContactEmail(getVDCSessionBean().getLoginBean().getUser().getEmail());
createdVDC.setAffiliation(strAffiliation);
createdVDC.setDvnDescription(strShortDescription);
vdcService.edit(createdVDC);
StatusMessage msg = new StatusMessage();
String hostUrl = PropertyUtil.getHostUrl();
- msg.setMessageText("Your new dataverse <a href='http://" + hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL()+ "'>http://" + hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL()+ "</a> has been successfully created!");
+ msg.setMessageText("Your new dataverse <a href='http://" + hostUrl + "/dvn/dv/" + createdVDC.getAlias() + "'>http://" + hostUrl + "/dvn/dv/" + createdVDC.getAlias() + "</a> has been successfully created!");
msg.setStyleClass("successMessage");
Map m = getRequestMap();
m.put("statusMessage", msg);
VDCUser creator = userService.findByUserName(getVDCSessionBean().getLoginBean().getUser().getUserName());
String toMailAddress = getVDCSessionBean().getLoginBean().getUser().getEmail();
String siteAddress = "unknown";
siteAddress = hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL();
logger.fine("created dataverse; site address: "+siteAddress);
mailService.sendAddSiteNotification(toMailAddress, name, siteAddress);
// Refresh User object in LoginBean so it contains the user's new role of VDC administrator.
getVDCSessionBean().getLoginBean().setUser(creator);
- return "/site/AddSiteSuccess?faces-redirect=true&vdcId=" + createdVDC.getId();
+ return "/site/AddSiteSuccessPage?faces-redirect=true&vdcId=" + createdVDC.getId();
}
else {
success = false;
return null;
}
}
private void saveClassifications(VDC createdVDC) {
for (ClassificationUI classUI: classificationList.getClassificationUIs()) {
if (classUI.isSelected()) {
createdVDC.getVdcGroups().add(classUI.getVdcGroup());
}
}
}
public String createScholarDataverse() {
String dataversetype = dataverseType;
String name = (String) dataverseName.getValue();
String alias = (String) dataverseAlias.getValue();
String strAffiliation = (String) affiliation.getValue();
String strShortDescription = (String) shortDescription.getValue();
Long userId = getVDCSessionBean().getLoginBean().getUser().getId();
if (validateClassificationCheckBoxes()) {
vdcService.createScholarDataverse(userId, firstName, lastName, name, strAffiliation, alias, dataversetype);
VDC createdScholarDataverse = vdcService.findScholarDataverseByAlias(alias);
saveClassifications(createdScholarDataverse);
// add default values to the VDC table and commit/set the vdc bean props
createdScholarDataverse.setDisplayNetworkAnnouncements(getVDCRequestBean().getVdcNetwork().isDisplayAnnouncements());
createdScholarDataverse.setDisplayAnnouncements(getVDCRequestBean().getVdcNetwork().isDisplayVDCAnnouncements());
createdScholarDataverse.setAnnouncements(getVDCRequestBean().getVdcNetwork().getDefaultVDCAnnouncements());
createdScholarDataverse.setDisplayNewStudies(getVDCRequestBean().getVdcNetwork().isDisplayVDCRecentStudies());
createdScholarDataverse.setAboutThisDataverse(getVDCRequestBean().getVdcNetwork().getDefaultVDCAboutText());
createdScholarDataverse.setContactEmail(getVDCSessionBean().getLoginBean().getUser().getEmail());
createdScholarDataverse.setDvnDescription(strShortDescription);
vdcService.edit(createdScholarDataverse);
getVDCRequestBean().setCurrentVDC(createdScholarDataverse);
// Refresh User object in LoginBean so it contains the user's new role of VDC administrator.
StatusMessage msg = new StatusMessage();
String hostUrl = PropertyUtil.getHostUrl();
msg.setMessageText("Your new scholar dataverse <a href='http://" + hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL()+ "'>http://" + hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL()+ "</a> has been successfully created!");
msg.setStyleClass("successMessage");
Map m = getRequestMap();
m.put("statusMessage", msg);
VDCUser creator = userService.findByUserName(getVDCSessionBean().getLoginBean().getUser().getUserName());
String toMailAddress = getVDCSessionBean().getLoginBean().getUser().getEmail();
String siteAddress = "unknown";
siteAddress = hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL();
mailService.sendAddSiteNotification(toMailAddress, name, siteAddress);
getVDCSessionBean().getLoginBean().setUser(creator);
return "addSiteSuccess";
}
else {
return null;
}
}
public String cancel() {
return "cancel";
}
public boolean validateClassificationCheckBoxes() {
if (!getVDCRequestBean().getVdcNetwork().isRequireDVclassification()){
return true;
}
else {
for (ClassificationUI classUI: classificationList.getClassificationUIs()) {
if (classUI.isSelected()) {
return true;
}
}
FacesMessage message = new FacesMessage("You must select at least one classification for your dataverse.");
FacesContext.getCurrentInstance().addMessage("addsiteform", message);
return false;
}
}
public void validateShortDescription(FacesContext context,
UIComponent toValidate,
Object value) {
String newValue = (String)value;
if (newValue != null && newValue.trim().length() > 0) {
if (newValue.length() > 255) {
((UIInput)toValidate).setValid(false);
FacesMessage message = new FacesMessage("The field cannot be more than 255 characters in length.");
context.addMessage(toValidate.getClientId(context), message);
}
}
if ((newValue == null || newValue.trim().length() == 0) && getVDCRequestBean().getVdcNetwork().isRequireDVdescription()) {
FacesMessage message = new FacesMessage("The field must have a value.");
context.addMessage(toValidate.getClientId(context), message);
((UIInput) toValidate).setValid(false);
context.renderResponse();
}
}
public void validateName(FacesContext context,
UIComponent toValidate,
Object value) {
String name = (String) value;
if (name != null && name.trim().length() == 0) {
FacesMessage message = new FacesMessage("The dataverse name field must have a value.");
context.addMessage(toValidate.getClientId(context), message);
context.renderResponse();
}
boolean nameFound = false;
VDC vdc = vdcService.findByName(name);
if (vdc != null) {
nameFound = true;
}
if (nameFound) {
((UIInput) toValidate).setValid(false);
FacesMessage message = new FacesMessage("This name is already taken.");
context.addMessage(toValidate.getClientId(context), message);
}
resetScholarProperties();
}
public void validateAlias(FacesContext context,
UIComponent toValidate,
Object value) {
CharacterValidator charactervalidator = new CharacterValidator();
charactervalidator.validate(context, toValidate, value);
String alias = (String) value;
boolean isValid = false;
VDC vdc = vdcService.findByAlias(alias);
if (alias.equals("") || vdc != null) {
isValid = true;
}
if (isValid) {
((UIInput) toValidate).setValid(false);
FacesMessage message = new FacesMessage("This alias is already taken.");
context.addMessage(toValidate.getClientId(context), message);
}
resetScholarProperties();
}
private void resetScholarProperties() {
if (dataverseType != null) {
this.setDataverseType(dataverseType);
}
}
/**
* Changes for build 16
* to support scholar
* dataverses and display
*
* @author wbossons
*/
/**
* Used to set the discriminator value
* in the entity
*
*/
private String dataverseType = null;
public String getDataverseType() {
if (dataverseType == null) {
setDataverseType("Basic");
}
return dataverseType;
}
public void setDataverseType(String dataverseType) {
this.dataverseType = dataverseType;
}
/**
* Used to set the discriminator value
* in the entity
*
*/
private String selected = null;
public String getSelected() {
return selected;
}
public void setSelected(String selected) {
this.selected = selected;
}
/**
* set the possible options
*
*
*/
private List<SelectItem> dataverseOptions = null;
public List getDataverseOptions() {
if (this.dataverseOptions == null) {
dataverseOptions = new ArrayList();
/**
* Choose Scholar if this dataverse will have your
* own name and will contain your own research,
* and Basic for any other dataverse.
*
*
Select the group that will most likely fit your
* dataverse, be it a university department, a journal,
* a research center, etc. If you create a Scholar dataverse,
* it will be automatically entered under the Scholar group.
*
*/
try {
String scholarOption = messagebundle.getString("scholarOption");
String basicOption = messagebundle.getString("basicOption");
String scholarLabel = messagebundle.getString("scholarOptionDetail");
String basicLabel = messagebundle.getString("basicOptionDetail");
dataverseOptions.add(new SelectItem(basicOption, basicLabel));
dataverseOptions.add(new SelectItem(scholarOption, scholarLabel));
} catch (Exception uee) {
System.out.println("Exception: " + uee.toString());
}
}
return dataverseOptions;
}
/**
* Holds value of property firstName.
*/
private String firstName = new String("");
/**
* Getter for property firstName.
* @return Value of property firstName.
*/
public String getFirstName() {
return this.firstName;
}
/**
* Setter for property firstName.
* @param firstName New value of property firstName.
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* Holds value of property lastName.
*/
private String lastName;
/**
* Getter for property lastName.
* @return Value of property lastName.
*/
public String getLastName() {
return this.lastName;
}
/**
* Setter for property lastName.
* @param lastName New value of property lastName.
*/
public void setLastName(String lastname) {
this.lastName = lastname;
}
/**
* Holds value of property affiliation.
*/
private HtmlInputText affiliation;
/**
* Getter for property affiliation.
* @return Value of property affiliation.
*/
public HtmlInputText getAffiliation() {
return this.affiliation;
}
public HtmlInputTextarea getShortDescription() {
return shortDescription;
}
public void setShortDescription(HtmlInputTextarea shortDescription) {
this.shortDescription = shortDescription;
}
/**
* Setter for property affiliation.
* @param affiliation New value of property affiliation.
*/
public void setAffiliation(HtmlInputText affiliation) {
this.affiliation = affiliation;
}
HtmlInputTextarea shortDescription;
//END Group Select widgets
/**
* value change listeners and validators
*
*
*/
public void changeDataverseOption(ValueChangeEvent event) {
String newValue = (String) event.getNewValue();
this.setDataverseType(newValue);
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
request.setAttribute("dataverseType", newValue);
FacesContext.getCurrentInstance().renderResponse();
}
public void changeFirstName(ValueChangeEvent event) {
String newValue = (String) event.getNewValue();
this.setFirstName(newValue);
}
public void changeLastName(ValueChangeEvent event) {
String newValue = (String) event.getNewValue();
this.setLastName(newValue);
}
public void validateIsEmpty(FacesContext context,
UIComponent toValidate,
Object value) {
String newValue = (String) value;
if (newValue == null || newValue.trim().length() == 0) {
((UIInput) toValidate).setValid(false);
FacesMessage message = new FacesMessage("The field must have a value.");
context.addMessage(toValidate.getClientId(context), message);
context.renderResponse();
}
}
public void validateIsEmptyRequiredAffiliation(FacesContext context,
UIComponent toValidate,
Object value) {
String newValue = (String) value;
if ((newValue == null || newValue.trim().length() == 0) && getVDCRequestBean().getVdcNetwork().isRequireDVaffiliation()) {
FacesMessage message = new FacesMessage("The field must have a value.");
context.addMessage(toValidate.getClientId(context), message);
context.renderResponse();
((UIInput) toValidate).setValid(false);
}
}
}
| false | true | public String create() {
// Long selectedgroup = this.getSelectedGroup();
String dtype = dataverseType;
String name = (String) dataverseName.getValue();
String alias = (String) dataverseAlias.getValue();
String strAffiliation = (String) affiliation.getValue();
String strShortDescription = (String) shortDescription.getValue();
Long userId = getVDCSessionBean().getLoginBean().getUser().getId();
boolean success = true;
if (validateClassificationCheckBoxes()) {
vdcService.create(userId, name, alias, dtype);
VDC createdVDC = vdcService.findByAlias(alias);
saveClassifications(createdVDC);
createdVDC.setDtype(dataverseType);
createdVDC.setDisplayNetworkAnnouncements(getVDCRequestBean().getVdcNetwork().isDisplayAnnouncements());
createdVDC.setDisplayAnnouncements(getVDCRequestBean().getVdcNetwork().isDisplayVDCAnnouncements());
createdVDC.setAnnouncements(getVDCRequestBean().getVdcNetwork().getDefaultVDCAnnouncements());
createdVDC.setDisplayNewStudies(getVDCRequestBean().getVdcNetwork().isDisplayVDCRecentStudies());
createdVDC.setAboutThisDataverse(getVDCRequestBean().getVdcNetwork().getDefaultVDCAboutText());
createdVDC.setContactEmail(getVDCSessionBean().getLoginBean().getUser().getEmail());
createdVDC.setAffiliation(strAffiliation);
createdVDC.setDvnDescription(strShortDescription);
vdcService.edit(createdVDC);
StatusMessage msg = new StatusMessage();
String hostUrl = PropertyUtil.getHostUrl();
msg.setMessageText("Your new dataverse <a href='http://" + hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL()+ "'>http://" + hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL()+ "</a> has been successfully created!");
msg.setStyleClass("successMessage");
Map m = getRequestMap();
m.put("statusMessage", msg);
VDCUser creator = userService.findByUserName(getVDCSessionBean().getLoginBean().getUser().getUserName());
String toMailAddress = getVDCSessionBean().getLoginBean().getUser().getEmail();
String siteAddress = "unknown";
siteAddress = hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL();
logger.fine("created dataverse; site address: "+siteAddress);
mailService.sendAddSiteNotification(toMailAddress, name, siteAddress);
// Refresh User object in LoginBean so it contains the user's new role of VDC administrator.
getVDCSessionBean().getLoginBean().setUser(creator);
return "/site/AddSiteSuccess?faces-redirect=true&vdcId=" + createdVDC.getId();
}
else {
success = false;
return null;
}
}
| public String create() {
// Long selectedgroup = this.getSelectedGroup();
String dtype = dataverseType;
String name = (String) dataverseName.getValue();
String alias = (String) dataverseAlias.getValue();
String strAffiliation = (String) affiliation.getValue();
String strShortDescription = (String) shortDescription.getValue();
Long userId = getVDCSessionBean().getLoginBean().getUser().getId();
boolean success = true;
if (validateClassificationCheckBoxes()) {
vdcService.create(userId, name, alias, dtype);
VDC createdVDC = vdcService.findByAlias(alias);
saveClassifications(createdVDC);
createdVDC.setDtype(dataverseType);
createdVDC.setDisplayNetworkAnnouncements(getVDCRequestBean().getVdcNetwork().isDisplayAnnouncements());
createdVDC.setDisplayAnnouncements(getVDCRequestBean().getVdcNetwork().isDisplayVDCAnnouncements());
createdVDC.setAnnouncements(getVDCRequestBean().getVdcNetwork().getDefaultVDCAnnouncements());
createdVDC.setDisplayNewStudies(getVDCRequestBean().getVdcNetwork().isDisplayVDCRecentStudies());
createdVDC.setAboutThisDataverse(getVDCRequestBean().getVdcNetwork().getDefaultVDCAboutText());
createdVDC.setContactEmail(getVDCSessionBean().getLoginBean().getUser().getEmail());
createdVDC.setAffiliation(strAffiliation);
createdVDC.setDvnDescription(strShortDescription);
vdcService.edit(createdVDC);
StatusMessage msg = new StatusMessage();
String hostUrl = PropertyUtil.getHostUrl();
msg.setMessageText("Your new dataverse <a href='http://" + hostUrl + "/dvn/dv/" + createdVDC.getAlias() + "'>http://" + hostUrl + "/dvn/dv/" + createdVDC.getAlias() + "</a> has been successfully created!");
msg.setStyleClass("successMessage");
Map m = getRequestMap();
m.put("statusMessage", msg);
VDCUser creator = userService.findByUserName(getVDCSessionBean().getLoginBean().getUser().getUserName());
String toMailAddress = getVDCSessionBean().getLoginBean().getUser().getEmail();
String siteAddress = "unknown";
siteAddress = hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL();
logger.fine("created dataverse; site address: "+siteAddress);
mailService.sendAddSiteNotification(toMailAddress, name, siteAddress);
// Refresh User object in LoginBean so it contains the user's new role of VDC administrator.
getVDCSessionBean().getLoginBean().setUser(creator);
return "/site/AddSiteSuccessPage?faces-redirect=true&vdcId=" + createdVDC.getId();
}
else {
success = false;
return null;
}
}
|
diff --git a/src/main/java/tconstruct/common/TContent.java b/src/main/java/tconstruct/common/TContent.java
index 923bbd3bc..e5787b3e1 100644
--- a/src/main/java/tconstruct/common/TContent.java
+++ b/src/main/java/tconstruct/common/TContent.java
@@ -1,968 +1,969 @@
package tconstruct.common;
import java.util.HashMap;
import mantle.blocks.BlockUtils;
import mantle.items.abstracts.CraftingItem;
import net.minecraft.block.Block;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.material.MaterialLiquid;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.Potion;
import net.minecraft.stats.Achievement;
import net.minecraft.util.StatCollector;
import net.minecraft.util.WeightedRandomChestContent;
import net.minecraftforge.common.ChestGenHooks;
import net.minecraftforge.common.util.EnumHelper;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import tconstruct.TConstruct;
import tconstruct.achievements.TAchievements;
import tconstruct.blocks.BlockLandmine;
import tconstruct.blocks.BloodBlock;
import tconstruct.blocks.CastingChannelBlock;
import tconstruct.blocks.ConveyorBase;
import tconstruct.blocks.CraftingSlab;
import tconstruct.blocks.CraftingStationBlock;
import tconstruct.blocks.DryingRack;
import tconstruct.blocks.EquipBlock;
import tconstruct.blocks.FurnaceSlab;
import tconstruct.blocks.GlassBlockConnected;
import tconstruct.blocks.GlassBlockConnectedMeta;
import tconstruct.blocks.GlassPaneConnected;
import tconstruct.blocks.GlassPaneStained;
import tconstruct.blocks.GlueBlock;
import tconstruct.blocks.GlueFluid;
import tconstruct.blocks.GravelOre;
import tconstruct.blocks.LavaTankBlock;
import tconstruct.blocks.MeatBlock;
import tconstruct.blocks.MetalOre;
import tconstruct.blocks.MultiBrick;
import tconstruct.blocks.MultiBrickFancy;
import tconstruct.blocks.OreberryBush;
import tconstruct.blocks.OreberryBushEssence;
import tconstruct.blocks.SearedBlock;
import tconstruct.blocks.SearedSlab;
import tconstruct.blocks.SlabBase;
import tconstruct.blocks.SlimeExplosive;
import tconstruct.blocks.SlimePad;
import tconstruct.blocks.SmelteryBlock;
import tconstruct.blocks.SoilBlock;
import tconstruct.blocks.SpeedBlock;
import tconstruct.blocks.SpeedSlab;
import tconstruct.blocks.StoneLadder;
import tconstruct.blocks.StoneTorch;
import tconstruct.blocks.TConstructFluid;
import tconstruct.blocks.TMetalBlock;
import tconstruct.blocks.TankAirBlock;
import tconstruct.blocks.ToolForgeBlock;
import tconstruct.blocks.ToolStationBlock;
import tconstruct.blocks.WoodRail;
import tconstruct.blocks.slime.SlimeFluid;
import tconstruct.blocks.slime.SlimeGel;
import tconstruct.blocks.slime.SlimeGrass;
import tconstruct.blocks.slime.SlimeLeaves;
import tconstruct.blocks.slime.SlimeSapling;
import tconstruct.blocks.slime.SlimeTallGrass;
import tconstruct.blocks.traps.BarricadeBlock;
import tconstruct.blocks.traps.Punji;
import tconstruct.client.StepSoundSlime;
import tconstruct.entity.BlueSlime;
import tconstruct.entity.Crystal;
import tconstruct.entity.FancyEntityItem;
import tconstruct.entity.item.EntityLandmineFirework;
import tconstruct.entity.item.ExplosivePrimed;
import tconstruct.entity.projectile.ArrowEntity;
import tconstruct.entity.projectile.DaggerEntity;
import tconstruct.entity.projectile.LaunchedPotion;
import tconstruct.items.Bowstring;
import tconstruct.items.CreativeModifier;
import tconstruct.items.DiamondApple;
import tconstruct.items.FilledBucket;
import tconstruct.items.Fletching;
import tconstruct.items.GoldenHead;
import tconstruct.items.Jerky;
import tconstruct.items.Manual;
import tconstruct.items.MaterialItem;
import tconstruct.items.MetalPattern;
import tconstruct.items.OreBerries;
import tconstruct.items.Pattern;
import tconstruct.items.StrangeFood;
import tconstruct.items.TitleIcon;
import tconstruct.items.ToolPart;
import tconstruct.items.ToolPartHidden;
import tconstruct.items.ToolShard;
import tconstruct.items.armor.ArmorBasic;
import tconstruct.items.armor.ExoArmor;
import tconstruct.items.armor.HeartCanister;
import tconstruct.items.armor.Knapsack;
import tconstruct.items.tools.Arrow;
import tconstruct.items.tools.BattleSign;
import tconstruct.items.tools.Battleaxe;
import tconstruct.items.tools.Broadsword;
import tconstruct.items.tools.Chisel;
import tconstruct.items.tools.Cleaver;
import tconstruct.items.tools.Cutlass;
import tconstruct.items.tools.Dagger;
import tconstruct.items.tools.Excavator;
import tconstruct.items.tools.FryingPan;
import tconstruct.items.tools.Hammer;
import tconstruct.items.tools.Hatchet;
import tconstruct.items.tools.Longsword;
import tconstruct.items.tools.LumberAxe;
import tconstruct.items.tools.Mattock;
import tconstruct.items.tools.Pickaxe;
import tconstruct.items.tools.PotionLauncher;
import tconstruct.items.tools.Rapier;
import tconstruct.items.tools.Scythe;
import tconstruct.items.tools.Shortbow;
import tconstruct.items.tools.Shovel;
import tconstruct.library.TConstructRegistry;
import tconstruct.library.armor.EnumArmorPart;
import tconstruct.library.crafting.LiquidCasting;
import tconstruct.library.crafting.PatternBuilder;
import tconstruct.library.util.IPattern;
import tconstruct.util.config.PHConstruct;
import cpw.mods.fml.common.IFuelHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
public class TContent implements IFuelHandler
{
// Temporary items
// public static Item armorTest = new ArmorStandard(2445, 4,
// EnumArmorPart.HELMET).setCreativeTab(CreativeTabs.tabAllSearch);
public TContent()
{
registerItems();
TRecipes.registerItemRecipes();
registerBlocks();
TRecipes.registerBlockRecipes();
registerMaterials();
addCraftingRecipes();
setupToolTabs();
addLoot();
if (PHConstruct.achievementsEnabled)
{
addAchievements();
}
}
public void createEntities ()
{
EntityRegistry.registerModEntity(FancyEntityItem.class, "Fancy Item", 0, TConstruct.instance, 32, 5, true);
EntityRegistry.registerModEntity(DaggerEntity.class, "Dagger", 1, TConstruct.instance, 32, 5, true);
EntityRegistry.registerModEntity(Crystal.class, "Crystal", 2, TConstruct.instance, 32, 3, true);
EntityRegistry.registerModEntity(LaunchedPotion.class, "Launched Potion", 3, TConstruct.instance, 32, 3, true);
EntityRegistry.registerModEntity(ArrowEntity.class, "Arrow", 4, TConstruct.instance, 32, 5, true);
EntityRegistry.registerModEntity(EntityLandmineFirework.class, "LandmineFirework", 5, TConstruct.instance, 32, 5, true);
EntityRegistry.registerModEntity(ExplosivePrimed.class, "SlimeExplosive", 6, TConstruct.instance, 32, 5, true);
// EntityRegistry.registerModEntity(CartEntity.class, "Small Wagon", 1,
// TConstruct.instance, 32, 5, true);
EntityRegistry.registerModEntity(BlueSlime.class, "EdibleSlime", 12, TConstruct.instance, 64, 5, true);
// EntityRegistry.registerModEntity(MetalSlime.class, "MetalSlime", 13,
// TConstruct.instance, 64, 5, true);
}
void registerBlocks ()
{
// Tool Station
TRepo.toolStationWood = new ToolStationBlock(Material.wood).setBlockName("ToolStation");
TRepo.toolForge = new ToolForgeBlock(Material.iron).setBlockName("ToolForge");
TRepo.craftingStationWood = new CraftingStationBlock(Material.wood).setBlockName("CraftingStation");
TRepo.craftingSlabWood = new CraftingSlab(Material.wood).setBlockName("CraftingSlab");
TRepo.furnaceSlab = new FurnaceSlab(Material.rock).setBlockName("FurnaceSlab");
TRepo.heldItemBlock = new EquipBlock(Material.wood).setBlockName("Frypan");
/* battlesignBlock = new BattlesignBlock(PHConstruct.battlesignBlock).setUnlocalizedName("Battlesign");
GameRegistry.registerBlock(battlesignBlock, "BattlesignBlock");
ameRegistry.registerTileEntity(BattlesignLogic.class, "BattlesignLogic");*/
TRepo.craftedSoil = new SoilBlock().setLightOpacity(0).setBlockName("TConstruct.Soil");
TRepo.craftedSoil.stepSound = Block.soundTypeGravel;
TRepo.searedSlab = new SearedSlab().setBlockName("SearedSlab");
TRepo.searedSlab.stepSound = Block.soundTypeStone;
TRepo.speedSlab = new SpeedSlab().setBlockName("SpeedSlab");
TRepo.speedSlab.stepSound = Block.soundTypeStone;
TRepo.metalBlock = new TMetalBlock(Material.iron, 10.0F).setBlockName("tconstruct.metalblock");
TRepo.metalBlock.stepSound = Block.soundTypeMetal;
TRepo.meatBlock = new MeatBlock().setBlockName("tconstruct.meatblock");
TRepo.glueBlock = new GlueBlock().setBlockName("GlueBlock").setCreativeTab(TConstructRegistry.blockTab);
TRepo.woolSlab1 = new SlabBase(Material.cloth, Blocks.wool, 0, 8).setBlockName("cloth");
TRepo.woolSlab1.setStepSound(Block.soundTypeCloth).setCreativeTab(CreativeTabs.tabDecorations);
TRepo.woolSlab2 = new SlabBase(Material.cloth, Blocks.wool, 8, 8).setBlockName("cloth");
TRepo.woolSlab2.setStepSound(Block.soundTypeCloth).setCreativeTab(CreativeTabs.tabDecorations);
// Smeltery
TRepo.smeltery = new SmelteryBlock().setBlockName("Smeltery");
TRepo.smelteryNether = new SmelteryBlock("nether").setBlockName("Smeltery");
TRepo.lavaTank = new LavaTankBlock().setBlockName("LavaTank");
TRepo.lavaTank.setStepSound(Block.soundTypeGlass);
TRepo.lavaTankNether = new LavaTankBlock("nether").setStepSound(Block.soundTypeGlass).setBlockName("LavaTank");
TRepo.searedBlock = new SearedBlock().setBlockName("SearedBlock");
TRepo.searedBlockNether = new SearedBlock("nether").setBlockName("SearedBlock");
TRepo.castingChannel = (new CastingChannelBlock()).setBlockName("CastingChannel");
TRepo.tankAir = new TankAirBlock(Material.leaves).setBlockUnbreakable().setBlockName("tconstruct.tank.air");
// Traps
TRepo.landmine = new BlockLandmine().setHardness(0.5F).setResistance(0F).setStepSound(Block.soundTypeMetal).setCreativeTab(CreativeTabs.tabRedstone).setBlockName("landmine");
TRepo.punji = new Punji().setBlockName("trap.punji");
TRepo.barricadeOak = new BarricadeBlock(Blocks.log, 0).setBlockName("trap.barricade.oak");
TRepo.barricadeSpruce = new BarricadeBlock(Blocks.log, 1).setBlockName("trap.barricade.spruce");
TRepo.barricadeBirch = new BarricadeBlock(Blocks.log, 2).setBlockName("trap.barricade.birch");
TRepo.barricadeJungle = new BarricadeBlock(Blocks.log, 3).setBlockName("trap.barricade.jungle");
TRepo.slimeExplosive = new SlimeExplosive().setHardness(0.0F).setStepSound(Block.soundTypeGrass).setBlockName("explosive.slime");
TRepo.dryingRack = new DryingRack().setBlockName("Armor.DryingRack");
// Liquids
TRepo.liquidMetal = new MaterialLiquid(MapColor.tntColor);
TRepo.moltenIronFluid = new Fluid("iron.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenIronFluid))
TRepo.moltenIronFluid = FluidRegistry.getFluid("iron.molten");
TRepo.moltenIron = new TConstructFluid(TRepo.moltenIronFluid, Material.lava, "liquid_iron").setBlockName("fluid.molten.iron");
GameRegistry.registerBlock(TRepo.moltenIron, "fluid.molten.iron");
TRepo.moltenIronFluid.setBlock(TRepo.moltenIron).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenIronFluid, 1000), new ItemStack(TRepo.buckets, 1, 0), new ItemStack(Items.bucket)));
TRepo.moltenGoldFluid = new Fluid("gold.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenGoldFluid))
TRepo.moltenGoldFluid = FluidRegistry.getFluid("gold.molten");
TRepo.moltenGold = new TConstructFluid(TRepo.moltenGoldFluid, Material.lava, "liquid_gold").setBlockName("fluid.molten.gold");
GameRegistry.registerBlock(TRepo.moltenGold, "fluid.molten.gold");
TRepo.moltenGoldFluid.setBlock(TRepo.moltenGold).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenGoldFluid, 1000), new ItemStack(TRepo.buckets, 1, 1), new ItemStack(Items.bucket)));
TRepo.moltenCopperFluid = new Fluid("copper.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenCopperFluid))
TRepo.moltenCopperFluid = FluidRegistry.getFluid("copper.molten");
TRepo.moltenCopper = new TConstructFluid(TRepo.moltenCopperFluid, Material.lava, "liquid_copper").setBlockName("fluid.molten.copper");
GameRegistry.registerBlock(TRepo.moltenCopper, "fluid.molten.copper");
TRepo.moltenCopperFluid.setBlock(TRepo.moltenCopper).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenCopperFluid, 1000), new ItemStack(TRepo.buckets, 1, 2), new ItemStack(Items.bucket)));
TRepo.moltenTinFluid = new Fluid("tin.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenTinFluid))
TRepo.moltenTinFluid = FluidRegistry.getFluid("tin.molten");
TRepo.moltenTin = new TConstructFluid(TRepo.moltenTinFluid, Material.lava, "liquid_tin").setBlockName("fluid.molten.tin");
GameRegistry.registerBlock(TRepo.moltenTin, "fluid.molten.tin");
TRepo.moltenTinFluid.setBlock(TRepo.moltenTin).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenTinFluid, 1000), new ItemStack(TRepo.buckets, 1, 3), new ItemStack(Items.bucket)));
TRepo.moltenAluminumFluid = new Fluid("aluminum.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenAluminumFluid))
TRepo.moltenAluminumFluid = FluidRegistry.getFluid("aluminum.molten");
TRepo.moltenAluminum = new TConstructFluid(TRepo.moltenAluminumFluid, Material.lava, "liquid_aluminum").setBlockName("fluid.molten.aluminum");
GameRegistry.registerBlock(TRepo.moltenAluminum, "fluid.molten.aluminum");
TRepo.moltenAluminumFluid.setBlock(TRepo.moltenAluminum).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenAluminumFluid, 1000), new ItemStack(TRepo.buckets, 1, 4), new ItemStack(Items.bucket)));
TRepo.moltenCobaltFluid = new Fluid("cobalt.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenCobaltFluid))
TRepo.moltenCobaltFluid = FluidRegistry.getFluid("cobalt.molten");
TRepo.moltenCobalt = new TConstructFluid(TRepo.moltenCobaltFluid, Material.lava, "liquid_cobalt").setBlockName("fluid.molten.cobalt");
GameRegistry.registerBlock(TRepo.moltenCobalt, "fluid.molten.cobalt");
TRepo.moltenCobaltFluid.setBlock(TRepo.moltenCobalt).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenCobaltFluid, 1000), new ItemStack(TRepo.buckets, 1, 5), new ItemStack(Items.bucket)));
TRepo.moltenArditeFluid = new Fluid("ardite.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenArditeFluid))
TRepo.moltenArditeFluid = FluidRegistry.getFluid("ardite.molten");
TRepo.moltenArdite = new TConstructFluid(TRepo.moltenArditeFluid, Material.lava, "liquid_ardite").setBlockName("fluid.molten.ardite");
GameRegistry.registerBlock(TRepo.moltenArdite, "fluid.molten.ardite");
TRepo.moltenArditeFluid.setBlock(TRepo.moltenArdite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenArditeFluid, 1000), new ItemStack(TRepo.buckets, 1, 6), new ItemStack(Items.bucket)));
TRepo.moltenBronzeFluid = new Fluid("bronze.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenBronzeFluid))
TRepo.moltenBronzeFluid = FluidRegistry.getFluid("bronze.molten");
TRepo.moltenBronze = new TConstructFluid(TRepo.moltenBronzeFluid, Material.lava, "liquid_bronze").setBlockName("fluid.molten.bronze");
GameRegistry.registerBlock(TRepo.moltenBronze, "fluid.molten.bronze");
TRepo.moltenBronzeFluid.setBlock(TRepo.moltenBronze).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenBronzeFluid, 1000), new ItemStack(TRepo.buckets, 1, 7), new ItemStack(Items.bucket)));
TRepo.moltenAlubrassFluid = new Fluid("aluminumbrass.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenAlubrassFluid))
TRepo.moltenAlubrassFluid = FluidRegistry.getFluid("aluminumbrass.molten");
TRepo.moltenAlubrass = new TConstructFluid(TRepo.moltenAlubrassFluid, Material.lava, "liquid_alubrass").setBlockName("fluid.molten.alubrass");
GameRegistry.registerBlock(TRepo.moltenAlubrass, "fluid.molten.alubrass");
TRepo.moltenAlubrassFluid.setBlock(TRepo.moltenAlubrass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenAlubrassFluid, 1000), new ItemStack(TRepo.buckets, 1, 8), new ItemStack(Items.bucket)));
TRepo.moltenManyullynFluid = new Fluid("manyullyn.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenManyullynFluid))
TRepo.moltenManyullynFluid = FluidRegistry.getFluid("manyullyn.molten");
TRepo.moltenManyullyn = new TConstructFluid(TRepo.moltenManyullynFluid, Material.lava, "liquid_manyullyn").setBlockName("fluid.molten.manyullyn");
GameRegistry.registerBlock(TRepo.moltenManyullyn, "fluid.molten.manyullyn");
TRepo.moltenManyullynFluid.setBlock(TRepo.moltenManyullyn).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenManyullynFluid, 1000), new ItemStack(TRepo.buckets, 1, 9), new ItemStack(Items.bucket)));
TRepo.moltenAlumiteFluid = new Fluid("alumite.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenAlumiteFluid))
TRepo.moltenAlumiteFluid = FluidRegistry.getFluid("alumite.molten");
TRepo.moltenAlumite = new TConstructFluid(TRepo.moltenAlumiteFluid, Material.lava, "liquid_alumite").setBlockName("fluid.molten.alumite");
GameRegistry.registerBlock(TRepo.moltenAlumite, "fluid.molten.alumite");
TRepo.moltenAlumiteFluid.setBlock(TRepo.moltenAlumite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenAlumiteFluid, 1000), new ItemStack(TRepo.buckets, 1, 10), new ItemStack(Items.bucket)));
TRepo.moltenObsidianFluid = new Fluid("obsidian.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenObsidianFluid))
TRepo.moltenObsidianFluid = FluidRegistry.getFluid("obsidian.molten");
TRepo.moltenObsidian = new TConstructFluid(TRepo.moltenObsidianFluid, Material.lava, "liquid_obsidian").setBlockName("fluid.molten.obsidian");
GameRegistry.registerBlock(TRepo.moltenObsidian, "fluid.molten.obsidian");
TRepo.moltenObsidianFluid.setBlock(TRepo.moltenObsidian).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenObsidianFluid, 1000), new ItemStack(TRepo.buckets, 1, 11), new ItemStack(Items.bucket)));
TRepo.moltenSteelFluid = new Fluid("steel.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenSteelFluid))
TRepo.moltenSteelFluid = FluidRegistry.getFluid("steel.molten");
TRepo.moltenSteel = new TConstructFluid(TRepo.moltenSteelFluid, Material.lava, "liquid_steel").setBlockName("fluid.molten.steel");
GameRegistry.registerBlock(TRepo.moltenSteel, "fluid.molten.steel");
TRepo.moltenSteelFluid.setBlock(TRepo.moltenSteel).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenSteelFluid, 1000), new ItemStack(TRepo.buckets, 1, 12), new ItemStack(Items.bucket)));
TRepo.moltenGlassFluid = new Fluid("glass.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenGlassFluid))
TRepo.moltenGlassFluid = FluidRegistry.getFluid("glass.molten");
TRepo.moltenGlass = new TConstructFluid(TRepo.moltenGlassFluid, Material.lava, "liquid_glass", true).setBlockName("fluid.molten.glass");
GameRegistry.registerBlock(TRepo.moltenGlass, "fluid.molten.glass");
TRepo.moltenGlassFluid.setBlock(TRepo.moltenGlass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenGlassFluid, 1000), new ItemStack(TRepo.buckets, 1, 13), new ItemStack(Items.bucket)));
TRepo.moltenStoneFluid = new Fluid("stone.seared");
if (!FluidRegistry.registerFluid(TRepo.moltenStoneFluid))
TRepo.moltenStoneFluid = FluidRegistry.getFluid("stone.seared");
TRepo.moltenStone = new TConstructFluid(TRepo.moltenStoneFluid, Material.lava, "liquid_stone").setBlockName("molten.stone");
GameRegistry.registerBlock(TRepo.moltenStone, "molten.stone");
TRepo.moltenStoneFluid.setBlock(TRepo.moltenStone).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenStoneFluid, 1000), new ItemStack(TRepo.buckets, 1, 14), new ItemStack(Items.bucket)));
TRepo.moltenEmeraldFluid = new Fluid("emerald.liquid");
if (!FluidRegistry.registerFluid(TRepo.moltenEmeraldFluid))
TRepo.moltenEmeraldFluid = FluidRegistry.getFluid("emerald.liquid");
TRepo.moltenEmerald = new TConstructFluid(TRepo.moltenEmeraldFluid, Material.water, "liquid_villager").setBlockName("molten.emerald");
GameRegistry.registerBlock(TRepo.moltenEmerald, "molten.emerald");
TRepo.moltenEmeraldFluid.setBlock(TRepo.moltenEmerald).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenEmeraldFluid, 1000), new ItemStack(TRepo.buckets, 1, 15), new ItemStack(Items.bucket)));
TRepo.bloodFluid = new Fluid("blood");
if (!FluidRegistry.registerFluid(TRepo.bloodFluid))
TRepo.bloodFluid = FluidRegistry.getFluid("blood");
TRepo.blood = new BloodBlock(TRepo.bloodFluid, Material.water, "liquid_cow").setBlockName("liquid.blood");
GameRegistry.registerBlock(TRepo.blood, "liquid.blood");
TRepo.bloodFluid.setBlock(TRepo.blood).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.bloodFluid, 1000), new ItemStack(TRepo.buckets, 1, 16), new ItemStack(Items.bucket)));
TRepo.moltenNickelFluid = new Fluid("nickel.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenNickelFluid))
TRepo.moltenNickelFluid = FluidRegistry.getFluid("nickel.molten");
TRepo.moltenNickel = new TConstructFluid(TRepo.moltenNickelFluid, Material.lava, "liquid_ferrous").setBlockName("fluid.molten.nickel");
GameRegistry.registerBlock(TRepo.moltenNickel, "fluid.molten.nickel");
TRepo.moltenNickelFluid.setBlock(TRepo.moltenNickel).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenNickelFluid, 1000), new ItemStack(TRepo.buckets, 1, 17), new ItemStack(Items.bucket)));
TRepo.moltenLeadFluid = new Fluid("lead.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenLeadFluid))
TRepo.moltenLeadFluid = FluidRegistry.getFluid("lead.molten");
TRepo.moltenLead = new TConstructFluid(TRepo.moltenLeadFluid, Material.lava, "liquid_lead").setBlockName("fluid.molten.lead");
GameRegistry.registerBlock(TRepo.moltenLead, "fluid.molten.lead");
TRepo.moltenLeadFluid.setBlock(TRepo.moltenLead).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenLeadFluid, 1000), new ItemStack(TRepo.buckets, 1, 18), new ItemStack(Items.bucket)));
TRepo.moltenSilverFluid = new Fluid("silver.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenSilverFluid))
TRepo.moltenSilverFluid = FluidRegistry.getFluid("silver.molten");
TRepo.moltenSilver = new TConstructFluid(TRepo.moltenSilverFluid, Material.lava, "liquid_silver").setBlockName("fluid.molten.silver");
GameRegistry.registerBlock(TRepo.moltenSilver, "fluid.molten.silver");
TRepo.moltenSilverFluid.setBlock(TRepo.moltenSilver).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenSilverFluid, 1000), new ItemStack(TRepo.buckets, 1, 19), new ItemStack(Items.bucket)));
TRepo.moltenShinyFluid = new Fluid("platinum.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenShinyFluid))
TRepo.moltenShinyFluid = FluidRegistry.getFluid("platinum.molten");
TRepo.moltenShiny = new TConstructFluid(TRepo.moltenShinyFluid, Material.lava, "liquid_shiny").setBlockName("fluid.molten.shiny");
GameRegistry.registerBlock(TRepo.moltenShiny, "fluid.molten.shiny");
TRepo.moltenShinyFluid.setBlock(TRepo.moltenShiny).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenShinyFluid, 1000), new ItemStack(TRepo.buckets, 1, 20), new ItemStack(Items.bucket)));
TRepo.moltenInvarFluid = new Fluid("invar.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenInvarFluid))
TRepo.moltenInvarFluid = FluidRegistry.getFluid("invar.molten");
TRepo.moltenInvar = new TConstructFluid(TRepo.moltenInvarFluid, Material.lava, "liquid_invar").setBlockName("fluid.molten.invar");
GameRegistry.registerBlock(TRepo.moltenInvar, "fluid.molten.invar");
TRepo.moltenInvarFluid.setBlock(TRepo.moltenInvar).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenInvarFluid, 1000), new ItemStack(TRepo.buckets, 1, 21), new ItemStack(Items.bucket)));
TRepo.moltenElectrumFluid = new Fluid("electrum.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenElectrumFluid))
TRepo.moltenElectrumFluid = FluidRegistry.getFluid("electrum.molten");
TRepo.moltenElectrum = new TConstructFluid(TRepo.moltenElectrumFluid, Material.lava, "liquid_electrum").setBlockName("fluid.molten.electrum");
GameRegistry.registerBlock(TRepo.moltenElectrum, "fluid.molten.electrum");
TRepo.moltenElectrumFluid.setBlock(TRepo.moltenElectrum).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenElectrumFluid, 1000), new ItemStack(TRepo.buckets, 1, 22), new ItemStack(Items.bucket)));
TRepo.moltenEnderFluid = new Fluid("ender");
if (!FluidRegistry.registerFluid(TRepo.moltenEnderFluid))
{
TRepo.moltenEnderFluid = FluidRegistry.getFluid("ender");
TRepo.moltenEnder = TRepo.moltenEnderFluid.getBlock();
if (TRepo.moltenEnder == null)
TConstruct.logger.info("Molten ender block missing!");
}
else
{
TRepo.moltenEnder = new TConstructFluid(TRepo.moltenEnderFluid, Material.water, "liquid_ender").setBlockName("fluid.ender");
GameRegistry.registerBlock(TRepo.moltenEnder, "fluid.ender");
TRepo.moltenEnderFluid.setBlock(TRepo.moltenEnder).setDensity(3000).setViscosity(6000);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenEnderFluid, 1000), new ItemStack(TRepo.buckets, 1, 23), new ItemStack(Items.bucket)));
}
// Slime
TRepo.slimeStep = new StepSoundSlime("mob.slime", 1.0f, 1.0f);
TRepo.blueSlimeFluid = new Fluid("slime.blue");
if (!FluidRegistry.registerFluid(TRepo.blueSlimeFluid))
TRepo.blueSlimeFluid = FluidRegistry.getFluid("slime.blue");
TRepo.slimePool = new SlimeFluid(TRepo.blueSlimeFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(TRepo.slimeStep).setBlockName("liquid.slime");
GameRegistry.registerBlock(TRepo.slimePool, "liquid.slime");
TRepo.blueSlimeFluid.setBlock(TRepo.slimePool);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.blueSlimeFluid, 1000), new ItemStack(TRepo.buckets, 1, 24), new ItemStack(Items.bucket)));
// Glue
TRepo.glueFluid = new Fluid("glue").setDensity(6000).setViscosity(6000).setTemperature(200);
if (!FluidRegistry.registerFluid(TRepo.glueFluid))
TRepo.glueFluid = FluidRegistry.getFluid("glue");
TRepo.glueFluidBlock = new GlueFluid(TRepo.glueFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(TRepo.slimeStep).setBlockName("liquid.glue");
GameRegistry.registerBlock(TRepo.glueFluidBlock, "liquid.glue");
TRepo.glueFluid.setBlock(TRepo.glueFluidBlock);
- FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.glueFluid, 1000), new ItemStack(TRepo.buckets, 1, 26), new ItemStack(Items.bucket)));
+ FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.glueFluid, 1000), new ItemStack(TRepo.buckets, 1, 25), new ItemStack(Items.bucket)));
TRepo.pigIronFluid = new Fluid("pigiron.molten");
if (!FluidRegistry.registerFluid(TRepo.pigIronFluid))
TRepo.pigIronFluid = FluidRegistry.getFluid("pigiron.molten");
else
TRepo.pigIronFluid.setDensity(3000).setViscosity(6000).setTemperature(1300);
+ FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.pigIronFluid, 1000), new ItemStack(TRepo.buckets, 1, 26), new ItemStack(Items.bucket)));
TRepo.fluids = new Fluid[] { TRepo.moltenIronFluid, TRepo.moltenGoldFluid, TRepo.moltenCopperFluid, TRepo.moltenTinFluid, TRepo.moltenAluminumFluid, TRepo.moltenCobaltFluid,
TRepo.moltenArditeFluid, TRepo.moltenBronzeFluid, TRepo.moltenAlubrassFluid, TRepo.moltenManyullynFluid, TRepo.moltenAlumiteFluid, TRepo.moltenObsidianFluid, TRepo.moltenSteelFluid,
TRepo.moltenGlassFluid, TRepo.moltenStoneFluid, TRepo.moltenEmeraldFluid, TRepo.bloodFluid, TRepo.moltenNickelFluid, TRepo.moltenLeadFluid, TRepo.moltenSilverFluid,
TRepo.moltenShinyFluid, TRepo.moltenInvarFluid, TRepo.moltenElectrumFluid, TRepo.moltenEnderFluid, TRepo.blueSlimeFluid, TRepo.glueFluid, TRepo.pigIronFluid };
TRepo.fluidBlocks = new Block[] { TRepo.moltenIron, TRepo.moltenGold, TRepo.moltenCopper, TRepo.moltenTin, TRepo.moltenAluminum, TRepo.moltenCobalt, TRepo.moltenArdite, TRepo.moltenBronze,
TRepo.moltenAlubrass, TRepo.moltenManyullyn, TRepo.moltenAlumite, TRepo.moltenObsidian, TRepo.moltenSteel, TRepo.moltenGlass, TRepo.moltenStone, TRepo.moltenEmerald, TRepo.blood,
TRepo.moltenNickel, TRepo.moltenLead, TRepo.moltenSilver, TRepo.moltenShiny, TRepo.moltenInvar, TRepo.moltenElectrum, TRepo.moltenEnder, TRepo.slimePool, TRepo.glueFluidBlock };
// Slime Islands
TRepo.slimeGel = new SlimeGel().setStepSound(TRepo.slimeStep).setLightOpacity(0).setBlockName("slime.gel");
TRepo.slimeGrass = new SlimeGrass().setStepSound(Block.soundTypeGrass).setLightOpacity(0).setBlockName("slime.grass");
TRepo.slimeTallGrass = new SlimeTallGrass().setStepSound(Block.soundTypeGrass).setBlockName("slime.grass.tall");
TRepo.slimeLeaves = (SlimeLeaves) new SlimeLeaves().setStepSound(TRepo.slimeStep).setLightOpacity(0).setBlockName("slime.leaves");
TRepo.slimeSapling = (SlimeSapling) new SlimeSapling().setStepSound(TRepo.slimeStep).setBlockName("slime.sapling");
TRepo.slimeChannel = new ConveyorBase(Material.water, "greencurrent").setHardness(0.3f).setStepSound(TRepo.slimeStep).setBlockName("slime.channel");
TRepo.bloodChannel = new ConveyorBase(Material.water, "liquid_cow").setHardness(0.3f).setStepSound(TRepo.slimeStep).setBlockName("blood.channel");
TRepo.slimePad = new SlimePad(Material.cloth).setStepSound(TRepo.slimeStep).setHardness(0.3f).setBlockName("slime.pad");
// Decoration
TRepo.stoneTorch = new StoneTorch().setBlockName("decoration.stonetorch");
TRepo.stoneLadder = new StoneLadder().setBlockName("decoration.stoneladder");
TRepo.multiBrick = new MultiBrick().setBlockName("Decoration.Brick");
TRepo.multiBrickFancy = new MultiBrickFancy().setBlockName("Decoration.BrickFancy");
// Ores
String[] berryOres = new String[] { "berry_iron", "berry_gold", "berry_copper", "berry_tin", "berry_iron_ripe", "berry_gold_ripe", "berry_copper_ripe", "berry_tin_ripe" };
TRepo.oreBerry = (OreberryBush) new OreberryBush(berryOres, 0, 4, new String[] { "oreIron", "oreGold", "oreCopper", "oreTin" }).setBlockName("ore.berries.one");
String[] berryOresTwo = new String[] { "berry_aluminum", "berry_essence", "", "", "berry_aluminum_ripe", "berry_essence_ripe", "", "" };
TRepo.oreBerrySecond = (OreberryBush) new OreberryBushEssence(berryOresTwo, 4, 2, new String[] { "oreAluminum", "oreSilver" }).setBlockName("ore.berries.two");
String[] oreTypes = new String[] { "nether_slag", "nether_cobalt", "nether_ardite", "ore_copper", "ore_tin", "ore_aluminum", "ore_slag" };
TRepo.oreSlag = new MetalOre(Material.rock, 10.0F, oreTypes).setBlockName("tconstruct.stoneore");
TRepo.oreSlag.setHarvestLevel("pickaxe", 4, 1);
TRepo.oreSlag.setHarvestLevel("pickaxe", 4, 2);
TRepo.oreSlag.setHarvestLevel("pickaxe", 1, 3);
TRepo.oreSlag.setHarvestLevel("pickaxe", 1, 4);
TRepo.oreSlag.setHarvestLevel("pickaxe", 1, 5);
TRepo.oreGravel = new GravelOre().setBlockName("GravelOre").setBlockName("tconstruct.gravelore");
TRepo.oreGravel.setHarvestLevel("shovel", 1, 0);
TRepo.oreGravel.setHarvestLevel("shovel", 2, 1);
TRepo.oreGravel.setHarvestLevel("shovel", 1, 2);
TRepo.oreGravel.setHarvestLevel("shovel", 1, 3);
TRepo.oreGravel.setHarvestLevel("shovel", 1, 4);
TRepo.oreGravel.setHarvestLevel("shovel", 4, 5);
TRepo.speedBlock = new SpeedBlock().setBlockName("SpeedBlock");
// Glass
TRepo.clearGlass = new GlassBlockConnected("clear", false).setBlockName("GlassBlock");
TRepo.clearGlass.stepSound = Block.soundTypeGlass;
TRepo.glassPane = new GlassPaneConnected("clear", false);
TRepo.stainedGlassClear = new GlassBlockConnectedMeta("stained", true, "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue",
"brown", "green", "red", "black").setBlockName("GlassBlock.StainedClear");
TRepo.stainedGlassClear.stepSound = Block.soundTypeGlass;
TRepo.stainedGlassClearPane = new GlassPaneStained();
// Rail
TRepo.woodenRail = new WoodRail().setStepSound(Block.soundTypeWood).setCreativeTab(TConstructRegistry.blockTab).setBlockName("rail.wood");
}
void registerItems ()
{
TRepo.titleIcon = new TitleIcon().setUnlocalizedName("tconstruct.titleicon");
GameRegistry.registerItem(TRepo.titleIcon, "titleIcon");
String[] blanks = new String[] { "blank_pattern", "blank_cast", "blank_cast" };
TRepo.blankPattern = new CraftingItem(blanks, blanks, "materials/", "tinker", TConstructRegistry.materialTab).setUnlocalizedName("tconstruct.Pattern");
GameRegistry.registerItem(TRepo.blankPattern, "blankPattern");
TRepo.materials = new MaterialItem().setUnlocalizedName("tconstruct.Materials");
TRepo.toolRod = new ToolPart("_rod", "ToolRod").setUnlocalizedName("tconstruct.ToolRod");
TRepo.toolShard = new ToolShard("_chunk").setUnlocalizedName("tconstruct.ToolShard");
TRepo.woodPattern = new Pattern("pattern_", "materials/").setUnlocalizedName("tconstruct.Pattern");
TRepo.metalPattern = new MetalPattern("cast_", "materials/").setUnlocalizedName("tconstruct.MetalPattern");
// armorPattern = new ArmorPattern(PHConstruct.armorPattern,
// "armorcast_",
// "materials/").setUnlocalizedName("tconstruct.ArmorPattern");
GameRegistry.registerItem(TRepo.materials, "materials");
GameRegistry.registerItem(TRepo.woodPattern, "woodPattern");
GameRegistry.registerItem(TRepo.metalPattern, "metalPattern");
// GameRegistry.registerItem(TRepo.armorPattern, "armorPattern");
TConstructRegistry.addItemToDirectory("blankPattern", TRepo.blankPattern);
TConstructRegistry.addItemToDirectory("woodPattern", TRepo.woodPattern);
TConstructRegistry.addItemToDirectory("metalPattern", TRepo.metalPattern);
// TConstructRegistry.addItemToDirectory("armorPattern", armorPattern);
String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead",
"knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" };
for (int i = 1; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Pattern", new ItemStack(TRepo.woodPattern, 1, i));
}
for (int i = 0; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Cast", new ItemStack(TRepo.metalPattern, 1, i));
}
/*
* String[] armorPartTypes = { "helmet", "chestplate", "leggings",
* "boots" }; for (int i = 1; i < armorPartTypes.length; i++) {
* TConstructRegistry.addItemStackToDirectory(armorPartTypes[i] +
* "Cast", new ItemStack(armorPattern, 1, i)); }
*/
TRepo.manualBook = new Manual();
GameRegistry.registerItem(TRepo.manualBook, "manualBook");
TRepo.buckets = new FilledBucket(BlockUtils.getBlockFromItem(TRepo.buckets));
GameRegistry.registerItem(TRepo.buckets, "buckets");
TRepo.pickaxe = new Pickaxe();
TRepo.shovel = new Shovel();
TRepo.hatchet = new Hatchet();
TRepo.broadsword = new Broadsword();
TRepo.longsword = new Longsword();
TRepo.rapier = new Rapier();
TRepo.dagger = new Dagger();
TRepo.cutlass = new Cutlass();
TRepo.frypan = new FryingPan();
TRepo.battlesign = new BattleSign();
TRepo.mattock = new Mattock();
TRepo.chisel = new Chisel();
TRepo.lumberaxe = new LumberAxe();
TRepo.cleaver = new Cleaver();
TRepo.scythe = new Scythe();
TRepo.excavator = new Excavator();
TRepo.hammer = new Hammer();
TRepo.battleaxe = new Battleaxe();
TRepo.shortbow = new Shortbow();
TRepo.arrow = new Arrow();
Item[] tools = { TRepo.pickaxe, TRepo.shovel, TRepo.hatchet, TRepo.broadsword, TRepo.longsword, TRepo.rapier, TRepo.dagger, TRepo.cutlass, TRepo.frypan, TRepo.battlesign, TRepo.mattock,
TRepo.chisel, TRepo.lumberaxe, TRepo.cleaver, TRepo.scythe, TRepo.excavator, TRepo.hammer, TRepo.battleaxe, TRepo.shortbow, TRepo.arrow };
String[] toolStrings = { "pickaxe", "shovel", "hatchet", "broadsword", "longsword", "rapier", "dagger", "cutlass", "frypan", "battlesign", "mattock", "chisel", "lumberaxe", "cleaver",
"scythe", "excavator", "hammer", "battleaxe", "shortbow", "arrow" };
for (int i = 0; i < tools.length; i++)
{
GameRegistry.registerItem(tools[i], toolStrings[i]); // 1.7 compat
TConstructRegistry.addItemToDirectory(toolStrings[i], tools[i]);
}
TRepo.potionLauncher = new PotionLauncher().setUnlocalizedName("tconstruct.PotionLauncher");
GameRegistry.registerItem(TRepo.potionLauncher, "potionLauncher");
TRepo.pickaxeHead = new ToolPart("_pickaxe_head", "PickHead").setUnlocalizedName("tconstruct.PickaxeHead");
TRepo.shovelHead = new ToolPart("_shovel_head", "ShovelHead").setUnlocalizedName("tconstruct.ShovelHead");
TRepo.hatchetHead = new ToolPart("_axe_head", "AxeHead").setUnlocalizedName("tconstruct.AxeHead");
TRepo.binding = new ToolPart("_binding", "Binding").setUnlocalizedName("tconstruct.Binding");
TRepo.toughBinding = new ToolPart("_toughbind", "ToughBind").setUnlocalizedName("tconstruct.ThickBinding");
TRepo.toughRod = new ToolPart("_toughrod", "ToughRod").setUnlocalizedName("tconstruct.ThickRod");
TRepo.largePlate = new ToolPart("_largeplate", "LargePlate").setUnlocalizedName("tconstruct.LargePlate");
TRepo.swordBlade = new ToolPart("_sword_blade", "SwordBlade").setUnlocalizedName("tconstruct.SwordBlade");
TRepo.wideGuard = new ToolPart("_large_guard", "LargeGuard").setUnlocalizedName("tconstruct.LargeGuard");
TRepo.handGuard = new ToolPart("_medium_guard", "MediumGuard").setUnlocalizedName("tconstruct.MediumGuard");
TRepo.crossbar = new ToolPart("_crossbar", "Crossbar").setUnlocalizedName("tconstruct.Crossbar");
TRepo.knifeBlade = new ToolPart("_knife_blade", "KnifeBlade").setUnlocalizedName("tconstruct.KnifeBlade");
TRepo.fullGuard = new ToolPartHidden("_full_guard", "FullGuard").setUnlocalizedName("tconstruct.FullGuard");
TRepo.frypanHead = new ToolPart("_frypan_head", "FrypanHead").setUnlocalizedName("tconstruct.FrypanHead");
TRepo.signHead = new ToolPart("_battlesign_head", "SignHead").setUnlocalizedName("tconstruct.SignHead");
TRepo.chiselHead = new ToolPart("_chisel_head", "ChiselHead").setUnlocalizedName("tconstruct.ChiselHead");
TRepo.scytheBlade = new ToolPart("_scythe_head", "ScytheHead").setUnlocalizedName("tconstruct.ScytheBlade");
TRepo.broadAxeHead = new ToolPart("_lumberaxe_head", "LumberHead").setUnlocalizedName("tconstruct.LumberHead");
TRepo.excavatorHead = new ToolPart("_excavator_head", "ExcavatorHead").setUnlocalizedName("tconstruct.ExcavatorHead");
TRepo.largeSwordBlade = new ToolPart("_large_sword_blade", "LargeSwordBlade").setUnlocalizedName("tconstruct.LargeSwordBlade");
TRepo.hammerHead = new ToolPart("_hammer_head", "HammerHead").setUnlocalizedName("tconstruct.HammerHead");
TRepo.bowstring = new Bowstring().setUnlocalizedName("tconstruct.Bowstring");
TRepo.arrowhead = new ToolPart("_arrowhead", "ArrowHead").setUnlocalizedName("tconstruct.Arrowhead");
TRepo.fletching = new Fletching().setUnlocalizedName("tconstruct.Fletching");
Item[] toolParts = { TRepo.toolRod, TRepo.toolShard, TRepo.pickaxeHead, TRepo.shovelHead, TRepo.hatchetHead, TRepo.binding, TRepo.toughBinding, TRepo.toughRod, TRepo.largePlate,
TRepo.swordBlade, TRepo.wideGuard, TRepo.handGuard, TRepo.crossbar, TRepo.knifeBlade, TRepo.fullGuard, TRepo.frypanHead, TRepo.signHead, TRepo.chiselHead, TRepo.scytheBlade,
TRepo.broadAxeHead, TRepo.excavatorHead, TRepo.largeSwordBlade, TRepo.hammerHead, TRepo.bowstring, TRepo.fletching, TRepo.arrowhead };
String[] toolPartStrings = { "toolRod", "toolShard", "pickaxeHead", "shovelHead", "hatchetHead", "binding", "toughBinding", "toughRod", "heavyPlate", "swordBlade", "wideGuard", "handGuard",
"crossbar", "knifeBlade", "fullGuard", "frypanHead", "signHead", "chiselHead", "scytheBlade", "broadAxeHead", "excavatorHead", "largeSwordBlade", "hammerHead", "bowstring",
"fletching", "arrowhead" };
for (int i = 0; i < toolParts.length; i++)
{
GameRegistry.registerItem(toolParts[i], toolPartStrings[i]); // 1.7
// compat
TConstructRegistry.addItemToDirectory(toolPartStrings[i], toolParts[i]);
}
TRepo.diamondApple = new DiamondApple().setUnlocalizedName("tconstruct.apple.diamond");
TRepo.strangeFood = new StrangeFood().setUnlocalizedName("tconstruct.strangefood");
TRepo.oreBerries = new OreBerries().setUnlocalizedName("oreberry");
GameRegistry.registerItem(TRepo.diamondApple, "diamondApple");
GameRegistry.registerItem(TRepo.strangeFood, "strangeFood");
GameRegistry.registerItem(TRepo.oreBerries, "oreBerries");
boolean foodOverhaul = false;
if (Loader.isModLoaded("HungerOverhaul") || Loader.isModLoaded("fc_food"))
{
foodOverhaul = true;
}
TRepo.jerky = new Jerky(foodOverhaul).setUnlocalizedName("tconstruct.jerky");
GameRegistry.registerItem(TRepo.jerky, "jerky");
// Wearables
// heavyHelmet = new TArmorBase(PHConstruct.heavyHelmet,
// 0).setUnlocalizedName("tconstruct.HeavyHelmet");
TRepo.heartCanister = new HeartCanister().setUnlocalizedName("tconstruct.canister");
// heavyBoots = new TArmorBase(PHConstruct.heavyBoots,
// 3).setUnlocalizedName("tconstruct.HeavyBoots");
// glove = new
// Glove(PHConstruct.glove).setUnlocalizedName("tconstruct.Glove");
TRepo.knapsack = new Knapsack().setUnlocalizedName("tconstruct.storage");
TRepo.goldHead = new GoldenHead(4, 1.2F, false).setAlwaysEdible().setPotionEffect(Potion.regeneration.id, 10, 0, 1.0F).setUnlocalizedName("goldenhead");
// GameRegistry.registerItem(TRepo.heavyHelmet, "heavyHelmet");
GameRegistry.registerItem(TRepo.heartCanister, "heartCanister");
// GameRegistry.registerItem(TRepo.heavyBoots, "heavyBoots");
// GameRegistry.registerItem(TRepo.glove, "glove");
GameRegistry.registerItem(TRepo.knapsack, "knapsack");
GameRegistry.registerItem(TRepo.goldHead, "goldHead");
TRepo.creativeModifier = new CreativeModifier().setUnlocalizedName("tconstruct.modifier.creative");
GameRegistry.registerItem(TRepo.creativeModifier, "creativeModifier");
LiquidCasting basinCasting = TConstruct.getBasinCasting();
TRepo.materialWood = EnumHelper.addArmorMaterial("WOOD", 2, new int[] { 1, 2, 2, 1 }, 3);
TRepo.helmetWood = new ArmorBasic(TRepo.materialWood, 0, "wood").setUnlocalizedName("tconstruct.helmetWood");
TRepo.chestplateWood = new ArmorBasic(TRepo.materialWood, 1, "wood").setUnlocalizedName("tconstruct.chestplateWood");
TRepo.leggingsWood = new ArmorBasic(TRepo.materialWood, 2, "wood").setUnlocalizedName("tconstruct.leggingsWood");
TRepo.bootsWood = new ArmorBasic(TRepo.materialWood, 3, "wood").setUnlocalizedName("tconstruct.bootsWood");
GameRegistry.registerItem(TRepo.helmetWood, "helmetWood");
GameRegistry.registerItem(TRepo.chestplateWood, "chestplateWood");
GameRegistry.registerItem(TRepo.leggingsWood, "leggingsWood");
GameRegistry.registerItem(TRepo.bootsWood, "bootsWood");
TRepo.exoGoggles = new ExoArmor(EnumArmorPart.HELMET, "exosuit").setUnlocalizedName("tconstruct.exoGoggles");
TRepo.exoChest = new ExoArmor(EnumArmorPart.CHEST, "exosuit").setUnlocalizedName("tconstruct.exoChest");
TRepo.exoPants = new ExoArmor(EnumArmorPart.PANTS, "exosuit").setUnlocalizedName("tconstruct.exoPants");
TRepo.exoShoes = new ExoArmor(EnumArmorPart.SHOES, "exosuit").setUnlocalizedName("tconstruct.exoShoes");
GameRegistry.registerItem(TRepo.exoGoggles, "helmetExo");
GameRegistry.registerItem(TRepo.exoChest, "chestplateExo");
GameRegistry.registerItem(TRepo.exoPants, "leggingsExo");
GameRegistry.registerItem(TRepo.exoShoes, "bootsExo");
String[] materialStrings = { "paperStack", "greenSlimeCrystal", "searedBrick", "ingotCobalt", "ingotArdite", "ingotManyullyn", "mossBall", "lavaCrystal", "necroticBone", "ingotCopper",
"ingotTin", "ingotAluminum", "rawAluminum", "ingotBronze", "ingotAluminumBrass", "ingotAlumite", "ingotSteel", "blueSlimeCrystal", "ingotObsidian", "nuggetIron", "nuggetCopper",
"nuggetTin", "nuggetAluminum", "nuggetSilver", "nuggetAluminumBrass", "silkyCloth", "silkyJewel", "nuggetObsidian", "nuggetCobalt", "nuggetArdite", "nuggetManyullyn", "nuggetBronze",
"nuggetAlumite", "nuggetSteel", "ingotPigIron", "nuggetPigIron", "glueball" };
for (int i = 0; i < materialStrings.length; i++)
{
TConstructRegistry.addItemStackToDirectory(materialStrings[i], new ItemStack(TRepo.materials, 1, i));
}
String[] oreberries = { "Iron", "Gold", "Copper", "Tin", "Aluminum", "Essence" };
for (int i = 0; i < oreberries.length; i++)
{
TConstructRegistry.addItemStackToDirectory("oreberry" + oreberries[i], new ItemStack(TRepo.oreBerries, 1, i));
}
TConstructRegistry.addItemStackToDirectory("diamondApple", new ItemStack(TRepo.diamondApple, 1, 0));
TConstructRegistry.addItemStackToDirectory("blueSlimeFood", new ItemStack(TRepo.strangeFood, 1, 0));
TConstructRegistry.addItemStackToDirectory("canisterEmpty", new ItemStack(TRepo.heartCanister, 1, 0));
TConstructRegistry.addItemStackToDirectory("miniRedHeart", new ItemStack(TRepo.heartCanister, 1, 1));
TConstructRegistry.addItemStackToDirectory("canisterRedHeart", new ItemStack(TRepo.heartCanister, 1, 2));
// Vanilla stack sizes
Items.wooden_door.setMaxStackSize(16);
Items.iron_door.setMaxStackSize(16);
Items.boat.setMaxStackSize(16);
Items.minecart.setMaxStackSize(3);
// Items.minecartEmpty.setMaxStackSize(3);
// Items.minecartCrate.setMaxStackSize(3);
// Items.minecartPowered.setMaxStackSize(3);
Items.cake.setMaxStackSize(16);
// Block.torchWood.setTickRandomly(false);
}
void registerMaterials ()
{
TConstructRegistry.addToolMaterial(0, "Wood", "Wooden ", 0, 59, 200, 0, 1.0F, 0, 0f, "\u00A7e", "");
TConstructRegistry.addToolMaterial(1, "Stone", 1, 131, 400, 1, 0.5F, 0, 1f, "", StatCollector.translateToLocal("materialtraits.stonebound"));
TConstructRegistry.addToolMaterial(2, "Iron", 2, 250, 600, 2, 1.3F, 1, 0f, "\u00A7f", "");
TConstructRegistry.addToolMaterial(3, "Flint", 1, 171, 525, 2, 0.7F, 0, 0f, "\u00A78", "");
TConstructRegistry.addToolMaterial(4, "Cactus", 1, 150, 500, 2, 1.0F, 0, -1f, "\u00A72", StatCollector.translateToLocal("materialtraits.jagged"));
TConstructRegistry.addToolMaterial(5, "Bone", 1, 200, 400, 1, 1.0F, 0, 0f, "\u00A7e", "");
TConstructRegistry.addToolMaterial(6, "Obsidian", 3, 89, 700, 2, 0.8F, 3, 0f, "\u00A7d", "");
TConstructRegistry.addToolMaterial(7, "Netherrack", 2, 131, 400, 1, 1.2F, 0, 1f, "\u00A74", StatCollector.translateToLocal("materialtraits.stonebound"));
TConstructRegistry.addToolMaterial(8, "Slime", 0, 500, 150, 0, 1.5F, 0, 0f, "\u00A7a", "");
TConstructRegistry.addToolMaterial(9, "Paper", 0, 30, 200, 0, 0.3F, 0, 0f, "\u00A7f", StatCollector.translateToLocal("materialtraits.writable"));
TConstructRegistry.addToolMaterial(10, "Cobalt", 4, 800, 1100, 3, 1.75F, 2, 0f, "\u00A73", "");
TConstructRegistry.addToolMaterial(11, "Ardite", 4, 600, 800, 3, 2.0F, 0, 2f, "\u00A74", StatCollector.translateToLocal("materialtraits.stonebound"));
TConstructRegistry.addToolMaterial(12, "Manyullyn", 5, 1200, 900, 4, 2.5F, 0, 0f, "\u00A75", "");
TConstructRegistry.addToolMaterial(13, "Copper", 1, 180, 500, 2, 1.15F, 0, 0f, "\u00A7c", "");
TConstructRegistry.addToolMaterial(14, "Bronze", 2, 350, 700, 2, 1.3F, 1, 0f, "\u00A76", "");
TConstructRegistry.addToolMaterial(15, "Alumite", 4, 550, 800, 3, 1.3F, 2, 0f, "\u00A7d", "");
TConstructRegistry.addToolMaterial(16, "Steel", 4, 750, 800, 3, 1.3F, 2, 0f, "", "");
TConstructRegistry.addToolMaterial(17, "BlueSlime", "Slime ", 0, 1200, 150, 0, 2.0F, 0, 0f, "\u00A7b", "");
TConstructRegistry.addToolMaterial(18, "PigIron", "Pig Iron ", 3, 250, 600, 2, 1.3F, 1, 0f, "\u00A7c", StatCollector.translateToLocal("materialtraits.tasty"));
TConstructRegistry.addBowMaterial(0, 384, 20, 1.0f); // Wood
TConstructRegistry.addBowMaterial(1, 10, 80, 0.2f); // Stone
TConstructRegistry.addBowMaterial(2, 576, 40, 1.2f); // Iron
TConstructRegistry.addBowMaterial(3, 10, 80, 0.2f); // Flint
TConstructRegistry.addBowMaterial(4, 384, 20, 1.0f); // Cactus
TConstructRegistry.addBowMaterial(5, 192, 30, 1.0f); // Bone
TConstructRegistry.addBowMaterial(6, 10, 80, 0.2f); // Obsidian
TConstructRegistry.addBowMaterial(7, 10, 80, 0.2f); // Netherrack
TConstructRegistry.addBowMaterial(8, 1536, 20, 1.2f); // Slime
TConstructRegistry.addBowMaterial(9, 48, 25, 0.5f); // Paper
TConstructRegistry.addBowMaterial(10, 1152, 40, 1.2f); // Cobalt
TConstructRegistry.addBowMaterial(11, 960, 40, 1.2f); // Ardite
TConstructRegistry.addBowMaterial(12, 1536, 40, 1.2f); // Manyullyn
TConstructRegistry.addBowMaterial(13, 384, 40, 1.2f); // Copper
TConstructRegistry.addBowMaterial(14, 576, 40, 1.2f); // Bronze
TConstructRegistry.addBowMaterial(15, 768, 40, 1.2f); // Alumite
TConstructRegistry.addBowMaterial(16, 768, 40, 1.2f); // Steel
TConstructRegistry.addBowMaterial(17, 576, 20, 1.2f); // Blue Slime
TConstructRegistry.addBowMaterial(18, 384, 20, 1.2f); // Slime
// Material ID, mass, fragility
TConstructRegistry.addArrowMaterial(0, 0.69F, 1.0F, 100F); // Wood
TConstructRegistry.addArrowMaterial(1, 2.5F, 5.0F, 100F); // Stone
TConstructRegistry.addArrowMaterial(2, 7.2F, 0.5F, 100F); // Iron
TConstructRegistry.addArrowMaterial(3, 2.65F, 1.0F, 100F); // Flint
TConstructRegistry.addArrowMaterial(4, 0.76F, 1.0F, 100F); // Cactus
TConstructRegistry.addArrowMaterial(5, 0.69F, 1.0F, 100); // Bone
TConstructRegistry.addArrowMaterial(6, 2.4F, 1.0F, 100F); // Obsidian
TConstructRegistry.addArrowMaterial(7, 3.5F, 1.0F, 100F); // Netherrack
TConstructRegistry.addArrowMaterial(8, 0.42F, 0.0F, 100F); // Slime
TConstructRegistry.addArrowMaterial(9, 1.1F, 3.0F, 90F); // Paper
TConstructRegistry.addArrowMaterial(10, 8.9F, 0.25F, 100F); // Cobalt
TConstructRegistry.addArrowMaterial(11, 7.2F, 0.25F, 100F); // Ardite
TConstructRegistry.addArrowMaterial(12, 10.6F, 0.1F, 100F); // Manyullyn
TConstructRegistry.addArrowMaterial(13, 8.96F, 0.5F, 100F); // Copper
TConstructRegistry.addArrowMaterial(14, 7.9F, 0.25F, 100F); // Bronze
TConstructRegistry.addArrowMaterial(15, 4.7F, 0.25F, 100F); // Alumite
TConstructRegistry.addArrowMaterial(16, 7.6F, 0.25F, 100F); // Steel
TConstructRegistry.addArrowMaterial(17, 0.42F, 0.0F, 100F); // Blue
// Slime
TConstructRegistry.addArrowMaterial(18, 6.8F, 0.5F, 100F); // Iron
TConstructRegistry.addBowstringMaterial(0, 2, new ItemStack(Items.string), new ItemStack(TRepo.bowstring, 1, 0), 1F, 1F, 1f); // String
TConstructRegistry.addFletchingMaterial(0, 2, new ItemStack(Items.feather), new ItemStack(TRepo.fletching, 1, 0), 100F, 0F, 0.05F); // Feather
for (int i = 0; i < 4; i++)
TConstructRegistry.addFletchingMaterial(1, 2, new ItemStack(Blocks.leaves, 1, i), new ItemStack(TRepo.fletching, 1, 1), 75F, 0F, 0.2F); // All four vanialla Leaves
TConstructRegistry.addFletchingMaterial(2, 2, new ItemStack(TRepo.materials, 1, 1), new ItemStack(TRepo.fletching, 1, 2), 100F, 0F, 0.12F); // Slime
TConstructRegistry.addFletchingMaterial(3, 2, new ItemStack(TRepo.materials, 1, 17), new ItemStack(TRepo.fletching, 1, 3), 100F, 0F, 0.12F); // BlueSlime
PatternBuilder pb = PatternBuilder.instance;
if (PHConstruct.enableTWood)
pb.registerFullMaterial(Blocks.planks, 2, StatCollector.translateToLocal("gui.partbuilder.material.wood"), new ItemStack(Items.stick), new ItemStack(Items.stick), 0);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.wood"), new ItemStack(Items.stick, 2), new ItemStack(Items.stick), 0);
if (PHConstruct.enableTStone)
{
pb.registerFullMaterial(Blocks.stone, 2, StatCollector.translateToLocal("gui.partbuilder.material.stone"), new ItemStack(TRepo.toolShard, 1, 1), new ItemStack(TRepo.toolRod, 1, 1), 1);
pb.registerMaterial(Blocks.cobblestone, 2, StatCollector.translateToLocal("gui.partbuilder.material.stone"));
}
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.stone"), new ItemStack(TRepo.toolShard, 1, 1), new ItemStack(TRepo.toolRod, 1, 1), 0);
pb.registerFullMaterial(Items.iron_ingot, 2, StatCollector.translateToLocal("gui.partbuilder.material.iron"), new ItemStack(TRepo.toolShard, 1, 2), new ItemStack(TRepo.toolRod, 1, 2), 2);
if (PHConstruct.enableTFlint)
pb.registerFullMaterial(Items.flint, 2, StatCollector.translateToLocal("gui.partbuilder.material.flint"), new ItemStack(TRepo.toolShard, 1, 3), new ItemStack(TRepo.toolRod, 1, 3), 3);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.flint"), new ItemStack(TRepo.toolShard, 1, 3), new ItemStack(TRepo.toolRod, 1, 3), 3);
if (PHConstruct.enableTCactus)
pb.registerFullMaterial(Blocks.cactus, 2, StatCollector.translateToLocal("gui.partbuilder.material.cactus"), new ItemStack(TRepo.toolShard, 1, 4), new ItemStack(TRepo.toolRod, 1, 4), 4);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.cactus"), new ItemStack(TRepo.toolShard, 1, 4), new ItemStack(TRepo.toolRod, 1, 4), 4);
if (PHConstruct.enableTBone)
pb.registerFullMaterial(Items.bone, 2, StatCollector.translateToLocal("gui.partbuilder.material.bone"), new ItemStack(Items.dye, 1, 15), new ItemStack(Items.bone), 5);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.bone"), new ItemStack(Items.dye, 1, 15), new ItemStack(Items.bone), 5);
pb.registerFullMaterial(Blocks.obsidian, 2, StatCollector.translateToLocal("gui.partbuilder.material.obsidian"), new ItemStack(TRepo.toolShard, 1, 6), new ItemStack(TRepo.toolRod, 1, 6), 6);
pb.registerMaterial(new ItemStack(TRepo.materials, 1, 18), 2, StatCollector.translateToLocal("gui.partbuilder.material.obsidian"));
if (PHConstruct.enableTNetherrack)
pb.registerFullMaterial(Blocks.netherrack, 2, StatCollector.translateToLocal("gui.partbuilder.material.netherrack"), new ItemStack(TRepo.toolShard, 1, 7), new ItemStack(TRepo.toolRod, 1, 7), 7);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.netherrack"), new ItemStack(TRepo.toolShard, 1, 7), new ItemStack(TRepo.toolRod, 1, 7), 7);
if (PHConstruct.enableTSlime)
pb.registerFullMaterial(new ItemStack(TRepo.materials, 1, 1), 2, StatCollector.translateToLocal("gui.partbuilder.material.slime"), new ItemStack(TRepo.toolShard, 1, 8), new ItemStack(TRepo.toolRod, 1, 8), 8);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.slime"), new ItemStack(TRepo.toolShard, 1, 8), new ItemStack(TRepo.toolRod, 1, 17), 8);
if (PHConstruct.enableTPaper)
pb.registerFullMaterial(new ItemStack(TRepo.materials, 1, 0), 2, StatCollector.translateToLocal("gui.partbuilder.material.paper"), new ItemStack(Items.paper, 2), new ItemStack(TRepo.toolRod, 1, 9), 9);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.blueslime"), new ItemStack(Items.paper, 2), new ItemStack(TRepo.toolRod, 1, 9), 9);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.cobalt"), new ItemStack(TRepo.toolShard, 1, 10), new ItemStack(TRepo.toolRod, 1, 10), 10);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.ardite"), new ItemStack(TRepo.toolShard, 1, 11), new ItemStack(TRepo.toolRod, 1, 11), 11);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.manyullyn"), new ItemStack(TRepo.toolShard, 1, 12), new ItemStack(TRepo.toolRod, 1, 12), 12);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.copper"), new ItemStack(TRepo.toolShard, 1, 13), new ItemStack(TRepo.toolRod, 1, 13), 13);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.bronze"), new ItemStack(TRepo.toolShard, 1, 14), new ItemStack(TRepo.toolRod, 1, 14), 14);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.alumite"), new ItemStack(TRepo.toolShard, 1, 15), new ItemStack(TRepo.toolRod, 1, 15), 15);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.steel"), new ItemStack(TRepo.toolShard, 1, 16), new ItemStack(TRepo.toolRod, 1, 16), 16);
if (PHConstruct.enableTBlueSlime)
pb.registerFullMaterial(new ItemStack(TRepo.materials, 1, 17), 2, StatCollector.translateToLocal("gui.partbuilder.material.blueslime"), new ItemStack(TRepo.toolShard, 1, 17), new ItemStack(TRepo.toolRod, 1, 17), 17);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.blueslime"), new ItemStack(TRepo.toolShard, 1, 17), new ItemStack(TRepo.toolRod, 1, 17), 17);
pb.registerFullMaterial(new ItemStack(TRepo.materials, 1, 34), 2, StatCollector.translateToLocal("gui.partbuilder.material.pigiron"), new ItemStack(TRepo.toolShard, 1, 18), new ItemStack(TRepo.toolRod, 1, 18), 18);
pb.addToolPattern((IPattern) TRepo.woodPattern);
}
void addCraftingRecipes ()
{
TRecipes.addPartMapping();
TRecipes.addRecipesForToolBuilder();
TRecipes.addRecipesForTableCasting();
TRecipes.addRecipesForBasinCasting();
TRecipes.addRecipesForSmeltery();
TRecipes.addRecipesForChisel();
TRecipes.addRecipesForFurnace();
TRecipes.addRecipesForCraftingTable();
TRecipes.addRecipesForDryingRack();
}
void setupToolTabs ()
{
TConstructRegistry.materialTab.init(new ItemStack(TRepo.manualBook, 1, 0));
TConstructRegistry.partTab.init(new ItemStack(TRepo.titleIcon, 1, 255));
TConstructRegistry.blockTab.init(new ItemStack(TRepo.toolStationWood));
ItemStack tool = new ItemStack(TRepo.longsword, 1, 0);
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("InfiTool", new NBTTagCompound());
compound.getCompoundTag("InfiTool").setInteger("RenderHead", 2);
compound.getCompoundTag("InfiTool").setInteger("RenderHandle", 0);
compound.getCompoundTag("InfiTool").setInteger("RenderAccessory", 10);
tool.setTagCompound(compound);
// TConstruct.
TConstructRegistry.toolTab.init(tool);
}
public void addLoot ()
{
// Item, min, max, weight
ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(TRepo.heartCanister, 1, 1), 1, 1, 5));
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(TRepo.heartCanister, 1, 1), 1, 1, 10));
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_JUNGLE_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(TRepo.heartCanister, 1, 1), 1, 1, 10));
TRepo.tinkerHouseChest = new ChestGenHooks("TinkerHouse", new WeightedRandomChestContent[0], 3, 27);
TRepo.tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(TRepo.heartCanister, 1, 1), 1, 1, 1));
int[] validTypes = { 0, 1, 2, 3, 4, 5, 6, 8, 9, 13, 14, 17 };
Item[] partTypes = { TRepo.pickaxeHead, TRepo.shovelHead, TRepo.hatchetHead, TRepo.binding, TRepo.swordBlade, TRepo.wideGuard, TRepo.handGuard, TRepo.crossbar, TRepo.knifeBlade,
TRepo.frypanHead, TRepo.signHead, TRepo.chiselHead };
for (int partIter = 0; partIter < partTypes.length; partIter++)
{
for (int typeIter = 0; typeIter < validTypes.length; typeIter++)
{
TRepo.tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(partTypes[partIter], 1, validTypes[typeIter]), 1, 1, 15));
}
}
TRepo.tinkerHousePatterns = new ChestGenHooks("TinkerPatterns", new WeightedRandomChestContent[0], 5, 30);
for (int i = 0; i < 13; i++)
{
TRepo.tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(TRepo.woodPattern, 1, i + 1), 1, 3, 20));
}
TRepo.tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(TRepo.woodPattern, 1, 22), 1, 3, 40));
}
public static String[] liquidNames;
@Override
public int getBurnTime (ItemStack fuel)
{
if (fuel.getItem() == TRepo.materials && fuel.getItemDamage() == 7)
return 26400;
return 0;
}
public void addAchievements ()
{
HashMap<String, Achievement> achievements = TAchievements.achievements;
achievements.put("tconstruct:beginner", new Achievement("tconstruct:beginner", "tconstruct.beginner", 0, 0, TRepo.manualBook, null));// .setIndependent());
achievements.put("tconstruct:pattern", new Achievement("tconstruct:pattern", "tconstruct.pattern", 2, 1, TRepo.blankPattern, achievements.get("tconstruct:beginner")));
achievements.put("tconstruct:tinkerer", new Achievement("tconstruct:tinkerer", "tconstruct.tinkerer", 2, 2, new ItemStack(TRepo.titleIcon, 1, 4096), achievements.get("tconstruct:pattern")));
achievements.put("tconstruct:preparedFight",
new Achievement("tconstruct:preparedFight", "tconstruct.preparedFight", 1, 3, new ItemStack(TRepo.titleIcon, 1, 4097), achievements.get("tconstruct:tinkerer")));
achievements.put("tconstruct:proTinkerer",
new Achievement("tconstruct:proTinkerer", "tconstruct.proTinkerer", 4, 4, new ItemStack(TRepo.titleIcon, 1, 4098), achievements.get("tconstruct:tinkerer")).setSpecial());
achievements.put("tconstruct:smelteryMaker", new Achievement("tconstruct:smelteryMaker", "tconstruct.smelteryMaker", -2, -1, TRepo.smeltery, achievements.get("tconstruct:beginner")));
achievements.put("tconstruct:enemySlayer",
new Achievement("tconstruct:enemySlayer", "tconstruct.enemySlayer", 0, 5, new ItemStack(TRepo.titleIcon, 1, 4099), achievements.get("tconstruct:preparedFight")));
achievements.put("tconstruct:dualConvenience",
new Achievement("tconstruct:dualConvenience", "tconstruct.dualConvenience", 0, 7, new ItemStack(TRepo.titleIcon, 1, 4100), achievements.get("tconstruct:enemySlayer")).setSpecial());
achievements.put("tconstruct:doingItWrong",
new Achievement("tconstruct:doingItWrong", "tconstruct.doingItWrong", -2, -3, new ItemStack(TRepo.manualBook, 1, 2), achievements.get("tconstruct:smelteryMaker")));
achievements.put("tconstruct:betterCrafting",
new Achievement("tconstruct:betterCrafting", "tconstruct.betterCrafting", -2, 2, TRepo.craftingStationWood, achievements.get("tconstruct:beginner")));
}
}
| false | true | void registerBlocks ()
{
// Tool Station
TRepo.toolStationWood = new ToolStationBlock(Material.wood).setBlockName("ToolStation");
TRepo.toolForge = new ToolForgeBlock(Material.iron).setBlockName("ToolForge");
TRepo.craftingStationWood = new CraftingStationBlock(Material.wood).setBlockName("CraftingStation");
TRepo.craftingSlabWood = new CraftingSlab(Material.wood).setBlockName("CraftingSlab");
TRepo.furnaceSlab = new FurnaceSlab(Material.rock).setBlockName("FurnaceSlab");
TRepo.heldItemBlock = new EquipBlock(Material.wood).setBlockName("Frypan");
/* battlesignBlock = new BattlesignBlock(PHConstruct.battlesignBlock).setUnlocalizedName("Battlesign");
GameRegistry.registerBlock(battlesignBlock, "BattlesignBlock");
ameRegistry.registerTileEntity(BattlesignLogic.class, "BattlesignLogic");*/
TRepo.craftedSoil = new SoilBlock().setLightOpacity(0).setBlockName("TConstruct.Soil");
TRepo.craftedSoil.stepSound = Block.soundTypeGravel;
TRepo.searedSlab = new SearedSlab().setBlockName("SearedSlab");
TRepo.searedSlab.stepSound = Block.soundTypeStone;
TRepo.speedSlab = new SpeedSlab().setBlockName("SpeedSlab");
TRepo.speedSlab.stepSound = Block.soundTypeStone;
TRepo.metalBlock = new TMetalBlock(Material.iron, 10.0F).setBlockName("tconstruct.metalblock");
TRepo.metalBlock.stepSound = Block.soundTypeMetal;
TRepo.meatBlock = new MeatBlock().setBlockName("tconstruct.meatblock");
TRepo.glueBlock = new GlueBlock().setBlockName("GlueBlock").setCreativeTab(TConstructRegistry.blockTab);
TRepo.woolSlab1 = new SlabBase(Material.cloth, Blocks.wool, 0, 8).setBlockName("cloth");
TRepo.woolSlab1.setStepSound(Block.soundTypeCloth).setCreativeTab(CreativeTabs.tabDecorations);
TRepo.woolSlab2 = new SlabBase(Material.cloth, Blocks.wool, 8, 8).setBlockName("cloth");
TRepo.woolSlab2.setStepSound(Block.soundTypeCloth).setCreativeTab(CreativeTabs.tabDecorations);
// Smeltery
TRepo.smeltery = new SmelteryBlock().setBlockName("Smeltery");
TRepo.smelteryNether = new SmelteryBlock("nether").setBlockName("Smeltery");
TRepo.lavaTank = new LavaTankBlock().setBlockName("LavaTank");
TRepo.lavaTank.setStepSound(Block.soundTypeGlass);
TRepo.lavaTankNether = new LavaTankBlock("nether").setStepSound(Block.soundTypeGlass).setBlockName("LavaTank");
TRepo.searedBlock = new SearedBlock().setBlockName("SearedBlock");
TRepo.searedBlockNether = new SearedBlock("nether").setBlockName("SearedBlock");
TRepo.castingChannel = (new CastingChannelBlock()).setBlockName("CastingChannel");
TRepo.tankAir = new TankAirBlock(Material.leaves).setBlockUnbreakable().setBlockName("tconstruct.tank.air");
// Traps
TRepo.landmine = new BlockLandmine().setHardness(0.5F).setResistance(0F).setStepSound(Block.soundTypeMetal).setCreativeTab(CreativeTabs.tabRedstone).setBlockName("landmine");
TRepo.punji = new Punji().setBlockName("trap.punji");
TRepo.barricadeOak = new BarricadeBlock(Blocks.log, 0).setBlockName("trap.barricade.oak");
TRepo.barricadeSpruce = new BarricadeBlock(Blocks.log, 1).setBlockName("trap.barricade.spruce");
TRepo.barricadeBirch = new BarricadeBlock(Blocks.log, 2).setBlockName("trap.barricade.birch");
TRepo.barricadeJungle = new BarricadeBlock(Blocks.log, 3).setBlockName("trap.barricade.jungle");
TRepo.slimeExplosive = new SlimeExplosive().setHardness(0.0F).setStepSound(Block.soundTypeGrass).setBlockName("explosive.slime");
TRepo.dryingRack = new DryingRack().setBlockName("Armor.DryingRack");
// Liquids
TRepo.liquidMetal = new MaterialLiquid(MapColor.tntColor);
TRepo.moltenIronFluid = new Fluid("iron.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenIronFluid))
TRepo.moltenIronFluid = FluidRegistry.getFluid("iron.molten");
TRepo.moltenIron = new TConstructFluid(TRepo.moltenIronFluid, Material.lava, "liquid_iron").setBlockName("fluid.molten.iron");
GameRegistry.registerBlock(TRepo.moltenIron, "fluid.molten.iron");
TRepo.moltenIronFluid.setBlock(TRepo.moltenIron).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenIronFluid, 1000), new ItemStack(TRepo.buckets, 1, 0), new ItemStack(Items.bucket)));
TRepo.moltenGoldFluid = new Fluid("gold.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenGoldFluid))
TRepo.moltenGoldFluid = FluidRegistry.getFluid("gold.molten");
TRepo.moltenGold = new TConstructFluid(TRepo.moltenGoldFluid, Material.lava, "liquid_gold").setBlockName("fluid.molten.gold");
GameRegistry.registerBlock(TRepo.moltenGold, "fluid.molten.gold");
TRepo.moltenGoldFluid.setBlock(TRepo.moltenGold).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenGoldFluid, 1000), new ItemStack(TRepo.buckets, 1, 1), new ItemStack(Items.bucket)));
TRepo.moltenCopperFluid = new Fluid("copper.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenCopperFluid))
TRepo.moltenCopperFluid = FluidRegistry.getFluid("copper.molten");
TRepo.moltenCopper = new TConstructFluid(TRepo.moltenCopperFluid, Material.lava, "liquid_copper").setBlockName("fluid.molten.copper");
GameRegistry.registerBlock(TRepo.moltenCopper, "fluid.molten.copper");
TRepo.moltenCopperFluid.setBlock(TRepo.moltenCopper).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenCopperFluid, 1000), new ItemStack(TRepo.buckets, 1, 2), new ItemStack(Items.bucket)));
TRepo.moltenTinFluid = new Fluid("tin.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenTinFluid))
TRepo.moltenTinFluid = FluidRegistry.getFluid("tin.molten");
TRepo.moltenTin = new TConstructFluid(TRepo.moltenTinFluid, Material.lava, "liquid_tin").setBlockName("fluid.molten.tin");
GameRegistry.registerBlock(TRepo.moltenTin, "fluid.molten.tin");
TRepo.moltenTinFluid.setBlock(TRepo.moltenTin).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenTinFluid, 1000), new ItemStack(TRepo.buckets, 1, 3), new ItemStack(Items.bucket)));
TRepo.moltenAluminumFluid = new Fluid("aluminum.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenAluminumFluid))
TRepo.moltenAluminumFluid = FluidRegistry.getFluid("aluminum.molten");
TRepo.moltenAluminum = new TConstructFluid(TRepo.moltenAluminumFluid, Material.lava, "liquid_aluminum").setBlockName("fluid.molten.aluminum");
GameRegistry.registerBlock(TRepo.moltenAluminum, "fluid.molten.aluminum");
TRepo.moltenAluminumFluid.setBlock(TRepo.moltenAluminum).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenAluminumFluid, 1000), new ItemStack(TRepo.buckets, 1, 4), new ItemStack(Items.bucket)));
TRepo.moltenCobaltFluid = new Fluid("cobalt.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenCobaltFluid))
TRepo.moltenCobaltFluid = FluidRegistry.getFluid("cobalt.molten");
TRepo.moltenCobalt = new TConstructFluid(TRepo.moltenCobaltFluid, Material.lava, "liquid_cobalt").setBlockName("fluid.molten.cobalt");
GameRegistry.registerBlock(TRepo.moltenCobalt, "fluid.molten.cobalt");
TRepo.moltenCobaltFluid.setBlock(TRepo.moltenCobalt).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenCobaltFluid, 1000), new ItemStack(TRepo.buckets, 1, 5), new ItemStack(Items.bucket)));
TRepo.moltenArditeFluid = new Fluid("ardite.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenArditeFluid))
TRepo.moltenArditeFluid = FluidRegistry.getFluid("ardite.molten");
TRepo.moltenArdite = new TConstructFluid(TRepo.moltenArditeFluid, Material.lava, "liquid_ardite").setBlockName("fluid.molten.ardite");
GameRegistry.registerBlock(TRepo.moltenArdite, "fluid.molten.ardite");
TRepo.moltenArditeFluid.setBlock(TRepo.moltenArdite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenArditeFluid, 1000), new ItemStack(TRepo.buckets, 1, 6), new ItemStack(Items.bucket)));
TRepo.moltenBronzeFluid = new Fluid("bronze.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenBronzeFluid))
TRepo.moltenBronzeFluid = FluidRegistry.getFluid("bronze.molten");
TRepo.moltenBronze = new TConstructFluid(TRepo.moltenBronzeFluid, Material.lava, "liquid_bronze").setBlockName("fluid.molten.bronze");
GameRegistry.registerBlock(TRepo.moltenBronze, "fluid.molten.bronze");
TRepo.moltenBronzeFluid.setBlock(TRepo.moltenBronze).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenBronzeFluid, 1000), new ItemStack(TRepo.buckets, 1, 7), new ItemStack(Items.bucket)));
TRepo.moltenAlubrassFluid = new Fluid("aluminumbrass.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenAlubrassFluid))
TRepo.moltenAlubrassFluid = FluidRegistry.getFluid("aluminumbrass.molten");
TRepo.moltenAlubrass = new TConstructFluid(TRepo.moltenAlubrassFluid, Material.lava, "liquid_alubrass").setBlockName("fluid.molten.alubrass");
GameRegistry.registerBlock(TRepo.moltenAlubrass, "fluid.molten.alubrass");
TRepo.moltenAlubrassFluid.setBlock(TRepo.moltenAlubrass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenAlubrassFluid, 1000), new ItemStack(TRepo.buckets, 1, 8), new ItemStack(Items.bucket)));
TRepo.moltenManyullynFluid = new Fluid("manyullyn.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenManyullynFluid))
TRepo.moltenManyullynFluid = FluidRegistry.getFluid("manyullyn.molten");
TRepo.moltenManyullyn = new TConstructFluid(TRepo.moltenManyullynFluid, Material.lava, "liquid_manyullyn").setBlockName("fluid.molten.manyullyn");
GameRegistry.registerBlock(TRepo.moltenManyullyn, "fluid.molten.manyullyn");
TRepo.moltenManyullynFluid.setBlock(TRepo.moltenManyullyn).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenManyullynFluid, 1000), new ItemStack(TRepo.buckets, 1, 9), new ItemStack(Items.bucket)));
TRepo.moltenAlumiteFluid = new Fluid("alumite.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenAlumiteFluid))
TRepo.moltenAlumiteFluid = FluidRegistry.getFluid("alumite.molten");
TRepo.moltenAlumite = new TConstructFluid(TRepo.moltenAlumiteFluid, Material.lava, "liquid_alumite").setBlockName("fluid.molten.alumite");
GameRegistry.registerBlock(TRepo.moltenAlumite, "fluid.molten.alumite");
TRepo.moltenAlumiteFluid.setBlock(TRepo.moltenAlumite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenAlumiteFluid, 1000), new ItemStack(TRepo.buckets, 1, 10), new ItemStack(Items.bucket)));
TRepo.moltenObsidianFluid = new Fluid("obsidian.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenObsidianFluid))
TRepo.moltenObsidianFluid = FluidRegistry.getFluid("obsidian.molten");
TRepo.moltenObsidian = new TConstructFluid(TRepo.moltenObsidianFluid, Material.lava, "liquid_obsidian").setBlockName("fluid.molten.obsidian");
GameRegistry.registerBlock(TRepo.moltenObsidian, "fluid.molten.obsidian");
TRepo.moltenObsidianFluid.setBlock(TRepo.moltenObsidian).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenObsidianFluid, 1000), new ItemStack(TRepo.buckets, 1, 11), new ItemStack(Items.bucket)));
TRepo.moltenSteelFluid = new Fluid("steel.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenSteelFluid))
TRepo.moltenSteelFluid = FluidRegistry.getFluid("steel.molten");
TRepo.moltenSteel = new TConstructFluid(TRepo.moltenSteelFluid, Material.lava, "liquid_steel").setBlockName("fluid.molten.steel");
GameRegistry.registerBlock(TRepo.moltenSteel, "fluid.molten.steel");
TRepo.moltenSteelFluid.setBlock(TRepo.moltenSteel).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenSteelFluid, 1000), new ItemStack(TRepo.buckets, 1, 12), new ItemStack(Items.bucket)));
TRepo.moltenGlassFluid = new Fluid("glass.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenGlassFluid))
TRepo.moltenGlassFluid = FluidRegistry.getFluid("glass.molten");
TRepo.moltenGlass = new TConstructFluid(TRepo.moltenGlassFluid, Material.lava, "liquid_glass", true).setBlockName("fluid.molten.glass");
GameRegistry.registerBlock(TRepo.moltenGlass, "fluid.molten.glass");
TRepo.moltenGlassFluid.setBlock(TRepo.moltenGlass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenGlassFluid, 1000), new ItemStack(TRepo.buckets, 1, 13), new ItemStack(Items.bucket)));
TRepo.moltenStoneFluid = new Fluid("stone.seared");
if (!FluidRegistry.registerFluid(TRepo.moltenStoneFluid))
TRepo.moltenStoneFluid = FluidRegistry.getFluid("stone.seared");
TRepo.moltenStone = new TConstructFluid(TRepo.moltenStoneFluid, Material.lava, "liquid_stone").setBlockName("molten.stone");
GameRegistry.registerBlock(TRepo.moltenStone, "molten.stone");
TRepo.moltenStoneFluid.setBlock(TRepo.moltenStone).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenStoneFluid, 1000), new ItemStack(TRepo.buckets, 1, 14), new ItemStack(Items.bucket)));
TRepo.moltenEmeraldFluid = new Fluid("emerald.liquid");
if (!FluidRegistry.registerFluid(TRepo.moltenEmeraldFluid))
TRepo.moltenEmeraldFluid = FluidRegistry.getFluid("emerald.liquid");
TRepo.moltenEmerald = new TConstructFluid(TRepo.moltenEmeraldFluid, Material.water, "liquid_villager").setBlockName("molten.emerald");
GameRegistry.registerBlock(TRepo.moltenEmerald, "molten.emerald");
TRepo.moltenEmeraldFluid.setBlock(TRepo.moltenEmerald).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenEmeraldFluid, 1000), new ItemStack(TRepo.buckets, 1, 15), new ItemStack(Items.bucket)));
TRepo.bloodFluid = new Fluid("blood");
if (!FluidRegistry.registerFluid(TRepo.bloodFluid))
TRepo.bloodFluid = FluidRegistry.getFluid("blood");
TRepo.blood = new BloodBlock(TRepo.bloodFluid, Material.water, "liquid_cow").setBlockName("liquid.blood");
GameRegistry.registerBlock(TRepo.blood, "liquid.blood");
TRepo.bloodFluid.setBlock(TRepo.blood).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.bloodFluid, 1000), new ItemStack(TRepo.buckets, 1, 16), new ItemStack(Items.bucket)));
TRepo.moltenNickelFluid = new Fluid("nickel.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenNickelFluid))
TRepo.moltenNickelFluid = FluidRegistry.getFluid("nickel.molten");
TRepo.moltenNickel = new TConstructFluid(TRepo.moltenNickelFluid, Material.lava, "liquid_ferrous").setBlockName("fluid.molten.nickel");
GameRegistry.registerBlock(TRepo.moltenNickel, "fluid.molten.nickel");
TRepo.moltenNickelFluid.setBlock(TRepo.moltenNickel).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenNickelFluid, 1000), new ItemStack(TRepo.buckets, 1, 17), new ItemStack(Items.bucket)));
TRepo.moltenLeadFluid = new Fluid("lead.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenLeadFluid))
TRepo.moltenLeadFluid = FluidRegistry.getFluid("lead.molten");
TRepo.moltenLead = new TConstructFluid(TRepo.moltenLeadFluid, Material.lava, "liquid_lead").setBlockName("fluid.molten.lead");
GameRegistry.registerBlock(TRepo.moltenLead, "fluid.molten.lead");
TRepo.moltenLeadFluid.setBlock(TRepo.moltenLead).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenLeadFluid, 1000), new ItemStack(TRepo.buckets, 1, 18), new ItemStack(Items.bucket)));
TRepo.moltenSilverFluid = new Fluid("silver.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenSilverFluid))
TRepo.moltenSilverFluid = FluidRegistry.getFluid("silver.molten");
TRepo.moltenSilver = new TConstructFluid(TRepo.moltenSilverFluid, Material.lava, "liquid_silver").setBlockName("fluid.molten.silver");
GameRegistry.registerBlock(TRepo.moltenSilver, "fluid.molten.silver");
TRepo.moltenSilverFluid.setBlock(TRepo.moltenSilver).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenSilverFluid, 1000), new ItemStack(TRepo.buckets, 1, 19), new ItemStack(Items.bucket)));
TRepo.moltenShinyFluid = new Fluid("platinum.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenShinyFluid))
TRepo.moltenShinyFluid = FluidRegistry.getFluid("platinum.molten");
TRepo.moltenShiny = new TConstructFluid(TRepo.moltenShinyFluid, Material.lava, "liquid_shiny").setBlockName("fluid.molten.shiny");
GameRegistry.registerBlock(TRepo.moltenShiny, "fluid.molten.shiny");
TRepo.moltenShinyFluid.setBlock(TRepo.moltenShiny).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenShinyFluid, 1000), new ItemStack(TRepo.buckets, 1, 20), new ItemStack(Items.bucket)));
TRepo.moltenInvarFluid = new Fluid("invar.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenInvarFluid))
TRepo.moltenInvarFluid = FluidRegistry.getFluid("invar.molten");
TRepo.moltenInvar = new TConstructFluid(TRepo.moltenInvarFluid, Material.lava, "liquid_invar").setBlockName("fluid.molten.invar");
GameRegistry.registerBlock(TRepo.moltenInvar, "fluid.molten.invar");
TRepo.moltenInvarFluid.setBlock(TRepo.moltenInvar).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenInvarFluid, 1000), new ItemStack(TRepo.buckets, 1, 21), new ItemStack(Items.bucket)));
TRepo.moltenElectrumFluid = new Fluid("electrum.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenElectrumFluid))
TRepo.moltenElectrumFluid = FluidRegistry.getFluid("electrum.molten");
TRepo.moltenElectrum = new TConstructFluid(TRepo.moltenElectrumFluid, Material.lava, "liquid_electrum").setBlockName("fluid.molten.electrum");
GameRegistry.registerBlock(TRepo.moltenElectrum, "fluid.molten.electrum");
TRepo.moltenElectrumFluid.setBlock(TRepo.moltenElectrum).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenElectrumFluid, 1000), new ItemStack(TRepo.buckets, 1, 22), new ItemStack(Items.bucket)));
TRepo.moltenEnderFluid = new Fluid("ender");
if (!FluidRegistry.registerFluid(TRepo.moltenEnderFluid))
{
TRepo.moltenEnderFluid = FluidRegistry.getFluid("ender");
TRepo.moltenEnder = TRepo.moltenEnderFluid.getBlock();
if (TRepo.moltenEnder == null)
TConstruct.logger.info("Molten ender block missing!");
}
else
{
TRepo.moltenEnder = new TConstructFluid(TRepo.moltenEnderFluid, Material.water, "liquid_ender").setBlockName("fluid.ender");
GameRegistry.registerBlock(TRepo.moltenEnder, "fluid.ender");
TRepo.moltenEnderFluid.setBlock(TRepo.moltenEnder).setDensity(3000).setViscosity(6000);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenEnderFluid, 1000), new ItemStack(TRepo.buckets, 1, 23), new ItemStack(Items.bucket)));
}
// Slime
TRepo.slimeStep = new StepSoundSlime("mob.slime", 1.0f, 1.0f);
TRepo.blueSlimeFluid = new Fluid("slime.blue");
if (!FluidRegistry.registerFluid(TRepo.blueSlimeFluid))
TRepo.blueSlimeFluid = FluidRegistry.getFluid("slime.blue");
TRepo.slimePool = new SlimeFluid(TRepo.blueSlimeFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(TRepo.slimeStep).setBlockName("liquid.slime");
GameRegistry.registerBlock(TRepo.slimePool, "liquid.slime");
TRepo.blueSlimeFluid.setBlock(TRepo.slimePool);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.blueSlimeFluid, 1000), new ItemStack(TRepo.buckets, 1, 24), new ItemStack(Items.bucket)));
// Glue
TRepo.glueFluid = new Fluid("glue").setDensity(6000).setViscosity(6000).setTemperature(200);
if (!FluidRegistry.registerFluid(TRepo.glueFluid))
TRepo.glueFluid = FluidRegistry.getFluid("glue");
TRepo.glueFluidBlock = new GlueFluid(TRepo.glueFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(TRepo.slimeStep).setBlockName("liquid.glue");
GameRegistry.registerBlock(TRepo.glueFluidBlock, "liquid.glue");
TRepo.glueFluid.setBlock(TRepo.glueFluidBlock);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.glueFluid, 1000), new ItemStack(TRepo.buckets, 1, 26), new ItemStack(Items.bucket)));
TRepo.pigIronFluid = new Fluid("pigiron.molten");
if (!FluidRegistry.registerFluid(TRepo.pigIronFluid))
TRepo.pigIronFluid = FluidRegistry.getFluid("pigiron.molten");
else
TRepo.pigIronFluid.setDensity(3000).setViscosity(6000).setTemperature(1300);
TRepo.fluids = new Fluid[] { TRepo.moltenIronFluid, TRepo.moltenGoldFluid, TRepo.moltenCopperFluid, TRepo.moltenTinFluid, TRepo.moltenAluminumFluid, TRepo.moltenCobaltFluid,
TRepo.moltenArditeFluid, TRepo.moltenBronzeFluid, TRepo.moltenAlubrassFluid, TRepo.moltenManyullynFluid, TRepo.moltenAlumiteFluid, TRepo.moltenObsidianFluid, TRepo.moltenSteelFluid,
TRepo.moltenGlassFluid, TRepo.moltenStoneFluid, TRepo.moltenEmeraldFluid, TRepo.bloodFluid, TRepo.moltenNickelFluid, TRepo.moltenLeadFluid, TRepo.moltenSilverFluid,
TRepo.moltenShinyFluid, TRepo.moltenInvarFluid, TRepo.moltenElectrumFluid, TRepo.moltenEnderFluid, TRepo.blueSlimeFluid, TRepo.glueFluid, TRepo.pigIronFluid };
TRepo.fluidBlocks = new Block[] { TRepo.moltenIron, TRepo.moltenGold, TRepo.moltenCopper, TRepo.moltenTin, TRepo.moltenAluminum, TRepo.moltenCobalt, TRepo.moltenArdite, TRepo.moltenBronze,
TRepo.moltenAlubrass, TRepo.moltenManyullyn, TRepo.moltenAlumite, TRepo.moltenObsidian, TRepo.moltenSteel, TRepo.moltenGlass, TRepo.moltenStone, TRepo.moltenEmerald, TRepo.blood,
TRepo.moltenNickel, TRepo.moltenLead, TRepo.moltenSilver, TRepo.moltenShiny, TRepo.moltenInvar, TRepo.moltenElectrum, TRepo.moltenEnder, TRepo.slimePool, TRepo.glueFluidBlock };
// Slime Islands
TRepo.slimeGel = new SlimeGel().setStepSound(TRepo.slimeStep).setLightOpacity(0).setBlockName("slime.gel");
TRepo.slimeGrass = new SlimeGrass().setStepSound(Block.soundTypeGrass).setLightOpacity(0).setBlockName("slime.grass");
TRepo.slimeTallGrass = new SlimeTallGrass().setStepSound(Block.soundTypeGrass).setBlockName("slime.grass.tall");
TRepo.slimeLeaves = (SlimeLeaves) new SlimeLeaves().setStepSound(TRepo.slimeStep).setLightOpacity(0).setBlockName("slime.leaves");
TRepo.slimeSapling = (SlimeSapling) new SlimeSapling().setStepSound(TRepo.slimeStep).setBlockName("slime.sapling");
TRepo.slimeChannel = new ConveyorBase(Material.water, "greencurrent").setHardness(0.3f).setStepSound(TRepo.slimeStep).setBlockName("slime.channel");
TRepo.bloodChannel = new ConveyorBase(Material.water, "liquid_cow").setHardness(0.3f).setStepSound(TRepo.slimeStep).setBlockName("blood.channel");
TRepo.slimePad = new SlimePad(Material.cloth).setStepSound(TRepo.slimeStep).setHardness(0.3f).setBlockName("slime.pad");
// Decoration
TRepo.stoneTorch = new StoneTorch().setBlockName("decoration.stonetorch");
TRepo.stoneLadder = new StoneLadder().setBlockName("decoration.stoneladder");
TRepo.multiBrick = new MultiBrick().setBlockName("Decoration.Brick");
TRepo.multiBrickFancy = new MultiBrickFancy().setBlockName("Decoration.BrickFancy");
// Ores
String[] berryOres = new String[] { "berry_iron", "berry_gold", "berry_copper", "berry_tin", "berry_iron_ripe", "berry_gold_ripe", "berry_copper_ripe", "berry_tin_ripe" };
TRepo.oreBerry = (OreberryBush) new OreberryBush(berryOres, 0, 4, new String[] { "oreIron", "oreGold", "oreCopper", "oreTin" }).setBlockName("ore.berries.one");
String[] berryOresTwo = new String[] { "berry_aluminum", "berry_essence", "", "", "berry_aluminum_ripe", "berry_essence_ripe", "", "" };
TRepo.oreBerrySecond = (OreberryBush) new OreberryBushEssence(berryOresTwo, 4, 2, new String[] { "oreAluminum", "oreSilver" }).setBlockName("ore.berries.two");
String[] oreTypes = new String[] { "nether_slag", "nether_cobalt", "nether_ardite", "ore_copper", "ore_tin", "ore_aluminum", "ore_slag" };
TRepo.oreSlag = new MetalOre(Material.rock, 10.0F, oreTypes).setBlockName("tconstruct.stoneore");
TRepo.oreSlag.setHarvestLevel("pickaxe", 4, 1);
TRepo.oreSlag.setHarvestLevel("pickaxe", 4, 2);
TRepo.oreSlag.setHarvestLevel("pickaxe", 1, 3);
TRepo.oreSlag.setHarvestLevel("pickaxe", 1, 4);
TRepo.oreSlag.setHarvestLevel("pickaxe", 1, 5);
TRepo.oreGravel = new GravelOre().setBlockName("GravelOre").setBlockName("tconstruct.gravelore");
TRepo.oreGravel.setHarvestLevel("shovel", 1, 0);
TRepo.oreGravel.setHarvestLevel("shovel", 2, 1);
TRepo.oreGravel.setHarvestLevel("shovel", 1, 2);
TRepo.oreGravel.setHarvestLevel("shovel", 1, 3);
TRepo.oreGravel.setHarvestLevel("shovel", 1, 4);
TRepo.oreGravel.setHarvestLevel("shovel", 4, 5);
TRepo.speedBlock = new SpeedBlock().setBlockName("SpeedBlock");
// Glass
TRepo.clearGlass = new GlassBlockConnected("clear", false).setBlockName("GlassBlock");
TRepo.clearGlass.stepSound = Block.soundTypeGlass;
TRepo.glassPane = new GlassPaneConnected("clear", false);
TRepo.stainedGlassClear = new GlassBlockConnectedMeta("stained", true, "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue",
"brown", "green", "red", "black").setBlockName("GlassBlock.StainedClear");
TRepo.stainedGlassClear.stepSound = Block.soundTypeGlass;
TRepo.stainedGlassClearPane = new GlassPaneStained();
// Rail
TRepo.woodenRail = new WoodRail().setStepSound(Block.soundTypeWood).setCreativeTab(TConstructRegistry.blockTab).setBlockName("rail.wood");
}
void registerItems ()
{
TRepo.titleIcon = new TitleIcon().setUnlocalizedName("tconstruct.titleicon");
GameRegistry.registerItem(TRepo.titleIcon, "titleIcon");
String[] blanks = new String[] { "blank_pattern", "blank_cast", "blank_cast" };
TRepo.blankPattern = new CraftingItem(blanks, blanks, "materials/", "tinker", TConstructRegistry.materialTab).setUnlocalizedName("tconstruct.Pattern");
GameRegistry.registerItem(TRepo.blankPattern, "blankPattern");
TRepo.materials = new MaterialItem().setUnlocalizedName("tconstruct.Materials");
TRepo.toolRod = new ToolPart("_rod", "ToolRod").setUnlocalizedName("tconstruct.ToolRod");
TRepo.toolShard = new ToolShard("_chunk").setUnlocalizedName("tconstruct.ToolShard");
TRepo.woodPattern = new Pattern("pattern_", "materials/").setUnlocalizedName("tconstruct.Pattern");
TRepo.metalPattern = new MetalPattern("cast_", "materials/").setUnlocalizedName("tconstruct.MetalPattern");
// armorPattern = new ArmorPattern(PHConstruct.armorPattern,
// "armorcast_",
// "materials/").setUnlocalizedName("tconstruct.ArmorPattern");
GameRegistry.registerItem(TRepo.materials, "materials");
GameRegistry.registerItem(TRepo.woodPattern, "woodPattern");
GameRegistry.registerItem(TRepo.metalPattern, "metalPattern");
// GameRegistry.registerItem(TRepo.armorPattern, "armorPattern");
TConstructRegistry.addItemToDirectory("blankPattern", TRepo.blankPattern);
TConstructRegistry.addItemToDirectory("woodPattern", TRepo.woodPattern);
TConstructRegistry.addItemToDirectory("metalPattern", TRepo.metalPattern);
// TConstructRegistry.addItemToDirectory("armorPattern", armorPattern);
String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead",
"knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" };
for (int i = 1; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Pattern", new ItemStack(TRepo.woodPattern, 1, i));
}
for (int i = 0; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Cast", new ItemStack(TRepo.metalPattern, 1, i));
}
/*
* String[] armorPartTypes = { "helmet", "chestplate", "leggings",
* "boots" }; for (int i = 1; i < armorPartTypes.length; i++) {
* TConstructRegistry.addItemStackToDirectory(armorPartTypes[i] +
* "Cast", new ItemStack(armorPattern, 1, i)); }
*/
TRepo.manualBook = new Manual();
GameRegistry.registerItem(TRepo.manualBook, "manualBook");
TRepo.buckets = new FilledBucket(BlockUtils.getBlockFromItem(TRepo.buckets));
GameRegistry.registerItem(TRepo.buckets, "buckets");
TRepo.pickaxe = new Pickaxe();
TRepo.shovel = new Shovel();
TRepo.hatchet = new Hatchet();
TRepo.broadsword = new Broadsword();
TRepo.longsword = new Longsword();
TRepo.rapier = new Rapier();
TRepo.dagger = new Dagger();
TRepo.cutlass = new Cutlass();
TRepo.frypan = new FryingPan();
TRepo.battlesign = new BattleSign();
TRepo.mattock = new Mattock();
TRepo.chisel = new Chisel();
TRepo.lumberaxe = new LumberAxe();
TRepo.cleaver = new Cleaver();
TRepo.scythe = new Scythe();
TRepo.excavator = new Excavator();
TRepo.hammer = new Hammer();
TRepo.battleaxe = new Battleaxe();
TRepo.shortbow = new Shortbow();
TRepo.arrow = new Arrow();
Item[] tools = { TRepo.pickaxe, TRepo.shovel, TRepo.hatchet, TRepo.broadsword, TRepo.longsword, TRepo.rapier, TRepo.dagger, TRepo.cutlass, TRepo.frypan, TRepo.battlesign, TRepo.mattock,
TRepo.chisel, TRepo.lumberaxe, TRepo.cleaver, TRepo.scythe, TRepo.excavator, TRepo.hammer, TRepo.battleaxe, TRepo.shortbow, TRepo.arrow };
String[] toolStrings = { "pickaxe", "shovel", "hatchet", "broadsword", "longsword", "rapier", "dagger", "cutlass", "frypan", "battlesign", "mattock", "chisel", "lumberaxe", "cleaver",
"scythe", "excavator", "hammer", "battleaxe", "shortbow", "arrow" };
for (int i = 0; i < tools.length; i++)
{
GameRegistry.registerItem(tools[i], toolStrings[i]); // 1.7 compat
TConstructRegistry.addItemToDirectory(toolStrings[i], tools[i]);
}
TRepo.potionLauncher = new PotionLauncher().setUnlocalizedName("tconstruct.PotionLauncher");
GameRegistry.registerItem(TRepo.potionLauncher, "potionLauncher");
TRepo.pickaxeHead = new ToolPart("_pickaxe_head", "PickHead").setUnlocalizedName("tconstruct.PickaxeHead");
TRepo.shovelHead = new ToolPart("_shovel_head", "ShovelHead").setUnlocalizedName("tconstruct.ShovelHead");
TRepo.hatchetHead = new ToolPart("_axe_head", "AxeHead").setUnlocalizedName("tconstruct.AxeHead");
TRepo.binding = new ToolPart("_binding", "Binding").setUnlocalizedName("tconstruct.Binding");
TRepo.toughBinding = new ToolPart("_toughbind", "ToughBind").setUnlocalizedName("tconstruct.ThickBinding");
TRepo.toughRod = new ToolPart("_toughrod", "ToughRod").setUnlocalizedName("tconstruct.ThickRod");
TRepo.largePlate = new ToolPart("_largeplate", "LargePlate").setUnlocalizedName("tconstruct.LargePlate");
TRepo.swordBlade = new ToolPart("_sword_blade", "SwordBlade").setUnlocalizedName("tconstruct.SwordBlade");
TRepo.wideGuard = new ToolPart("_large_guard", "LargeGuard").setUnlocalizedName("tconstruct.LargeGuard");
TRepo.handGuard = new ToolPart("_medium_guard", "MediumGuard").setUnlocalizedName("tconstruct.MediumGuard");
TRepo.crossbar = new ToolPart("_crossbar", "Crossbar").setUnlocalizedName("tconstruct.Crossbar");
TRepo.knifeBlade = new ToolPart("_knife_blade", "KnifeBlade").setUnlocalizedName("tconstruct.KnifeBlade");
TRepo.fullGuard = new ToolPartHidden("_full_guard", "FullGuard").setUnlocalizedName("tconstruct.FullGuard");
TRepo.frypanHead = new ToolPart("_frypan_head", "FrypanHead").setUnlocalizedName("tconstruct.FrypanHead");
TRepo.signHead = new ToolPart("_battlesign_head", "SignHead").setUnlocalizedName("tconstruct.SignHead");
TRepo.chiselHead = new ToolPart("_chisel_head", "ChiselHead").setUnlocalizedName("tconstruct.ChiselHead");
TRepo.scytheBlade = new ToolPart("_scythe_head", "ScytheHead").setUnlocalizedName("tconstruct.ScytheBlade");
TRepo.broadAxeHead = new ToolPart("_lumberaxe_head", "LumberHead").setUnlocalizedName("tconstruct.LumberHead");
TRepo.excavatorHead = new ToolPart("_excavator_head", "ExcavatorHead").setUnlocalizedName("tconstruct.ExcavatorHead");
TRepo.largeSwordBlade = new ToolPart("_large_sword_blade", "LargeSwordBlade").setUnlocalizedName("tconstruct.LargeSwordBlade");
TRepo.hammerHead = new ToolPart("_hammer_head", "HammerHead").setUnlocalizedName("tconstruct.HammerHead");
TRepo.bowstring = new Bowstring().setUnlocalizedName("tconstruct.Bowstring");
TRepo.arrowhead = new ToolPart("_arrowhead", "ArrowHead").setUnlocalizedName("tconstruct.Arrowhead");
TRepo.fletching = new Fletching().setUnlocalizedName("tconstruct.Fletching");
Item[] toolParts = { TRepo.toolRod, TRepo.toolShard, TRepo.pickaxeHead, TRepo.shovelHead, TRepo.hatchetHead, TRepo.binding, TRepo.toughBinding, TRepo.toughRod, TRepo.largePlate,
TRepo.swordBlade, TRepo.wideGuard, TRepo.handGuard, TRepo.crossbar, TRepo.knifeBlade, TRepo.fullGuard, TRepo.frypanHead, TRepo.signHead, TRepo.chiselHead, TRepo.scytheBlade,
TRepo.broadAxeHead, TRepo.excavatorHead, TRepo.largeSwordBlade, TRepo.hammerHead, TRepo.bowstring, TRepo.fletching, TRepo.arrowhead };
String[] toolPartStrings = { "toolRod", "toolShard", "pickaxeHead", "shovelHead", "hatchetHead", "binding", "toughBinding", "toughRod", "heavyPlate", "swordBlade", "wideGuard", "handGuard",
"crossbar", "knifeBlade", "fullGuard", "frypanHead", "signHead", "chiselHead", "scytheBlade", "broadAxeHead", "excavatorHead", "largeSwordBlade", "hammerHead", "bowstring",
"fletching", "arrowhead" };
for (int i = 0; i < toolParts.length; i++)
{
GameRegistry.registerItem(toolParts[i], toolPartStrings[i]); // 1.7
// compat
TConstructRegistry.addItemToDirectory(toolPartStrings[i], toolParts[i]);
}
TRepo.diamondApple = new DiamondApple().setUnlocalizedName("tconstruct.apple.diamond");
TRepo.strangeFood = new StrangeFood().setUnlocalizedName("tconstruct.strangefood");
TRepo.oreBerries = new OreBerries().setUnlocalizedName("oreberry");
GameRegistry.registerItem(TRepo.diamondApple, "diamondApple");
GameRegistry.registerItem(TRepo.strangeFood, "strangeFood");
GameRegistry.registerItem(TRepo.oreBerries, "oreBerries");
boolean foodOverhaul = false;
if (Loader.isModLoaded("HungerOverhaul") || Loader.isModLoaded("fc_food"))
{
foodOverhaul = true;
}
TRepo.jerky = new Jerky(foodOverhaul).setUnlocalizedName("tconstruct.jerky");
GameRegistry.registerItem(TRepo.jerky, "jerky");
// Wearables
// heavyHelmet = new TArmorBase(PHConstruct.heavyHelmet,
// 0).setUnlocalizedName("tconstruct.HeavyHelmet");
TRepo.heartCanister = new HeartCanister().setUnlocalizedName("tconstruct.canister");
// heavyBoots = new TArmorBase(PHConstruct.heavyBoots,
// 3).setUnlocalizedName("tconstruct.HeavyBoots");
// glove = new
// Glove(PHConstruct.glove).setUnlocalizedName("tconstruct.Glove");
TRepo.knapsack = new Knapsack().setUnlocalizedName("tconstruct.storage");
TRepo.goldHead = new GoldenHead(4, 1.2F, false).setAlwaysEdible().setPotionEffect(Potion.regeneration.id, 10, 0, 1.0F).setUnlocalizedName("goldenhead");
// GameRegistry.registerItem(TRepo.heavyHelmet, "heavyHelmet");
GameRegistry.registerItem(TRepo.heartCanister, "heartCanister");
// GameRegistry.registerItem(TRepo.heavyBoots, "heavyBoots");
// GameRegistry.registerItem(TRepo.glove, "glove");
GameRegistry.registerItem(TRepo.knapsack, "knapsack");
GameRegistry.registerItem(TRepo.goldHead, "goldHead");
TRepo.creativeModifier = new CreativeModifier().setUnlocalizedName("tconstruct.modifier.creative");
GameRegistry.registerItem(TRepo.creativeModifier, "creativeModifier");
LiquidCasting basinCasting = TConstruct.getBasinCasting();
TRepo.materialWood = EnumHelper.addArmorMaterial("WOOD", 2, new int[] { 1, 2, 2, 1 }, 3);
TRepo.helmetWood = new ArmorBasic(TRepo.materialWood, 0, "wood").setUnlocalizedName("tconstruct.helmetWood");
TRepo.chestplateWood = new ArmorBasic(TRepo.materialWood, 1, "wood").setUnlocalizedName("tconstruct.chestplateWood");
TRepo.leggingsWood = new ArmorBasic(TRepo.materialWood, 2, "wood").setUnlocalizedName("tconstruct.leggingsWood");
TRepo.bootsWood = new ArmorBasic(TRepo.materialWood, 3, "wood").setUnlocalizedName("tconstruct.bootsWood");
GameRegistry.registerItem(TRepo.helmetWood, "helmetWood");
GameRegistry.registerItem(TRepo.chestplateWood, "chestplateWood");
GameRegistry.registerItem(TRepo.leggingsWood, "leggingsWood");
GameRegistry.registerItem(TRepo.bootsWood, "bootsWood");
TRepo.exoGoggles = new ExoArmor(EnumArmorPart.HELMET, "exosuit").setUnlocalizedName("tconstruct.exoGoggles");
TRepo.exoChest = new ExoArmor(EnumArmorPart.CHEST, "exosuit").setUnlocalizedName("tconstruct.exoChest");
TRepo.exoPants = new ExoArmor(EnumArmorPart.PANTS, "exosuit").setUnlocalizedName("tconstruct.exoPants");
TRepo.exoShoes = new ExoArmor(EnumArmorPart.SHOES, "exosuit").setUnlocalizedName("tconstruct.exoShoes");
GameRegistry.registerItem(TRepo.exoGoggles, "helmetExo");
GameRegistry.registerItem(TRepo.exoChest, "chestplateExo");
GameRegistry.registerItem(TRepo.exoPants, "leggingsExo");
GameRegistry.registerItem(TRepo.exoShoes, "bootsExo");
String[] materialStrings = { "paperStack", "greenSlimeCrystal", "searedBrick", "ingotCobalt", "ingotArdite", "ingotManyullyn", "mossBall", "lavaCrystal", "necroticBone", "ingotCopper",
"ingotTin", "ingotAluminum", "rawAluminum", "ingotBronze", "ingotAluminumBrass", "ingotAlumite", "ingotSteel", "blueSlimeCrystal", "ingotObsidian", "nuggetIron", "nuggetCopper",
"nuggetTin", "nuggetAluminum", "nuggetSilver", "nuggetAluminumBrass", "silkyCloth", "silkyJewel", "nuggetObsidian", "nuggetCobalt", "nuggetArdite", "nuggetManyullyn", "nuggetBronze",
"nuggetAlumite", "nuggetSteel", "ingotPigIron", "nuggetPigIron", "glueball" };
for (int i = 0; i < materialStrings.length; i++)
{
TConstructRegistry.addItemStackToDirectory(materialStrings[i], new ItemStack(TRepo.materials, 1, i));
}
String[] oreberries = { "Iron", "Gold", "Copper", "Tin", "Aluminum", "Essence" };
for (int i = 0; i < oreberries.length; i++)
{
TConstructRegistry.addItemStackToDirectory("oreberry" + oreberries[i], new ItemStack(TRepo.oreBerries, 1, i));
}
TConstructRegistry.addItemStackToDirectory("diamondApple", new ItemStack(TRepo.diamondApple, 1, 0));
TConstructRegistry.addItemStackToDirectory("blueSlimeFood", new ItemStack(TRepo.strangeFood, 1, 0));
TConstructRegistry.addItemStackToDirectory("canisterEmpty", new ItemStack(TRepo.heartCanister, 1, 0));
TConstructRegistry.addItemStackToDirectory("miniRedHeart", new ItemStack(TRepo.heartCanister, 1, 1));
TConstructRegistry.addItemStackToDirectory("canisterRedHeart", new ItemStack(TRepo.heartCanister, 1, 2));
// Vanilla stack sizes
Items.wooden_door.setMaxStackSize(16);
Items.iron_door.setMaxStackSize(16);
Items.boat.setMaxStackSize(16);
Items.minecart.setMaxStackSize(3);
// Items.minecartEmpty.setMaxStackSize(3);
// Items.minecartCrate.setMaxStackSize(3);
// Items.minecartPowered.setMaxStackSize(3);
Items.cake.setMaxStackSize(16);
// Block.torchWood.setTickRandomly(false);
}
void registerMaterials ()
{
TConstructRegistry.addToolMaterial(0, "Wood", "Wooden ", 0, 59, 200, 0, 1.0F, 0, 0f, "\u00A7e", "");
TConstructRegistry.addToolMaterial(1, "Stone", 1, 131, 400, 1, 0.5F, 0, 1f, "", StatCollector.translateToLocal("materialtraits.stonebound"));
TConstructRegistry.addToolMaterial(2, "Iron", 2, 250, 600, 2, 1.3F, 1, 0f, "\u00A7f", "");
TConstructRegistry.addToolMaterial(3, "Flint", 1, 171, 525, 2, 0.7F, 0, 0f, "\u00A78", "");
TConstructRegistry.addToolMaterial(4, "Cactus", 1, 150, 500, 2, 1.0F, 0, -1f, "\u00A72", StatCollector.translateToLocal("materialtraits.jagged"));
TConstructRegistry.addToolMaterial(5, "Bone", 1, 200, 400, 1, 1.0F, 0, 0f, "\u00A7e", "");
TConstructRegistry.addToolMaterial(6, "Obsidian", 3, 89, 700, 2, 0.8F, 3, 0f, "\u00A7d", "");
TConstructRegistry.addToolMaterial(7, "Netherrack", 2, 131, 400, 1, 1.2F, 0, 1f, "\u00A74", StatCollector.translateToLocal("materialtraits.stonebound"));
TConstructRegistry.addToolMaterial(8, "Slime", 0, 500, 150, 0, 1.5F, 0, 0f, "\u00A7a", "");
TConstructRegistry.addToolMaterial(9, "Paper", 0, 30, 200, 0, 0.3F, 0, 0f, "\u00A7f", StatCollector.translateToLocal("materialtraits.writable"));
TConstructRegistry.addToolMaterial(10, "Cobalt", 4, 800, 1100, 3, 1.75F, 2, 0f, "\u00A73", "");
TConstructRegistry.addToolMaterial(11, "Ardite", 4, 600, 800, 3, 2.0F, 0, 2f, "\u00A74", StatCollector.translateToLocal("materialtraits.stonebound"));
TConstructRegistry.addToolMaterial(12, "Manyullyn", 5, 1200, 900, 4, 2.5F, 0, 0f, "\u00A75", "");
TConstructRegistry.addToolMaterial(13, "Copper", 1, 180, 500, 2, 1.15F, 0, 0f, "\u00A7c", "");
TConstructRegistry.addToolMaterial(14, "Bronze", 2, 350, 700, 2, 1.3F, 1, 0f, "\u00A76", "");
TConstructRegistry.addToolMaterial(15, "Alumite", 4, 550, 800, 3, 1.3F, 2, 0f, "\u00A7d", "");
TConstructRegistry.addToolMaterial(16, "Steel", 4, 750, 800, 3, 1.3F, 2, 0f, "", "");
TConstructRegistry.addToolMaterial(17, "BlueSlime", "Slime ", 0, 1200, 150, 0, 2.0F, 0, 0f, "\u00A7b", "");
TConstructRegistry.addToolMaterial(18, "PigIron", "Pig Iron ", 3, 250, 600, 2, 1.3F, 1, 0f, "\u00A7c", StatCollector.translateToLocal("materialtraits.tasty"));
TConstructRegistry.addBowMaterial(0, 384, 20, 1.0f); // Wood
TConstructRegistry.addBowMaterial(1, 10, 80, 0.2f); // Stone
TConstructRegistry.addBowMaterial(2, 576, 40, 1.2f); // Iron
TConstructRegistry.addBowMaterial(3, 10, 80, 0.2f); // Flint
TConstructRegistry.addBowMaterial(4, 384, 20, 1.0f); // Cactus
TConstructRegistry.addBowMaterial(5, 192, 30, 1.0f); // Bone
TConstructRegistry.addBowMaterial(6, 10, 80, 0.2f); // Obsidian
TConstructRegistry.addBowMaterial(7, 10, 80, 0.2f); // Netherrack
TConstructRegistry.addBowMaterial(8, 1536, 20, 1.2f); // Slime
TConstructRegistry.addBowMaterial(9, 48, 25, 0.5f); // Paper
TConstructRegistry.addBowMaterial(10, 1152, 40, 1.2f); // Cobalt
TConstructRegistry.addBowMaterial(11, 960, 40, 1.2f); // Ardite
TConstructRegistry.addBowMaterial(12, 1536, 40, 1.2f); // Manyullyn
TConstructRegistry.addBowMaterial(13, 384, 40, 1.2f); // Copper
TConstructRegistry.addBowMaterial(14, 576, 40, 1.2f); // Bronze
TConstructRegistry.addBowMaterial(15, 768, 40, 1.2f); // Alumite
TConstructRegistry.addBowMaterial(16, 768, 40, 1.2f); // Steel
TConstructRegistry.addBowMaterial(17, 576, 20, 1.2f); // Blue Slime
TConstructRegistry.addBowMaterial(18, 384, 20, 1.2f); // Slime
// Material ID, mass, fragility
TConstructRegistry.addArrowMaterial(0, 0.69F, 1.0F, 100F); // Wood
TConstructRegistry.addArrowMaterial(1, 2.5F, 5.0F, 100F); // Stone
TConstructRegistry.addArrowMaterial(2, 7.2F, 0.5F, 100F); // Iron
TConstructRegistry.addArrowMaterial(3, 2.65F, 1.0F, 100F); // Flint
TConstructRegistry.addArrowMaterial(4, 0.76F, 1.0F, 100F); // Cactus
TConstructRegistry.addArrowMaterial(5, 0.69F, 1.0F, 100); // Bone
TConstructRegistry.addArrowMaterial(6, 2.4F, 1.0F, 100F); // Obsidian
TConstructRegistry.addArrowMaterial(7, 3.5F, 1.0F, 100F); // Netherrack
TConstructRegistry.addArrowMaterial(8, 0.42F, 0.0F, 100F); // Slime
TConstructRegistry.addArrowMaterial(9, 1.1F, 3.0F, 90F); // Paper
TConstructRegistry.addArrowMaterial(10, 8.9F, 0.25F, 100F); // Cobalt
TConstructRegistry.addArrowMaterial(11, 7.2F, 0.25F, 100F); // Ardite
TConstructRegistry.addArrowMaterial(12, 10.6F, 0.1F, 100F); // Manyullyn
TConstructRegistry.addArrowMaterial(13, 8.96F, 0.5F, 100F); // Copper
TConstructRegistry.addArrowMaterial(14, 7.9F, 0.25F, 100F); // Bronze
TConstructRegistry.addArrowMaterial(15, 4.7F, 0.25F, 100F); // Alumite
TConstructRegistry.addArrowMaterial(16, 7.6F, 0.25F, 100F); // Steel
TConstructRegistry.addArrowMaterial(17, 0.42F, 0.0F, 100F); // Blue
// Slime
TConstructRegistry.addArrowMaterial(18, 6.8F, 0.5F, 100F); // Iron
TConstructRegistry.addBowstringMaterial(0, 2, new ItemStack(Items.string), new ItemStack(TRepo.bowstring, 1, 0), 1F, 1F, 1f); // String
TConstructRegistry.addFletchingMaterial(0, 2, new ItemStack(Items.feather), new ItemStack(TRepo.fletching, 1, 0), 100F, 0F, 0.05F); // Feather
for (int i = 0; i < 4; i++)
TConstructRegistry.addFletchingMaterial(1, 2, new ItemStack(Blocks.leaves, 1, i), new ItemStack(TRepo.fletching, 1, 1), 75F, 0F, 0.2F); // All four vanialla Leaves
TConstructRegistry.addFletchingMaterial(2, 2, new ItemStack(TRepo.materials, 1, 1), new ItemStack(TRepo.fletching, 1, 2), 100F, 0F, 0.12F); // Slime
TConstructRegistry.addFletchingMaterial(3, 2, new ItemStack(TRepo.materials, 1, 17), new ItemStack(TRepo.fletching, 1, 3), 100F, 0F, 0.12F); // BlueSlime
PatternBuilder pb = PatternBuilder.instance;
if (PHConstruct.enableTWood)
pb.registerFullMaterial(Blocks.planks, 2, StatCollector.translateToLocal("gui.partbuilder.material.wood"), new ItemStack(Items.stick), new ItemStack(Items.stick), 0);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.wood"), new ItemStack(Items.stick, 2), new ItemStack(Items.stick), 0);
if (PHConstruct.enableTStone)
{
pb.registerFullMaterial(Blocks.stone, 2, StatCollector.translateToLocal("gui.partbuilder.material.stone"), new ItemStack(TRepo.toolShard, 1, 1), new ItemStack(TRepo.toolRod, 1, 1), 1);
pb.registerMaterial(Blocks.cobblestone, 2, StatCollector.translateToLocal("gui.partbuilder.material.stone"));
}
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.stone"), new ItemStack(TRepo.toolShard, 1, 1), new ItemStack(TRepo.toolRod, 1, 1), 0);
pb.registerFullMaterial(Items.iron_ingot, 2, StatCollector.translateToLocal("gui.partbuilder.material.iron"), new ItemStack(TRepo.toolShard, 1, 2), new ItemStack(TRepo.toolRod, 1, 2), 2);
if (PHConstruct.enableTFlint)
pb.registerFullMaterial(Items.flint, 2, StatCollector.translateToLocal("gui.partbuilder.material.flint"), new ItemStack(TRepo.toolShard, 1, 3), new ItemStack(TRepo.toolRod, 1, 3), 3);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.flint"), new ItemStack(TRepo.toolShard, 1, 3), new ItemStack(TRepo.toolRod, 1, 3), 3);
if (PHConstruct.enableTCactus)
pb.registerFullMaterial(Blocks.cactus, 2, StatCollector.translateToLocal("gui.partbuilder.material.cactus"), new ItemStack(TRepo.toolShard, 1, 4), new ItemStack(TRepo.toolRod, 1, 4), 4);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.cactus"), new ItemStack(TRepo.toolShard, 1, 4), new ItemStack(TRepo.toolRod, 1, 4), 4);
if (PHConstruct.enableTBone)
pb.registerFullMaterial(Items.bone, 2, StatCollector.translateToLocal("gui.partbuilder.material.bone"), new ItemStack(Items.dye, 1, 15), new ItemStack(Items.bone), 5);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.bone"), new ItemStack(Items.dye, 1, 15), new ItemStack(Items.bone), 5);
pb.registerFullMaterial(Blocks.obsidian, 2, StatCollector.translateToLocal("gui.partbuilder.material.obsidian"), new ItemStack(TRepo.toolShard, 1, 6), new ItemStack(TRepo.toolRod, 1, 6), 6);
pb.registerMaterial(new ItemStack(TRepo.materials, 1, 18), 2, StatCollector.translateToLocal("gui.partbuilder.material.obsidian"));
if (PHConstruct.enableTNetherrack)
pb.registerFullMaterial(Blocks.netherrack, 2, StatCollector.translateToLocal("gui.partbuilder.material.netherrack"), new ItemStack(TRepo.toolShard, 1, 7), new ItemStack(TRepo.toolRod, 1, 7), 7);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.netherrack"), new ItemStack(TRepo.toolShard, 1, 7), new ItemStack(TRepo.toolRod, 1, 7), 7);
if (PHConstruct.enableTSlime)
pb.registerFullMaterial(new ItemStack(TRepo.materials, 1, 1), 2, StatCollector.translateToLocal("gui.partbuilder.material.slime"), new ItemStack(TRepo.toolShard, 1, 8), new ItemStack(TRepo.toolRod, 1, 8), 8);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.slime"), new ItemStack(TRepo.toolShard, 1, 8), new ItemStack(TRepo.toolRod, 1, 17), 8);
if (PHConstruct.enableTPaper)
pb.registerFullMaterial(new ItemStack(TRepo.materials, 1, 0), 2, StatCollector.translateToLocal("gui.partbuilder.material.paper"), new ItemStack(Items.paper, 2), new ItemStack(TRepo.toolRod, 1, 9), 9);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.blueslime"), new ItemStack(Items.paper, 2), new ItemStack(TRepo.toolRod, 1, 9), 9);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.cobalt"), new ItemStack(TRepo.toolShard, 1, 10), new ItemStack(TRepo.toolRod, 1, 10), 10);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.ardite"), new ItemStack(TRepo.toolShard, 1, 11), new ItemStack(TRepo.toolRod, 1, 11), 11);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.manyullyn"), new ItemStack(TRepo.toolShard, 1, 12), new ItemStack(TRepo.toolRod, 1, 12), 12);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.copper"), new ItemStack(TRepo.toolShard, 1, 13), new ItemStack(TRepo.toolRod, 1, 13), 13);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.bronze"), new ItemStack(TRepo.toolShard, 1, 14), new ItemStack(TRepo.toolRod, 1, 14), 14);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.alumite"), new ItemStack(TRepo.toolShard, 1, 15), new ItemStack(TRepo.toolRod, 1, 15), 15);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.steel"), new ItemStack(TRepo.toolShard, 1, 16), new ItemStack(TRepo.toolRod, 1, 16), 16);
if (PHConstruct.enableTBlueSlime)
pb.registerFullMaterial(new ItemStack(TRepo.materials, 1, 17), 2, StatCollector.translateToLocal("gui.partbuilder.material.blueslime"), new ItemStack(TRepo.toolShard, 1, 17), new ItemStack(TRepo.toolRod, 1, 17), 17);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.blueslime"), new ItemStack(TRepo.toolShard, 1, 17), new ItemStack(TRepo.toolRod, 1, 17), 17);
pb.registerFullMaterial(new ItemStack(TRepo.materials, 1, 34), 2, StatCollector.translateToLocal("gui.partbuilder.material.pigiron"), new ItemStack(TRepo.toolShard, 1, 18), new ItemStack(TRepo.toolRod, 1, 18), 18);
pb.addToolPattern((IPattern) TRepo.woodPattern);
}
void addCraftingRecipes ()
{
TRecipes.addPartMapping();
TRecipes.addRecipesForToolBuilder();
TRecipes.addRecipesForTableCasting();
TRecipes.addRecipesForBasinCasting();
TRecipes.addRecipesForSmeltery();
TRecipes.addRecipesForChisel();
TRecipes.addRecipesForFurnace();
TRecipes.addRecipesForCraftingTable();
TRecipes.addRecipesForDryingRack();
}
void setupToolTabs ()
{
TConstructRegistry.materialTab.init(new ItemStack(TRepo.manualBook, 1, 0));
TConstructRegistry.partTab.init(new ItemStack(TRepo.titleIcon, 1, 255));
TConstructRegistry.blockTab.init(new ItemStack(TRepo.toolStationWood));
ItemStack tool = new ItemStack(TRepo.longsword, 1, 0);
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("InfiTool", new NBTTagCompound());
compound.getCompoundTag("InfiTool").setInteger("RenderHead", 2);
compound.getCompoundTag("InfiTool").setInteger("RenderHandle", 0);
compound.getCompoundTag("InfiTool").setInteger("RenderAccessory", 10);
tool.setTagCompound(compound);
// TConstruct.
TConstructRegistry.toolTab.init(tool);
}
public void addLoot ()
{
// Item, min, max, weight
ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(TRepo.heartCanister, 1, 1), 1, 1, 5));
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(TRepo.heartCanister, 1, 1), 1, 1, 10));
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_JUNGLE_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(TRepo.heartCanister, 1, 1), 1, 1, 10));
TRepo.tinkerHouseChest = new ChestGenHooks("TinkerHouse", new WeightedRandomChestContent[0], 3, 27);
TRepo.tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(TRepo.heartCanister, 1, 1), 1, 1, 1));
int[] validTypes = { 0, 1, 2, 3, 4, 5, 6, 8, 9, 13, 14, 17 };
Item[] partTypes = { TRepo.pickaxeHead, TRepo.shovelHead, TRepo.hatchetHead, TRepo.binding, TRepo.swordBlade, TRepo.wideGuard, TRepo.handGuard, TRepo.crossbar, TRepo.knifeBlade,
TRepo.frypanHead, TRepo.signHead, TRepo.chiselHead };
for (int partIter = 0; partIter < partTypes.length; partIter++)
{
for (int typeIter = 0; typeIter < validTypes.length; typeIter++)
{
TRepo.tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(partTypes[partIter], 1, validTypes[typeIter]), 1, 1, 15));
}
}
TRepo.tinkerHousePatterns = new ChestGenHooks("TinkerPatterns", new WeightedRandomChestContent[0], 5, 30);
for (int i = 0; i < 13; i++)
{
TRepo.tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(TRepo.woodPattern, 1, i + 1), 1, 3, 20));
}
TRepo.tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(TRepo.woodPattern, 1, 22), 1, 3, 40));
}
public static String[] liquidNames;
@Override
public int getBurnTime (ItemStack fuel)
{
if (fuel.getItem() == TRepo.materials && fuel.getItemDamage() == 7)
return 26400;
return 0;
}
public void addAchievements ()
{
HashMap<String, Achievement> achievements = TAchievements.achievements;
achievements.put("tconstruct:beginner", new Achievement("tconstruct:beginner", "tconstruct.beginner", 0, 0, TRepo.manualBook, null));// .setIndependent());
achievements.put("tconstruct:pattern", new Achievement("tconstruct:pattern", "tconstruct.pattern", 2, 1, TRepo.blankPattern, achievements.get("tconstruct:beginner")));
achievements.put("tconstruct:tinkerer", new Achievement("tconstruct:tinkerer", "tconstruct.tinkerer", 2, 2, new ItemStack(TRepo.titleIcon, 1, 4096), achievements.get("tconstruct:pattern")));
achievements.put("tconstruct:preparedFight",
new Achievement("tconstruct:preparedFight", "tconstruct.preparedFight", 1, 3, new ItemStack(TRepo.titleIcon, 1, 4097), achievements.get("tconstruct:tinkerer")));
achievements.put("tconstruct:proTinkerer",
new Achievement("tconstruct:proTinkerer", "tconstruct.proTinkerer", 4, 4, new ItemStack(TRepo.titleIcon, 1, 4098), achievements.get("tconstruct:tinkerer")).setSpecial());
achievements.put("tconstruct:smelteryMaker", new Achievement("tconstruct:smelteryMaker", "tconstruct.smelteryMaker", -2, -1, TRepo.smeltery, achievements.get("tconstruct:beginner")));
achievements.put("tconstruct:enemySlayer",
new Achievement("tconstruct:enemySlayer", "tconstruct.enemySlayer", 0, 5, new ItemStack(TRepo.titleIcon, 1, 4099), achievements.get("tconstruct:preparedFight")));
achievements.put("tconstruct:dualConvenience",
new Achievement("tconstruct:dualConvenience", "tconstruct.dualConvenience", 0, 7, new ItemStack(TRepo.titleIcon, 1, 4100), achievements.get("tconstruct:enemySlayer")).setSpecial());
achievements.put("tconstruct:doingItWrong",
new Achievement("tconstruct:doingItWrong", "tconstruct.doingItWrong", -2, -3, new ItemStack(TRepo.manualBook, 1, 2), achievements.get("tconstruct:smelteryMaker")));
achievements.put("tconstruct:betterCrafting",
new Achievement("tconstruct:betterCrafting", "tconstruct.betterCrafting", -2, 2, TRepo.craftingStationWood, achievements.get("tconstruct:beginner")));
}
}
| void registerBlocks ()
{
// Tool Station
TRepo.toolStationWood = new ToolStationBlock(Material.wood).setBlockName("ToolStation");
TRepo.toolForge = new ToolForgeBlock(Material.iron).setBlockName("ToolForge");
TRepo.craftingStationWood = new CraftingStationBlock(Material.wood).setBlockName("CraftingStation");
TRepo.craftingSlabWood = new CraftingSlab(Material.wood).setBlockName("CraftingSlab");
TRepo.furnaceSlab = new FurnaceSlab(Material.rock).setBlockName("FurnaceSlab");
TRepo.heldItemBlock = new EquipBlock(Material.wood).setBlockName("Frypan");
/* battlesignBlock = new BattlesignBlock(PHConstruct.battlesignBlock).setUnlocalizedName("Battlesign");
GameRegistry.registerBlock(battlesignBlock, "BattlesignBlock");
ameRegistry.registerTileEntity(BattlesignLogic.class, "BattlesignLogic");*/
TRepo.craftedSoil = new SoilBlock().setLightOpacity(0).setBlockName("TConstruct.Soil");
TRepo.craftedSoil.stepSound = Block.soundTypeGravel;
TRepo.searedSlab = new SearedSlab().setBlockName("SearedSlab");
TRepo.searedSlab.stepSound = Block.soundTypeStone;
TRepo.speedSlab = new SpeedSlab().setBlockName("SpeedSlab");
TRepo.speedSlab.stepSound = Block.soundTypeStone;
TRepo.metalBlock = new TMetalBlock(Material.iron, 10.0F).setBlockName("tconstruct.metalblock");
TRepo.metalBlock.stepSound = Block.soundTypeMetal;
TRepo.meatBlock = new MeatBlock().setBlockName("tconstruct.meatblock");
TRepo.glueBlock = new GlueBlock().setBlockName("GlueBlock").setCreativeTab(TConstructRegistry.blockTab);
TRepo.woolSlab1 = new SlabBase(Material.cloth, Blocks.wool, 0, 8).setBlockName("cloth");
TRepo.woolSlab1.setStepSound(Block.soundTypeCloth).setCreativeTab(CreativeTabs.tabDecorations);
TRepo.woolSlab2 = new SlabBase(Material.cloth, Blocks.wool, 8, 8).setBlockName("cloth");
TRepo.woolSlab2.setStepSound(Block.soundTypeCloth).setCreativeTab(CreativeTabs.tabDecorations);
// Smeltery
TRepo.smeltery = new SmelteryBlock().setBlockName("Smeltery");
TRepo.smelteryNether = new SmelteryBlock("nether").setBlockName("Smeltery");
TRepo.lavaTank = new LavaTankBlock().setBlockName("LavaTank");
TRepo.lavaTank.setStepSound(Block.soundTypeGlass);
TRepo.lavaTankNether = new LavaTankBlock("nether").setStepSound(Block.soundTypeGlass).setBlockName("LavaTank");
TRepo.searedBlock = new SearedBlock().setBlockName("SearedBlock");
TRepo.searedBlockNether = new SearedBlock("nether").setBlockName("SearedBlock");
TRepo.castingChannel = (new CastingChannelBlock()).setBlockName("CastingChannel");
TRepo.tankAir = new TankAirBlock(Material.leaves).setBlockUnbreakable().setBlockName("tconstruct.tank.air");
// Traps
TRepo.landmine = new BlockLandmine().setHardness(0.5F).setResistance(0F).setStepSound(Block.soundTypeMetal).setCreativeTab(CreativeTabs.tabRedstone).setBlockName("landmine");
TRepo.punji = new Punji().setBlockName("trap.punji");
TRepo.barricadeOak = new BarricadeBlock(Blocks.log, 0).setBlockName("trap.barricade.oak");
TRepo.barricadeSpruce = new BarricadeBlock(Blocks.log, 1).setBlockName("trap.barricade.spruce");
TRepo.barricadeBirch = new BarricadeBlock(Blocks.log, 2).setBlockName("trap.barricade.birch");
TRepo.barricadeJungle = new BarricadeBlock(Blocks.log, 3).setBlockName("trap.barricade.jungle");
TRepo.slimeExplosive = new SlimeExplosive().setHardness(0.0F).setStepSound(Block.soundTypeGrass).setBlockName("explosive.slime");
TRepo.dryingRack = new DryingRack().setBlockName("Armor.DryingRack");
// Liquids
TRepo.liquidMetal = new MaterialLiquid(MapColor.tntColor);
TRepo.moltenIronFluid = new Fluid("iron.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenIronFluid))
TRepo.moltenIronFluid = FluidRegistry.getFluid("iron.molten");
TRepo.moltenIron = new TConstructFluid(TRepo.moltenIronFluid, Material.lava, "liquid_iron").setBlockName("fluid.molten.iron");
GameRegistry.registerBlock(TRepo.moltenIron, "fluid.molten.iron");
TRepo.moltenIronFluid.setBlock(TRepo.moltenIron).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenIronFluid, 1000), new ItemStack(TRepo.buckets, 1, 0), new ItemStack(Items.bucket)));
TRepo.moltenGoldFluid = new Fluid("gold.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenGoldFluid))
TRepo.moltenGoldFluid = FluidRegistry.getFluid("gold.molten");
TRepo.moltenGold = new TConstructFluid(TRepo.moltenGoldFluid, Material.lava, "liquid_gold").setBlockName("fluid.molten.gold");
GameRegistry.registerBlock(TRepo.moltenGold, "fluid.molten.gold");
TRepo.moltenGoldFluid.setBlock(TRepo.moltenGold).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenGoldFluid, 1000), new ItemStack(TRepo.buckets, 1, 1), new ItemStack(Items.bucket)));
TRepo.moltenCopperFluid = new Fluid("copper.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenCopperFluid))
TRepo.moltenCopperFluid = FluidRegistry.getFluid("copper.molten");
TRepo.moltenCopper = new TConstructFluid(TRepo.moltenCopperFluid, Material.lava, "liquid_copper").setBlockName("fluid.molten.copper");
GameRegistry.registerBlock(TRepo.moltenCopper, "fluid.molten.copper");
TRepo.moltenCopperFluid.setBlock(TRepo.moltenCopper).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenCopperFluid, 1000), new ItemStack(TRepo.buckets, 1, 2), new ItemStack(Items.bucket)));
TRepo.moltenTinFluid = new Fluid("tin.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenTinFluid))
TRepo.moltenTinFluid = FluidRegistry.getFluid("tin.molten");
TRepo.moltenTin = new TConstructFluid(TRepo.moltenTinFluid, Material.lava, "liquid_tin").setBlockName("fluid.molten.tin");
GameRegistry.registerBlock(TRepo.moltenTin, "fluid.molten.tin");
TRepo.moltenTinFluid.setBlock(TRepo.moltenTin).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenTinFluid, 1000), new ItemStack(TRepo.buckets, 1, 3), new ItemStack(Items.bucket)));
TRepo.moltenAluminumFluid = new Fluid("aluminum.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenAluminumFluid))
TRepo.moltenAluminumFluid = FluidRegistry.getFluid("aluminum.molten");
TRepo.moltenAluminum = new TConstructFluid(TRepo.moltenAluminumFluid, Material.lava, "liquid_aluminum").setBlockName("fluid.molten.aluminum");
GameRegistry.registerBlock(TRepo.moltenAluminum, "fluid.molten.aluminum");
TRepo.moltenAluminumFluid.setBlock(TRepo.moltenAluminum).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenAluminumFluid, 1000), new ItemStack(TRepo.buckets, 1, 4), new ItemStack(Items.bucket)));
TRepo.moltenCobaltFluid = new Fluid("cobalt.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenCobaltFluid))
TRepo.moltenCobaltFluid = FluidRegistry.getFluid("cobalt.molten");
TRepo.moltenCobalt = new TConstructFluid(TRepo.moltenCobaltFluid, Material.lava, "liquid_cobalt").setBlockName("fluid.molten.cobalt");
GameRegistry.registerBlock(TRepo.moltenCobalt, "fluid.molten.cobalt");
TRepo.moltenCobaltFluid.setBlock(TRepo.moltenCobalt).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenCobaltFluid, 1000), new ItemStack(TRepo.buckets, 1, 5), new ItemStack(Items.bucket)));
TRepo.moltenArditeFluid = new Fluid("ardite.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenArditeFluid))
TRepo.moltenArditeFluid = FluidRegistry.getFluid("ardite.molten");
TRepo.moltenArdite = new TConstructFluid(TRepo.moltenArditeFluid, Material.lava, "liquid_ardite").setBlockName("fluid.molten.ardite");
GameRegistry.registerBlock(TRepo.moltenArdite, "fluid.molten.ardite");
TRepo.moltenArditeFluid.setBlock(TRepo.moltenArdite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenArditeFluid, 1000), new ItemStack(TRepo.buckets, 1, 6), new ItemStack(Items.bucket)));
TRepo.moltenBronzeFluid = new Fluid("bronze.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenBronzeFluid))
TRepo.moltenBronzeFluid = FluidRegistry.getFluid("bronze.molten");
TRepo.moltenBronze = new TConstructFluid(TRepo.moltenBronzeFluid, Material.lava, "liquid_bronze").setBlockName("fluid.molten.bronze");
GameRegistry.registerBlock(TRepo.moltenBronze, "fluid.molten.bronze");
TRepo.moltenBronzeFluid.setBlock(TRepo.moltenBronze).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenBronzeFluid, 1000), new ItemStack(TRepo.buckets, 1, 7), new ItemStack(Items.bucket)));
TRepo.moltenAlubrassFluid = new Fluid("aluminumbrass.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenAlubrassFluid))
TRepo.moltenAlubrassFluid = FluidRegistry.getFluid("aluminumbrass.molten");
TRepo.moltenAlubrass = new TConstructFluid(TRepo.moltenAlubrassFluid, Material.lava, "liquid_alubrass").setBlockName("fluid.molten.alubrass");
GameRegistry.registerBlock(TRepo.moltenAlubrass, "fluid.molten.alubrass");
TRepo.moltenAlubrassFluid.setBlock(TRepo.moltenAlubrass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenAlubrassFluid, 1000), new ItemStack(TRepo.buckets, 1, 8), new ItemStack(Items.bucket)));
TRepo.moltenManyullynFluid = new Fluid("manyullyn.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenManyullynFluid))
TRepo.moltenManyullynFluid = FluidRegistry.getFluid("manyullyn.molten");
TRepo.moltenManyullyn = new TConstructFluid(TRepo.moltenManyullynFluid, Material.lava, "liquid_manyullyn").setBlockName("fluid.molten.manyullyn");
GameRegistry.registerBlock(TRepo.moltenManyullyn, "fluid.molten.manyullyn");
TRepo.moltenManyullynFluid.setBlock(TRepo.moltenManyullyn).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenManyullynFluid, 1000), new ItemStack(TRepo.buckets, 1, 9), new ItemStack(Items.bucket)));
TRepo.moltenAlumiteFluid = new Fluid("alumite.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenAlumiteFluid))
TRepo.moltenAlumiteFluid = FluidRegistry.getFluid("alumite.molten");
TRepo.moltenAlumite = new TConstructFluid(TRepo.moltenAlumiteFluid, Material.lava, "liquid_alumite").setBlockName("fluid.molten.alumite");
GameRegistry.registerBlock(TRepo.moltenAlumite, "fluid.molten.alumite");
TRepo.moltenAlumiteFluid.setBlock(TRepo.moltenAlumite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenAlumiteFluid, 1000), new ItemStack(TRepo.buckets, 1, 10), new ItemStack(Items.bucket)));
TRepo.moltenObsidianFluid = new Fluid("obsidian.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenObsidianFluid))
TRepo.moltenObsidianFluid = FluidRegistry.getFluid("obsidian.molten");
TRepo.moltenObsidian = new TConstructFluid(TRepo.moltenObsidianFluid, Material.lava, "liquid_obsidian").setBlockName("fluid.molten.obsidian");
GameRegistry.registerBlock(TRepo.moltenObsidian, "fluid.molten.obsidian");
TRepo.moltenObsidianFluid.setBlock(TRepo.moltenObsidian).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenObsidianFluid, 1000), new ItemStack(TRepo.buckets, 1, 11), new ItemStack(Items.bucket)));
TRepo.moltenSteelFluid = new Fluid("steel.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenSteelFluid))
TRepo.moltenSteelFluid = FluidRegistry.getFluid("steel.molten");
TRepo.moltenSteel = new TConstructFluid(TRepo.moltenSteelFluid, Material.lava, "liquid_steel").setBlockName("fluid.molten.steel");
GameRegistry.registerBlock(TRepo.moltenSteel, "fluid.molten.steel");
TRepo.moltenSteelFluid.setBlock(TRepo.moltenSteel).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenSteelFluid, 1000), new ItemStack(TRepo.buckets, 1, 12), new ItemStack(Items.bucket)));
TRepo.moltenGlassFluid = new Fluid("glass.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenGlassFluid))
TRepo.moltenGlassFluid = FluidRegistry.getFluid("glass.molten");
TRepo.moltenGlass = new TConstructFluid(TRepo.moltenGlassFluid, Material.lava, "liquid_glass", true).setBlockName("fluid.molten.glass");
GameRegistry.registerBlock(TRepo.moltenGlass, "fluid.molten.glass");
TRepo.moltenGlassFluid.setBlock(TRepo.moltenGlass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenGlassFluid, 1000), new ItemStack(TRepo.buckets, 1, 13), new ItemStack(Items.bucket)));
TRepo.moltenStoneFluid = new Fluid("stone.seared");
if (!FluidRegistry.registerFluid(TRepo.moltenStoneFluid))
TRepo.moltenStoneFluid = FluidRegistry.getFluid("stone.seared");
TRepo.moltenStone = new TConstructFluid(TRepo.moltenStoneFluid, Material.lava, "liquid_stone").setBlockName("molten.stone");
GameRegistry.registerBlock(TRepo.moltenStone, "molten.stone");
TRepo.moltenStoneFluid.setBlock(TRepo.moltenStone).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenStoneFluid, 1000), new ItemStack(TRepo.buckets, 1, 14), new ItemStack(Items.bucket)));
TRepo.moltenEmeraldFluid = new Fluid("emerald.liquid");
if (!FluidRegistry.registerFluid(TRepo.moltenEmeraldFluid))
TRepo.moltenEmeraldFluid = FluidRegistry.getFluid("emerald.liquid");
TRepo.moltenEmerald = new TConstructFluid(TRepo.moltenEmeraldFluid, Material.water, "liquid_villager").setBlockName("molten.emerald");
GameRegistry.registerBlock(TRepo.moltenEmerald, "molten.emerald");
TRepo.moltenEmeraldFluid.setBlock(TRepo.moltenEmerald).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenEmeraldFluid, 1000), new ItemStack(TRepo.buckets, 1, 15), new ItemStack(Items.bucket)));
TRepo.bloodFluid = new Fluid("blood");
if (!FluidRegistry.registerFluid(TRepo.bloodFluid))
TRepo.bloodFluid = FluidRegistry.getFluid("blood");
TRepo.blood = new BloodBlock(TRepo.bloodFluid, Material.water, "liquid_cow").setBlockName("liquid.blood");
GameRegistry.registerBlock(TRepo.blood, "liquid.blood");
TRepo.bloodFluid.setBlock(TRepo.blood).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.bloodFluid, 1000), new ItemStack(TRepo.buckets, 1, 16), new ItemStack(Items.bucket)));
TRepo.moltenNickelFluid = new Fluid("nickel.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenNickelFluid))
TRepo.moltenNickelFluid = FluidRegistry.getFluid("nickel.molten");
TRepo.moltenNickel = new TConstructFluid(TRepo.moltenNickelFluid, Material.lava, "liquid_ferrous").setBlockName("fluid.molten.nickel");
GameRegistry.registerBlock(TRepo.moltenNickel, "fluid.molten.nickel");
TRepo.moltenNickelFluid.setBlock(TRepo.moltenNickel).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenNickelFluid, 1000), new ItemStack(TRepo.buckets, 1, 17), new ItemStack(Items.bucket)));
TRepo.moltenLeadFluid = new Fluid("lead.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenLeadFluid))
TRepo.moltenLeadFluid = FluidRegistry.getFluid("lead.molten");
TRepo.moltenLead = new TConstructFluid(TRepo.moltenLeadFluid, Material.lava, "liquid_lead").setBlockName("fluid.molten.lead");
GameRegistry.registerBlock(TRepo.moltenLead, "fluid.molten.lead");
TRepo.moltenLeadFluid.setBlock(TRepo.moltenLead).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenLeadFluid, 1000), new ItemStack(TRepo.buckets, 1, 18), new ItemStack(Items.bucket)));
TRepo.moltenSilverFluid = new Fluid("silver.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenSilverFluid))
TRepo.moltenSilverFluid = FluidRegistry.getFluid("silver.molten");
TRepo.moltenSilver = new TConstructFluid(TRepo.moltenSilverFluid, Material.lava, "liquid_silver").setBlockName("fluid.molten.silver");
GameRegistry.registerBlock(TRepo.moltenSilver, "fluid.molten.silver");
TRepo.moltenSilverFluid.setBlock(TRepo.moltenSilver).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenSilverFluid, 1000), new ItemStack(TRepo.buckets, 1, 19), new ItemStack(Items.bucket)));
TRepo.moltenShinyFluid = new Fluid("platinum.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenShinyFluid))
TRepo.moltenShinyFluid = FluidRegistry.getFluid("platinum.molten");
TRepo.moltenShiny = new TConstructFluid(TRepo.moltenShinyFluid, Material.lava, "liquid_shiny").setBlockName("fluid.molten.shiny");
GameRegistry.registerBlock(TRepo.moltenShiny, "fluid.molten.shiny");
TRepo.moltenShinyFluid.setBlock(TRepo.moltenShiny).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenShinyFluid, 1000), new ItemStack(TRepo.buckets, 1, 20), new ItemStack(Items.bucket)));
TRepo.moltenInvarFluid = new Fluid("invar.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenInvarFluid))
TRepo.moltenInvarFluid = FluidRegistry.getFluid("invar.molten");
TRepo.moltenInvar = new TConstructFluid(TRepo.moltenInvarFluid, Material.lava, "liquid_invar").setBlockName("fluid.molten.invar");
GameRegistry.registerBlock(TRepo.moltenInvar, "fluid.molten.invar");
TRepo.moltenInvarFluid.setBlock(TRepo.moltenInvar).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenInvarFluid, 1000), new ItemStack(TRepo.buckets, 1, 21), new ItemStack(Items.bucket)));
TRepo.moltenElectrumFluid = new Fluid("electrum.molten");
if (!FluidRegistry.registerFluid(TRepo.moltenElectrumFluid))
TRepo.moltenElectrumFluid = FluidRegistry.getFluid("electrum.molten");
TRepo.moltenElectrum = new TConstructFluid(TRepo.moltenElectrumFluid, Material.lava, "liquid_electrum").setBlockName("fluid.molten.electrum");
GameRegistry.registerBlock(TRepo.moltenElectrum, "fluid.molten.electrum");
TRepo.moltenElectrumFluid.setBlock(TRepo.moltenElectrum).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenElectrumFluid, 1000), new ItemStack(TRepo.buckets, 1, 22), new ItemStack(Items.bucket)));
TRepo.moltenEnderFluid = new Fluid("ender");
if (!FluidRegistry.registerFluid(TRepo.moltenEnderFluid))
{
TRepo.moltenEnderFluid = FluidRegistry.getFluid("ender");
TRepo.moltenEnder = TRepo.moltenEnderFluid.getBlock();
if (TRepo.moltenEnder == null)
TConstruct.logger.info("Molten ender block missing!");
}
else
{
TRepo.moltenEnder = new TConstructFluid(TRepo.moltenEnderFluid, Material.water, "liquid_ender").setBlockName("fluid.ender");
GameRegistry.registerBlock(TRepo.moltenEnder, "fluid.ender");
TRepo.moltenEnderFluid.setBlock(TRepo.moltenEnder).setDensity(3000).setViscosity(6000);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.moltenEnderFluid, 1000), new ItemStack(TRepo.buckets, 1, 23), new ItemStack(Items.bucket)));
}
// Slime
TRepo.slimeStep = new StepSoundSlime("mob.slime", 1.0f, 1.0f);
TRepo.blueSlimeFluid = new Fluid("slime.blue");
if (!FluidRegistry.registerFluid(TRepo.blueSlimeFluid))
TRepo.blueSlimeFluid = FluidRegistry.getFluid("slime.blue");
TRepo.slimePool = new SlimeFluid(TRepo.blueSlimeFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(TRepo.slimeStep).setBlockName("liquid.slime");
GameRegistry.registerBlock(TRepo.slimePool, "liquid.slime");
TRepo.blueSlimeFluid.setBlock(TRepo.slimePool);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.blueSlimeFluid, 1000), new ItemStack(TRepo.buckets, 1, 24), new ItemStack(Items.bucket)));
// Glue
TRepo.glueFluid = new Fluid("glue").setDensity(6000).setViscosity(6000).setTemperature(200);
if (!FluidRegistry.registerFluid(TRepo.glueFluid))
TRepo.glueFluid = FluidRegistry.getFluid("glue");
TRepo.glueFluidBlock = new GlueFluid(TRepo.glueFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(TRepo.slimeStep).setBlockName("liquid.glue");
GameRegistry.registerBlock(TRepo.glueFluidBlock, "liquid.glue");
TRepo.glueFluid.setBlock(TRepo.glueFluidBlock);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.glueFluid, 1000), new ItemStack(TRepo.buckets, 1, 25), new ItemStack(Items.bucket)));
TRepo.pigIronFluid = new Fluid("pigiron.molten");
if (!FluidRegistry.registerFluid(TRepo.pigIronFluid))
TRepo.pigIronFluid = FluidRegistry.getFluid("pigiron.molten");
else
TRepo.pigIronFluid.setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TRepo.pigIronFluid, 1000), new ItemStack(TRepo.buckets, 1, 26), new ItemStack(Items.bucket)));
TRepo.fluids = new Fluid[] { TRepo.moltenIronFluid, TRepo.moltenGoldFluid, TRepo.moltenCopperFluid, TRepo.moltenTinFluid, TRepo.moltenAluminumFluid, TRepo.moltenCobaltFluid,
TRepo.moltenArditeFluid, TRepo.moltenBronzeFluid, TRepo.moltenAlubrassFluid, TRepo.moltenManyullynFluid, TRepo.moltenAlumiteFluid, TRepo.moltenObsidianFluid, TRepo.moltenSteelFluid,
TRepo.moltenGlassFluid, TRepo.moltenStoneFluid, TRepo.moltenEmeraldFluid, TRepo.bloodFluid, TRepo.moltenNickelFluid, TRepo.moltenLeadFluid, TRepo.moltenSilverFluid,
TRepo.moltenShinyFluid, TRepo.moltenInvarFluid, TRepo.moltenElectrumFluid, TRepo.moltenEnderFluid, TRepo.blueSlimeFluid, TRepo.glueFluid, TRepo.pigIronFluid };
TRepo.fluidBlocks = new Block[] { TRepo.moltenIron, TRepo.moltenGold, TRepo.moltenCopper, TRepo.moltenTin, TRepo.moltenAluminum, TRepo.moltenCobalt, TRepo.moltenArdite, TRepo.moltenBronze,
TRepo.moltenAlubrass, TRepo.moltenManyullyn, TRepo.moltenAlumite, TRepo.moltenObsidian, TRepo.moltenSteel, TRepo.moltenGlass, TRepo.moltenStone, TRepo.moltenEmerald, TRepo.blood,
TRepo.moltenNickel, TRepo.moltenLead, TRepo.moltenSilver, TRepo.moltenShiny, TRepo.moltenInvar, TRepo.moltenElectrum, TRepo.moltenEnder, TRepo.slimePool, TRepo.glueFluidBlock };
// Slime Islands
TRepo.slimeGel = new SlimeGel().setStepSound(TRepo.slimeStep).setLightOpacity(0).setBlockName("slime.gel");
TRepo.slimeGrass = new SlimeGrass().setStepSound(Block.soundTypeGrass).setLightOpacity(0).setBlockName("slime.grass");
TRepo.slimeTallGrass = new SlimeTallGrass().setStepSound(Block.soundTypeGrass).setBlockName("slime.grass.tall");
TRepo.slimeLeaves = (SlimeLeaves) new SlimeLeaves().setStepSound(TRepo.slimeStep).setLightOpacity(0).setBlockName("slime.leaves");
TRepo.slimeSapling = (SlimeSapling) new SlimeSapling().setStepSound(TRepo.slimeStep).setBlockName("slime.sapling");
TRepo.slimeChannel = new ConveyorBase(Material.water, "greencurrent").setHardness(0.3f).setStepSound(TRepo.slimeStep).setBlockName("slime.channel");
TRepo.bloodChannel = new ConveyorBase(Material.water, "liquid_cow").setHardness(0.3f).setStepSound(TRepo.slimeStep).setBlockName("blood.channel");
TRepo.slimePad = new SlimePad(Material.cloth).setStepSound(TRepo.slimeStep).setHardness(0.3f).setBlockName("slime.pad");
// Decoration
TRepo.stoneTorch = new StoneTorch().setBlockName("decoration.stonetorch");
TRepo.stoneLadder = new StoneLadder().setBlockName("decoration.stoneladder");
TRepo.multiBrick = new MultiBrick().setBlockName("Decoration.Brick");
TRepo.multiBrickFancy = new MultiBrickFancy().setBlockName("Decoration.BrickFancy");
// Ores
String[] berryOres = new String[] { "berry_iron", "berry_gold", "berry_copper", "berry_tin", "berry_iron_ripe", "berry_gold_ripe", "berry_copper_ripe", "berry_tin_ripe" };
TRepo.oreBerry = (OreberryBush) new OreberryBush(berryOres, 0, 4, new String[] { "oreIron", "oreGold", "oreCopper", "oreTin" }).setBlockName("ore.berries.one");
String[] berryOresTwo = new String[] { "berry_aluminum", "berry_essence", "", "", "berry_aluminum_ripe", "berry_essence_ripe", "", "" };
TRepo.oreBerrySecond = (OreberryBush) new OreberryBushEssence(berryOresTwo, 4, 2, new String[] { "oreAluminum", "oreSilver" }).setBlockName("ore.berries.two");
String[] oreTypes = new String[] { "nether_slag", "nether_cobalt", "nether_ardite", "ore_copper", "ore_tin", "ore_aluminum", "ore_slag" };
TRepo.oreSlag = new MetalOre(Material.rock, 10.0F, oreTypes).setBlockName("tconstruct.stoneore");
TRepo.oreSlag.setHarvestLevel("pickaxe", 4, 1);
TRepo.oreSlag.setHarvestLevel("pickaxe", 4, 2);
TRepo.oreSlag.setHarvestLevel("pickaxe", 1, 3);
TRepo.oreSlag.setHarvestLevel("pickaxe", 1, 4);
TRepo.oreSlag.setHarvestLevel("pickaxe", 1, 5);
TRepo.oreGravel = new GravelOre().setBlockName("GravelOre").setBlockName("tconstruct.gravelore");
TRepo.oreGravel.setHarvestLevel("shovel", 1, 0);
TRepo.oreGravel.setHarvestLevel("shovel", 2, 1);
TRepo.oreGravel.setHarvestLevel("shovel", 1, 2);
TRepo.oreGravel.setHarvestLevel("shovel", 1, 3);
TRepo.oreGravel.setHarvestLevel("shovel", 1, 4);
TRepo.oreGravel.setHarvestLevel("shovel", 4, 5);
TRepo.speedBlock = new SpeedBlock().setBlockName("SpeedBlock");
// Glass
TRepo.clearGlass = new GlassBlockConnected("clear", false).setBlockName("GlassBlock");
TRepo.clearGlass.stepSound = Block.soundTypeGlass;
TRepo.glassPane = new GlassPaneConnected("clear", false);
TRepo.stainedGlassClear = new GlassBlockConnectedMeta("stained", true, "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue",
"brown", "green", "red", "black").setBlockName("GlassBlock.StainedClear");
TRepo.stainedGlassClear.stepSound = Block.soundTypeGlass;
TRepo.stainedGlassClearPane = new GlassPaneStained();
// Rail
TRepo.woodenRail = new WoodRail().setStepSound(Block.soundTypeWood).setCreativeTab(TConstructRegistry.blockTab).setBlockName("rail.wood");
}
void registerItems ()
{
TRepo.titleIcon = new TitleIcon().setUnlocalizedName("tconstruct.titleicon");
GameRegistry.registerItem(TRepo.titleIcon, "titleIcon");
String[] blanks = new String[] { "blank_pattern", "blank_cast", "blank_cast" };
TRepo.blankPattern = new CraftingItem(blanks, blanks, "materials/", "tinker", TConstructRegistry.materialTab).setUnlocalizedName("tconstruct.Pattern");
GameRegistry.registerItem(TRepo.blankPattern, "blankPattern");
TRepo.materials = new MaterialItem().setUnlocalizedName("tconstruct.Materials");
TRepo.toolRod = new ToolPart("_rod", "ToolRod").setUnlocalizedName("tconstruct.ToolRod");
TRepo.toolShard = new ToolShard("_chunk").setUnlocalizedName("tconstruct.ToolShard");
TRepo.woodPattern = new Pattern("pattern_", "materials/").setUnlocalizedName("tconstruct.Pattern");
TRepo.metalPattern = new MetalPattern("cast_", "materials/").setUnlocalizedName("tconstruct.MetalPattern");
// armorPattern = new ArmorPattern(PHConstruct.armorPattern,
// "armorcast_",
// "materials/").setUnlocalizedName("tconstruct.ArmorPattern");
GameRegistry.registerItem(TRepo.materials, "materials");
GameRegistry.registerItem(TRepo.woodPattern, "woodPattern");
GameRegistry.registerItem(TRepo.metalPattern, "metalPattern");
// GameRegistry.registerItem(TRepo.armorPattern, "armorPattern");
TConstructRegistry.addItemToDirectory("blankPattern", TRepo.blankPattern);
TConstructRegistry.addItemToDirectory("woodPattern", TRepo.woodPattern);
TConstructRegistry.addItemToDirectory("metalPattern", TRepo.metalPattern);
// TConstructRegistry.addItemToDirectory("armorPattern", armorPattern);
String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead",
"knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" };
for (int i = 1; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Pattern", new ItemStack(TRepo.woodPattern, 1, i));
}
for (int i = 0; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Cast", new ItemStack(TRepo.metalPattern, 1, i));
}
/*
* String[] armorPartTypes = { "helmet", "chestplate", "leggings",
* "boots" }; for (int i = 1; i < armorPartTypes.length; i++) {
* TConstructRegistry.addItemStackToDirectory(armorPartTypes[i] +
* "Cast", new ItemStack(armorPattern, 1, i)); }
*/
TRepo.manualBook = new Manual();
GameRegistry.registerItem(TRepo.manualBook, "manualBook");
TRepo.buckets = new FilledBucket(BlockUtils.getBlockFromItem(TRepo.buckets));
GameRegistry.registerItem(TRepo.buckets, "buckets");
TRepo.pickaxe = new Pickaxe();
TRepo.shovel = new Shovel();
TRepo.hatchet = new Hatchet();
TRepo.broadsword = new Broadsword();
TRepo.longsword = new Longsword();
TRepo.rapier = new Rapier();
TRepo.dagger = new Dagger();
TRepo.cutlass = new Cutlass();
TRepo.frypan = new FryingPan();
TRepo.battlesign = new BattleSign();
TRepo.mattock = new Mattock();
TRepo.chisel = new Chisel();
TRepo.lumberaxe = new LumberAxe();
TRepo.cleaver = new Cleaver();
TRepo.scythe = new Scythe();
TRepo.excavator = new Excavator();
TRepo.hammer = new Hammer();
TRepo.battleaxe = new Battleaxe();
TRepo.shortbow = new Shortbow();
TRepo.arrow = new Arrow();
Item[] tools = { TRepo.pickaxe, TRepo.shovel, TRepo.hatchet, TRepo.broadsword, TRepo.longsword, TRepo.rapier, TRepo.dagger, TRepo.cutlass, TRepo.frypan, TRepo.battlesign, TRepo.mattock,
TRepo.chisel, TRepo.lumberaxe, TRepo.cleaver, TRepo.scythe, TRepo.excavator, TRepo.hammer, TRepo.battleaxe, TRepo.shortbow, TRepo.arrow };
String[] toolStrings = { "pickaxe", "shovel", "hatchet", "broadsword", "longsword", "rapier", "dagger", "cutlass", "frypan", "battlesign", "mattock", "chisel", "lumberaxe", "cleaver",
"scythe", "excavator", "hammer", "battleaxe", "shortbow", "arrow" };
for (int i = 0; i < tools.length; i++)
{
GameRegistry.registerItem(tools[i], toolStrings[i]); // 1.7 compat
TConstructRegistry.addItemToDirectory(toolStrings[i], tools[i]);
}
TRepo.potionLauncher = new PotionLauncher().setUnlocalizedName("tconstruct.PotionLauncher");
GameRegistry.registerItem(TRepo.potionLauncher, "potionLauncher");
TRepo.pickaxeHead = new ToolPart("_pickaxe_head", "PickHead").setUnlocalizedName("tconstruct.PickaxeHead");
TRepo.shovelHead = new ToolPart("_shovel_head", "ShovelHead").setUnlocalizedName("tconstruct.ShovelHead");
TRepo.hatchetHead = new ToolPart("_axe_head", "AxeHead").setUnlocalizedName("tconstruct.AxeHead");
TRepo.binding = new ToolPart("_binding", "Binding").setUnlocalizedName("tconstruct.Binding");
TRepo.toughBinding = new ToolPart("_toughbind", "ToughBind").setUnlocalizedName("tconstruct.ThickBinding");
TRepo.toughRod = new ToolPart("_toughrod", "ToughRod").setUnlocalizedName("tconstruct.ThickRod");
TRepo.largePlate = new ToolPart("_largeplate", "LargePlate").setUnlocalizedName("tconstruct.LargePlate");
TRepo.swordBlade = new ToolPart("_sword_blade", "SwordBlade").setUnlocalizedName("tconstruct.SwordBlade");
TRepo.wideGuard = new ToolPart("_large_guard", "LargeGuard").setUnlocalizedName("tconstruct.LargeGuard");
TRepo.handGuard = new ToolPart("_medium_guard", "MediumGuard").setUnlocalizedName("tconstruct.MediumGuard");
TRepo.crossbar = new ToolPart("_crossbar", "Crossbar").setUnlocalizedName("tconstruct.Crossbar");
TRepo.knifeBlade = new ToolPart("_knife_blade", "KnifeBlade").setUnlocalizedName("tconstruct.KnifeBlade");
TRepo.fullGuard = new ToolPartHidden("_full_guard", "FullGuard").setUnlocalizedName("tconstruct.FullGuard");
TRepo.frypanHead = new ToolPart("_frypan_head", "FrypanHead").setUnlocalizedName("tconstruct.FrypanHead");
TRepo.signHead = new ToolPart("_battlesign_head", "SignHead").setUnlocalizedName("tconstruct.SignHead");
TRepo.chiselHead = new ToolPart("_chisel_head", "ChiselHead").setUnlocalizedName("tconstruct.ChiselHead");
TRepo.scytheBlade = new ToolPart("_scythe_head", "ScytheHead").setUnlocalizedName("tconstruct.ScytheBlade");
TRepo.broadAxeHead = new ToolPart("_lumberaxe_head", "LumberHead").setUnlocalizedName("tconstruct.LumberHead");
TRepo.excavatorHead = new ToolPart("_excavator_head", "ExcavatorHead").setUnlocalizedName("tconstruct.ExcavatorHead");
TRepo.largeSwordBlade = new ToolPart("_large_sword_blade", "LargeSwordBlade").setUnlocalizedName("tconstruct.LargeSwordBlade");
TRepo.hammerHead = new ToolPart("_hammer_head", "HammerHead").setUnlocalizedName("tconstruct.HammerHead");
TRepo.bowstring = new Bowstring().setUnlocalizedName("tconstruct.Bowstring");
TRepo.arrowhead = new ToolPart("_arrowhead", "ArrowHead").setUnlocalizedName("tconstruct.Arrowhead");
TRepo.fletching = new Fletching().setUnlocalizedName("tconstruct.Fletching");
Item[] toolParts = { TRepo.toolRod, TRepo.toolShard, TRepo.pickaxeHead, TRepo.shovelHead, TRepo.hatchetHead, TRepo.binding, TRepo.toughBinding, TRepo.toughRod, TRepo.largePlate,
TRepo.swordBlade, TRepo.wideGuard, TRepo.handGuard, TRepo.crossbar, TRepo.knifeBlade, TRepo.fullGuard, TRepo.frypanHead, TRepo.signHead, TRepo.chiselHead, TRepo.scytheBlade,
TRepo.broadAxeHead, TRepo.excavatorHead, TRepo.largeSwordBlade, TRepo.hammerHead, TRepo.bowstring, TRepo.fletching, TRepo.arrowhead };
String[] toolPartStrings = { "toolRod", "toolShard", "pickaxeHead", "shovelHead", "hatchetHead", "binding", "toughBinding", "toughRod", "heavyPlate", "swordBlade", "wideGuard", "handGuard",
"crossbar", "knifeBlade", "fullGuard", "frypanHead", "signHead", "chiselHead", "scytheBlade", "broadAxeHead", "excavatorHead", "largeSwordBlade", "hammerHead", "bowstring",
"fletching", "arrowhead" };
for (int i = 0; i < toolParts.length; i++)
{
GameRegistry.registerItem(toolParts[i], toolPartStrings[i]); // 1.7
// compat
TConstructRegistry.addItemToDirectory(toolPartStrings[i], toolParts[i]);
}
TRepo.diamondApple = new DiamondApple().setUnlocalizedName("tconstruct.apple.diamond");
TRepo.strangeFood = new StrangeFood().setUnlocalizedName("tconstruct.strangefood");
TRepo.oreBerries = new OreBerries().setUnlocalizedName("oreberry");
GameRegistry.registerItem(TRepo.diamondApple, "diamondApple");
GameRegistry.registerItem(TRepo.strangeFood, "strangeFood");
GameRegistry.registerItem(TRepo.oreBerries, "oreBerries");
boolean foodOverhaul = false;
if (Loader.isModLoaded("HungerOverhaul") || Loader.isModLoaded("fc_food"))
{
foodOverhaul = true;
}
TRepo.jerky = new Jerky(foodOverhaul).setUnlocalizedName("tconstruct.jerky");
GameRegistry.registerItem(TRepo.jerky, "jerky");
// Wearables
// heavyHelmet = new TArmorBase(PHConstruct.heavyHelmet,
// 0).setUnlocalizedName("tconstruct.HeavyHelmet");
TRepo.heartCanister = new HeartCanister().setUnlocalizedName("tconstruct.canister");
// heavyBoots = new TArmorBase(PHConstruct.heavyBoots,
// 3).setUnlocalizedName("tconstruct.HeavyBoots");
// glove = new
// Glove(PHConstruct.glove).setUnlocalizedName("tconstruct.Glove");
TRepo.knapsack = new Knapsack().setUnlocalizedName("tconstruct.storage");
TRepo.goldHead = new GoldenHead(4, 1.2F, false).setAlwaysEdible().setPotionEffect(Potion.regeneration.id, 10, 0, 1.0F).setUnlocalizedName("goldenhead");
// GameRegistry.registerItem(TRepo.heavyHelmet, "heavyHelmet");
GameRegistry.registerItem(TRepo.heartCanister, "heartCanister");
// GameRegistry.registerItem(TRepo.heavyBoots, "heavyBoots");
// GameRegistry.registerItem(TRepo.glove, "glove");
GameRegistry.registerItem(TRepo.knapsack, "knapsack");
GameRegistry.registerItem(TRepo.goldHead, "goldHead");
TRepo.creativeModifier = new CreativeModifier().setUnlocalizedName("tconstruct.modifier.creative");
GameRegistry.registerItem(TRepo.creativeModifier, "creativeModifier");
LiquidCasting basinCasting = TConstruct.getBasinCasting();
TRepo.materialWood = EnumHelper.addArmorMaterial("WOOD", 2, new int[] { 1, 2, 2, 1 }, 3);
TRepo.helmetWood = new ArmorBasic(TRepo.materialWood, 0, "wood").setUnlocalizedName("tconstruct.helmetWood");
TRepo.chestplateWood = new ArmorBasic(TRepo.materialWood, 1, "wood").setUnlocalizedName("tconstruct.chestplateWood");
TRepo.leggingsWood = new ArmorBasic(TRepo.materialWood, 2, "wood").setUnlocalizedName("tconstruct.leggingsWood");
TRepo.bootsWood = new ArmorBasic(TRepo.materialWood, 3, "wood").setUnlocalizedName("tconstruct.bootsWood");
GameRegistry.registerItem(TRepo.helmetWood, "helmetWood");
GameRegistry.registerItem(TRepo.chestplateWood, "chestplateWood");
GameRegistry.registerItem(TRepo.leggingsWood, "leggingsWood");
GameRegistry.registerItem(TRepo.bootsWood, "bootsWood");
TRepo.exoGoggles = new ExoArmor(EnumArmorPart.HELMET, "exosuit").setUnlocalizedName("tconstruct.exoGoggles");
TRepo.exoChest = new ExoArmor(EnumArmorPart.CHEST, "exosuit").setUnlocalizedName("tconstruct.exoChest");
TRepo.exoPants = new ExoArmor(EnumArmorPart.PANTS, "exosuit").setUnlocalizedName("tconstruct.exoPants");
TRepo.exoShoes = new ExoArmor(EnumArmorPart.SHOES, "exosuit").setUnlocalizedName("tconstruct.exoShoes");
GameRegistry.registerItem(TRepo.exoGoggles, "helmetExo");
GameRegistry.registerItem(TRepo.exoChest, "chestplateExo");
GameRegistry.registerItem(TRepo.exoPants, "leggingsExo");
GameRegistry.registerItem(TRepo.exoShoes, "bootsExo");
String[] materialStrings = { "paperStack", "greenSlimeCrystal", "searedBrick", "ingotCobalt", "ingotArdite", "ingotManyullyn", "mossBall", "lavaCrystal", "necroticBone", "ingotCopper",
"ingotTin", "ingotAluminum", "rawAluminum", "ingotBronze", "ingotAluminumBrass", "ingotAlumite", "ingotSteel", "blueSlimeCrystal", "ingotObsidian", "nuggetIron", "nuggetCopper",
"nuggetTin", "nuggetAluminum", "nuggetSilver", "nuggetAluminumBrass", "silkyCloth", "silkyJewel", "nuggetObsidian", "nuggetCobalt", "nuggetArdite", "nuggetManyullyn", "nuggetBronze",
"nuggetAlumite", "nuggetSteel", "ingotPigIron", "nuggetPigIron", "glueball" };
for (int i = 0; i < materialStrings.length; i++)
{
TConstructRegistry.addItemStackToDirectory(materialStrings[i], new ItemStack(TRepo.materials, 1, i));
}
String[] oreberries = { "Iron", "Gold", "Copper", "Tin", "Aluminum", "Essence" };
for (int i = 0; i < oreberries.length; i++)
{
TConstructRegistry.addItemStackToDirectory("oreberry" + oreberries[i], new ItemStack(TRepo.oreBerries, 1, i));
}
TConstructRegistry.addItemStackToDirectory("diamondApple", new ItemStack(TRepo.diamondApple, 1, 0));
TConstructRegistry.addItemStackToDirectory("blueSlimeFood", new ItemStack(TRepo.strangeFood, 1, 0));
TConstructRegistry.addItemStackToDirectory("canisterEmpty", new ItemStack(TRepo.heartCanister, 1, 0));
TConstructRegistry.addItemStackToDirectory("miniRedHeart", new ItemStack(TRepo.heartCanister, 1, 1));
TConstructRegistry.addItemStackToDirectory("canisterRedHeart", new ItemStack(TRepo.heartCanister, 1, 2));
// Vanilla stack sizes
Items.wooden_door.setMaxStackSize(16);
Items.iron_door.setMaxStackSize(16);
Items.boat.setMaxStackSize(16);
Items.minecart.setMaxStackSize(3);
// Items.minecartEmpty.setMaxStackSize(3);
// Items.minecartCrate.setMaxStackSize(3);
// Items.minecartPowered.setMaxStackSize(3);
Items.cake.setMaxStackSize(16);
// Block.torchWood.setTickRandomly(false);
}
void registerMaterials ()
{
TConstructRegistry.addToolMaterial(0, "Wood", "Wooden ", 0, 59, 200, 0, 1.0F, 0, 0f, "\u00A7e", "");
TConstructRegistry.addToolMaterial(1, "Stone", 1, 131, 400, 1, 0.5F, 0, 1f, "", StatCollector.translateToLocal("materialtraits.stonebound"));
TConstructRegistry.addToolMaterial(2, "Iron", 2, 250, 600, 2, 1.3F, 1, 0f, "\u00A7f", "");
TConstructRegistry.addToolMaterial(3, "Flint", 1, 171, 525, 2, 0.7F, 0, 0f, "\u00A78", "");
TConstructRegistry.addToolMaterial(4, "Cactus", 1, 150, 500, 2, 1.0F, 0, -1f, "\u00A72", StatCollector.translateToLocal("materialtraits.jagged"));
TConstructRegistry.addToolMaterial(5, "Bone", 1, 200, 400, 1, 1.0F, 0, 0f, "\u00A7e", "");
TConstructRegistry.addToolMaterial(6, "Obsidian", 3, 89, 700, 2, 0.8F, 3, 0f, "\u00A7d", "");
TConstructRegistry.addToolMaterial(7, "Netherrack", 2, 131, 400, 1, 1.2F, 0, 1f, "\u00A74", StatCollector.translateToLocal("materialtraits.stonebound"));
TConstructRegistry.addToolMaterial(8, "Slime", 0, 500, 150, 0, 1.5F, 0, 0f, "\u00A7a", "");
TConstructRegistry.addToolMaterial(9, "Paper", 0, 30, 200, 0, 0.3F, 0, 0f, "\u00A7f", StatCollector.translateToLocal("materialtraits.writable"));
TConstructRegistry.addToolMaterial(10, "Cobalt", 4, 800, 1100, 3, 1.75F, 2, 0f, "\u00A73", "");
TConstructRegistry.addToolMaterial(11, "Ardite", 4, 600, 800, 3, 2.0F, 0, 2f, "\u00A74", StatCollector.translateToLocal("materialtraits.stonebound"));
TConstructRegistry.addToolMaterial(12, "Manyullyn", 5, 1200, 900, 4, 2.5F, 0, 0f, "\u00A75", "");
TConstructRegistry.addToolMaterial(13, "Copper", 1, 180, 500, 2, 1.15F, 0, 0f, "\u00A7c", "");
TConstructRegistry.addToolMaterial(14, "Bronze", 2, 350, 700, 2, 1.3F, 1, 0f, "\u00A76", "");
TConstructRegistry.addToolMaterial(15, "Alumite", 4, 550, 800, 3, 1.3F, 2, 0f, "\u00A7d", "");
TConstructRegistry.addToolMaterial(16, "Steel", 4, 750, 800, 3, 1.3F, 2, 0f, "", "");
TConstructRegistry.addToolMaterial(17, "BlueSlime", "Slime ", 0, 1200, 150, 0, 2.0F, 0, 0f, "\u00A7b", "");
TConstructRegistry.addToolMaterial(18, "PigIron", "Pig Iron ", 3, 250, 600, 2, 1.3F, 1, 0f, "\u00A7c", StatCollector.translateToLocal("materialtraits.tasty"));
TConstructRegistry.addBowMaterial(0, 384, 20, 1.0f); // Wood
TConstructRegistry.addBowMaterial(1, 10, 80, 0.2f); // Stone
TConstructRegistry.addBowMaterial(2, 576, 40, 1.2f); // Iron
TConstructRegistry.addBowMaterial(3, 10, 80, 0.2f); // Flint
TConstructRegistry.addBowMaterial(4, 384, 20, 1.0f); // Cactus
TConstructRegistry.addBowMaterial(5, 192, 30, 1.0f); // Bone
TConstructRegistry.addBowMaterial(6, 10, 80, 0.2f); // Obsidian
TConstructRegistry.addBowMaterial(7, 10, 80, 0.2f); // Netherrack
TConstructRegistry.addBowMaterial(8, 1536, 20, 1.2f); // Slime
TConstructRegistry.addBowMaterial(9, 48, 25, 0.5f); // Paper
TConstructRegistry.addBowMaterial(10, 1152, 40, 1.2f); // Cobalt
TConstructRegistry.addBowMaterial(11, 960, 40, 1.2f); // Ardite
TConstructRegistry.addBowMaterial(12, 1536, 40, 1.2f); // Manyullyn
TConstructRegistry.addBowMaterial(13, 384, 40, 1.2f); // Copper
TConstructRegistry.addBowMaterial(14, 576, 40, 1.2f); // Bronze
TConstructRegistry.addBowMaterial(15, 768, 40, 1.2f); // Alumite
TConstructRegistry.addBowMaterial(16, 768, 40, 1.2f); // Steel
TConstructRegistry.addBowMaterial(17, 576, 20, 1.2f); // Blue Slime
TConstructRegistry.addBowMaterial(18, 384, 20, 1.2f); // Slime
// Material ID, mass, fragility
TConstructRegistry.addArrowMaterial(0, 0.69F, 1.0F, 100F); // Wood
TConstructRegistry.addArrowMaterial(1, 2.5F, 5.0F, 100F); // Stone
TConstructRegistry.addArrowMaterial(2, 7.2F, 0.5F, 100F); // Iron
TConstructRegistry.addArrowMaterial(3, 2.65F, 1.0F, 100F); // Flint
TConstructRegistry.addArrowMaterial(4, 0.76F, 1.0F, 100F); // Cactus
TConstructRegistry.addArrowMaterial(5, 0.69F, 1.0F, 100); // Bone
TConstructRegistry.addArrowMaterial(6, 2.4F, 1.0F, 100F); // Obsidian
TConstructRegistry.addArrowMaterial(7, 3.5F, 1.0F, 100F); // Netherrack
TConstructRegistry.addArrowMaterial(8, 0.42F, 0.0F, 100F); // Slime
TConstructRegistry.addArrowMaterial(9, 1.1F, 3.0F, 90F); // Paper
TConstructRegistry.addArrowMaterial(10, 8.9F, 0.25F, 100F); // Cobalt
TConstructRegistry.addArrowMaterial(11, 7.2F, 0.25F, 100F); // Ardite
TConstructRegistry.addArrowMaterial(12, 10.6F, 0.1F, 100F); // Manyullyn
TConstructRegistry.addArrowMaterial(13, 8.96F, 0.5F, 100F); // Copper
TConstructRegistry.addArrowMaterial(14, 7.9F, 0.25F, 100F); // Bronze
TConstructRegistry.addArrowMaterial(15, 4.7F, 0.25F, 100F); // Alumite
TConstructRegistry.addArrowMaterial(16, 7.6F, 0.25F, 100F); // Steel
TConstructRegistry.addArrowMaterial(17, 0.42F, 0.0F, 100F); // Blue
// Slime
TConstructRegistry.addArrowMaterial(18, 6.8F, 0.5F, 100F); // Iron
TConstructRegistry.addBowstringMaterial(0, 2, new ItemStack(Items.string), new ItemStack(TRepo.bowstring, 1, 0), 1F, 1F, 1f); // String
TConstructRegistry.addFletchingMaterial(0, 2, new ItemStack(Items.feather), new ItemStack(TRepo.fletching, 1, 0), 100F, 0F, 0.05F); // Feather
for (int i = 0; i < 4; i++)
TConstructRegistry.addFletchingMaterial(1, 2, new ItemStack(Blocks.leaves, 1, i), new ItemStack(TRepo.fletching, 1, 1), 75F, 0F, 0.2F); // All four vanialla Leaves
TConstructRegistry.addFletchingMaterial(2, 2, new ItemStack(TRepo.materials, 1, 1), new ItemStack(TRepo.fletching, 1, 2), 100F, 0F, 0.12F); // Slime
TConstructRegistry.addFletchingMaterial(3, 2, new ItemStack(TRepo.materials, 1, 17), new ItemStack(TRepo.fletching, 1, 3), 100F, 0F, 0.12F); // BlueSlime
PatternBuilder pb = PatternBuilder.instance;
if (PHConstruct.enableTWood)
pb.registerFullMaterial(Blocks.planks, 2, StatCollector.translateToLocal("gui.partbuilder.material.wood"), new ItemStack(Items.stick), new ItemStack(Items.stick), 0);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.wood"), new ItemStack(Items.stick, 2), new ItemStack(Items.stick), 0);
if (PHConstruct.enableTStone)
{
pb.registerFullMaterial(Blocks.stone, 2, StatCollector.translateToLocal("gui.partbuilder.material.stone"), new ItemStack(TRepo.toolShard, 1, 1), new ItemStack(TRepo.toolRod, 1, 1), 1);
pb.registerMaterial(Blocks.cobblestone, 2, StatCollector.translateToLocal("gui.partbuilder.material.stone"));
}
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.stone"), new ItemStack(TRepo.toolShard, 1, 1), new ItemStack(TRepo.toolRod, 1, 1), 0);
pb.registerFullMaterial(Items.iron_ingot, 2, StatCollector.translateToLocal("gui.partbuilder.material.iron"), new ItemStack(TRepo.toolShard, 1, 2), new ItemStack(TRepo.toolRod, 1, 2), 2);
if (PHConstruct.enableTFlint)
pb.registerFullMaterial(Items.flint, 2, StatCollector.translateToLocal("gui.partbuilder.material.flint"), new ItemStack(TRepo.toolShard, 1, 3), new ItemStack(TRepo.toolRod, 1, 3), 3);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.flint"), new ItemStack(TRepo.toolShard, 1, 3), new ItemStack(TRepo.toolRod, 1, 3), 3);
if (PHConstruct.enableTCactus)
pb.registerFullMaterial(Blocks.cactus, 2, StatCollector.translateToLocal("gui.partbuilder.material.cactus"), new ItemStack(TRepo.toolShard, 1, 4), new ItemStack(TRepo.toolRod, 1, 4), 4);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.cactus"), new ItemStack(TRepo.toolShard, 1, 4), new ItemStack(TRepo.toolRod, 1, 4), 4);
if (PHConstruct.enableTBone)
pb.registerFullMaterial(Items.bone, 2, StatCollector.translateToLocal("gui.partbuilder.material.bone"), new ItemStack(Items.dye, 1, 15), new ItemStack(Items.bone), 5);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.bone"), new ItemStack(Items.dye, 1, 15), new ItemStack(Items.bone), 5);
pb.registerFullMaterial(Blocks.obsidian, 2, StatCollector.translateToLocal("gui.partbuilder.material.obsidian"), new ItemStack(TRepo.toolShard, 1, 6), new ItemStack(TRepo.toolRod, 1, 6), 6);
pb.registerMaterial(new ItemStack(TRepo.materials, 1, 18), 2, StatCollector.translateToLocal("gui.partbuilder.material.obsidian"));
if (PHConstruct.enableTNetherrack)
pb.registerFullMaterial(Blocks.netherrack, 2, StatCollector.translateToLocal("gui.partbuilder.material.netherrack"), new ItemStack(TRepo.toolShard, 1, 7), new ItemStack(TRepo.toolRod, 1, 7), 7);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.netherrack"), new ItemStack(TRepo.toolShard, 1, 7), new ItemStack(TRepo.toolRod, 1, 7), 7);
if (PHConstruct.enableTSlime)
pb.registerFullMaterial(new ItemStack(TRepo.materials, 1, 1), 2, StatCollector.translateToLocal("gui.partbuilder.material.slime"), new ItemStack(TRepo.toolShard, 1, 8), new ItemStack(TRepo.toolRod, 1, 8), 8);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.slime"), new ItemStack(TRepo.toolShard, 1, 8), new ItemStack(TRepo.toolRod, 1, 17), 8);
if (PHConstruct.enableTPaper)
pb.registerFullMaterial(new ItemStack(TRepo.materials, 1, 0), 2, StatCollector.translateToLocal("gui.partbuilder.material.paper"), new ItemStack(Items.paper, 2), new ItemStack(TRepo.toolRod, 1, 9), 9);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.blueslime"), new ItemStack(Items.paper, 2), new ItemStack(TRepo.toolRod, 1, 9), 9);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.cobalt"), new ItemStack(TRepo.toolShard, 1, 10), new ItemStack(TRepo.toolRod, 1, 10), 10);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.ardite"), new ItemStack(TRepo.toolShard, 1, 11), new ItemStack(TRepo.toolRod, 1, 11), 11);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.manyullyn"), new ItemStack(TRepo.toolShard, 1, 12), new ItemStack(TRepo.toolRod, 1, 12), 12);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.copper"), new ItemStack(TRepo.toolShard, 1, 13), new ItemStack(TRepo.toolRod, 1, 13), 13);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.bronze"), new ItemStack(TRepo.toolShard, 1, 14), new ItemStack(TRepo.toolRod, 1, 14), 14);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.alumite"), new ItemStack(TRepo.toolShard, 1, 15), new ItemStack(TRepo.toolRod, 1, 15), 15);
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.steel"), new ItemStack(TRepo.toolShard, 1, 16), new ItemStack(TRepo.toolRod, 1, 16), 16);
if (PHConstruct.enableTBlueSlime)
pb.registerFullMaterial(new ItemStack(TRepo.materials, 1, 17), 2, StatCollector.translateToLocal("gui.partbuilder.material.blueslime"), new ItemStack(TRepo.toolShard, 1, 17), new ItemStack(TRepo.toolRod, 1, 17), 17);
else
pb.registerMaterialSet(StatCollector.translateToLocal("gui.partbuilder.material.blueslime"), new ItemStack(TRepo.toolShard, 1, 17), new ItemStack(TRepo.toolRod, 1, 17), 17);
pb.registerFullMaterial(new ItemStack(TRepo.materials, 1, 34), 2, StatCollector.translateToLocal("gui.partbuilder.material.pigiron"), new ItemStack(TRepo.toolShard, 1, 18), new ItemStack(TRepo.toolRod, 1, 18), 18);
pb.addToolPattern((IPattern) TRepo.woodPattern);
}
void addCraftingRecipes ()
{
TRecipes.addPartMapping();
TRecipes.addRecipesForToolBuilder();
TRecipes.addRecipesForTableCasting();
TRecipes.addRecipesForBasinCasting();
TRecipes.addRecipesForSmeltery();
TRecipes.addRecipesForChisel();
TRecipes.addRecipesForFurnace();
TRecipes.addRecipesForCraftingTable();
TRecipes.addRecipesForDryingRack();
}
void setupToolTabs ()
{
TConstructRegistry.materialTab.init(new ItemStack(TRepo.manualBook, 1, 0));
TConstructRegistry.partTab.init(new ItemStack(TRepo.titleIcon, 1, 255));
TConstructRegistry.blockTab.init(new ItemStack(TRepo.toolStationWood));
ItemStack tool = new ItemStack(TRepo.longsword, 1, 0);
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("InfiTool", new NBTTagCompound());
compound.getCompoundTag("InfiTool").setInteger("RenderHead", 2);
compound.getCompoundTag("InfiTool").setInteger("RenderHandle", 0);
compound.getCompoundTag("InfiTool").setInteger("RenderAccessory", 10);
tool.setTagCompound(compound);
// TConstruct.
TConstructRegistry.toolTab.init(tool);
}
public void addLoot ()
{
// Item, min, max, weight
ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(TRepo.heartCanister, 1, 1), 1, 1, 5));
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(TRepo.heartCanister, 1, 1), 1, 1, 10));
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_JUNGLE_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(TRepo.heartCanister, 1, 1), 1, 1, 10));
TRepo.tinkerHouseChest = new ChestGenHooks("TinkerHouse", new WeightedRandomChestContent[0], 3, 27);
TRepo.tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(TRepo.heartCanister, 1, 1), 1, 1, 1));
int[] validTypes = { 0, 1, 2, 3, 4, 5, 6, 8, 9, 13, 14, 17 };
Item[] partTypes = { TRepo.pickaxeHead, TRepo.shovelHead, TRepo.hatchetHead, TRepo.binding, TRepo.swordBlade, TRepo.wideGuard, TRepo.handGuard, TRepo.crossbar, TRepo.knifeBlade,
TRepo.frypanHead, TRepo.signHead, TRepo.chiselHead };
for (int partIter = 0; partIter < partTypes.length; partIter++)
{
for (int typeIter = 0; typeIter < validTypes.length; typeIter++)
{
TRepo.tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(partTypes[partIter], 1, validTypes[typeIter]), 1, 1, 15));
}
}
TRepo.tinkerHousePatterns = new ChestGenHooks("TinkerPatterns", new WeightedRandomChestContent[0], 5, 30);
for (int i = 0; i < 13; i++)
{
TRepo.tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(TRepo.woodPattern, 1, i + 1), 1, 3, 20));
}
TRepo.tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(TRepo.woodPattern, 1, 22), 1, 3, 40));
}
public static String[] liquidNames;
@Override
public int getBurnTime (ItemStack fuel)
{
if (fuel.getItem() == TRepo.materials && fuel.getItemDamage() == 7)
return 26400;
return 0;
}
public void addAchievements ()
{
HashMap<String, Achievement> achievements = TAchievements.achievements;
achievements.put("tconstruct:beginner", new Achievement("tconstruct:beginner", "tconstruct.beginner", 0, 0, TRepo.manualBook, null));// .setIndependent());
achievements.put("tconstruct:pattern", new Achievement("tconstruct:pattern", "tconstruct.pattern", 2, 1, TRepo.blankPattern, achievements.get("tconstruct:beginner")));
achievements.put("tconstruct:tinkerer", new Achievement("tconstruct:tinkerer", "tconstruct.tinkerer", 2, 2, new ItemStack(TRepo.titleIcon, 1, 4096), achievements.get("tconstruct:pattern")));
achievements.put("tconstruct:preparedFight",
new Achievement("tconstruct:preparedFight", "tconstruct.preparedFight", 1, 3, new ItemStack(TRepo.titleIcon, 1, 4097), achievements.get("tconstruct:tinkerer")));
achievements.put("tconstruct:proTinkerer",
new Achievement("tconstruct:proTinkerer", "tconstruct.proTinkerer", 4, 4, new ItemStack(TRepo.titleIcon, 1, 4098), achievements.get("tconstruct:tinkerer")).setSpecial());
achievements.put("tconstruct:smelteryMaker", new Achievement("tconstruct:smelteryMaker", "tconstruct.smelteryMaker", -2, -1, TRepo.smeltery, achievements.get("tconstruct:beginner")));
achievements.put("tconstruct:enemySlayer",
new Achievement("tconstruct:enemySlayer", "tconstruct.enemySlayer", 0, 5, new ItemStack(TRepo.titleIcon, 1, 4099), achievements.get("tconstruct:preparedFight")));
achievements.put("tconstruct:dualConvenience",
new Achievement("tconstruct:dualConvenience", "tconstruct.dualConvenience", 0, 7, new ItemStack(TRepo.titleIcon, 1, 4100), achievements.get("tconstruct:enemySlayer")).setSpecial());
achievements.put("tconstruct:doingItWrong",
new Achievement("tconstruct:doingItWrong", "tconstruct.doingItWrong", -2, -3, new ItemStack(TRepo.manualBook, 1, 2), achievements.get("tconstruct:smelteryMaker")));
achievements.put("tconstruct:betterCrafting",
new Achievement("tconstruct:betterCrafting", "tconstruct.betterCrafting", -2, 2, TRepo.craftingStationWood, achievements.get("tconstruct:beginner")));
}
}
|
diff --git a/srcj/com/sun/electric/tool/drc/Quick.java b/srcj/com/sun/electric/tool/drc/Quick.java
index e0697b50f..b8a9f4b39 100755
--- a/srcj/com/sun/electric/tool/drc/Quick.java
+++ b/srcj/com/sun/electric/tool/drc/Quick.java
@@ -1,4834 +1,4840 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: Quick.java
*
* Copyright (c) 2004 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.drc;
import com.sun.electric.Main;
import com.sun.electric.database.geometry.DBMath;
import com.sun.electric.database.geometry.Geometric;
import com.sun.electric.database.geometry.GeometryHandler;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.geometry.PolyBase;
import com.sun.electric.database.geometry.PolyQTree;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.hierarchy.HierarchyEnumerator;
import com.sun.electric.database.hierarchy.Nodable;
import com.sun.electric.database.network.Netlist;
import com.sun.electric.database.network.Network;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.prototype.PortOriginal;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.text.Version;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.VarContext;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.technology.ArcProto;
import com.sun.electric.technology.DRCRules;
import com.sun.electric.technology.DRCTemplate;
import com.sun.electric.technology.Layer;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.SizeOffset;
import com.sun.electric.technology.Technology;
import com.sun.electric.technology.technologies.Generic;
import com.sun.electric.tool.Job;
import com.sun.electric.tool.user.ErrorLogger;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This is the "quick" DRC which does full hierarchical examination of the circuit.
* <P>
* The "quick" DRC works as follows:
* It first examines every primitive node and arc in the cell
* For each layer on these objects, it examines everything surrounding it, even in subcells
* R-trees are used to limit search.
* Where cell instances are found, the contents are examined recursively
* It next examines every cell instance in the cell
* All other instances within the surrounding area are considered
* When another instance is found, the two instances are examined for interaction
* A cache is kept of instance pairs in specified configurations to speed-up arrays
* All objects in the other instance that are inside the bounds of the first are considered
* The other instance is hierarchically examined to locate primitives in the area of consideration
* For each layer on each primitive object found in the other instance,
* Examine the contents of the first instance for interactions about that layer
* <P>
* Since Electric understands connectivity, it uses this information to determine whether two layers
* are connected or not. However, if such global connectivity is propagated in the standard Electric
* way (placing numbers on exports, descending into the cell, and pulling the numbers onto local networks)
* then it is not possible to decompose the DRC for multiple processors, since two different processors
* may want to write global network information on the same local networks at once.
* <P>
* To solve this problem, the "quick" DRC determines how many instances of each cell exist. For every
* network in every cell, an array is built that is as large as the number of instances of that cell.
* This array contains the global network number for that each instance of the cell. The algorithm for
* building these arrays is quick (1 second for a million-transistor chip) and the memory requirement
* is not excessive (8 megabytes for a million-transistor chip). It uses the CheckInst and CheckProto
* objects.
* @author Steve Rubin, Gilda Garreton
*/
public class Quick
{
private static final double TINYDELTA = DBMath.getEpsilon()*1.1;
// the different types of errors
private static final int SPACINGERROR = 1;
private static final int MINWIDTHERROR = 2;
private static final int NOTCHERROR = 3;
private static final int MINSIZEERROR = 4;
private static final int BADLAYERERROR = 5;
private static final int LAYERSURROUNDERROR = 6;
private static final int MINAREAERROR = 7;
private static final int ENCLOSEDAREAERROR = 8;
private static final int SURROUNDERROR = 10;
private static final int FORBIDDEN = 11;
private static final int RESOLUTION = 12;
private static final int CUTERROR = 15;
// Different types of warnings
private static final int ZEROLENGTHARCWARN = 13;
private static final int TECHMIXWARN = 14;
/**
* The CheckInst object is associated with every cell instance in the library.
* It helps determine network information on a global scale.
* It takes a "global-index" parameter, inherited from above (intially zero).
* It then computes its own index number as follows:
* thisindex = global-index * multiplier + localIndex + offset
* This individual index is used to lookup an entry on each network in the cell
* (an array is stored on each network, giving its global net number).
*/
private static class CheckInst
{
int localIndex;
int multiplier;
int offset;
};
private HashMap checkInsts = null;
/**
* The CheckProto object is placed on every cell and is used only temporarily
* to number the instances.
*/
private static class CheckProto
{
/** time stamp for counting within a particular parent */ int timeStamp;
/** number of instances of this cell in a particular parent */ int instanceCount;
/** total number of instances of this cell, hierarchically */ int hierInstanceCount;
/** number of instances of this cell in a particular parent */ int totalPerCell;
/** true if this cell has been checked */ boolean cellChecked;
/** true if this cell has parameters */ boolean cellParameterized;
/** true if this cell or subcell has parameters */ boolean treeParameterized;
/** list of instances in a particular parent */ List nodesInCell;
/** netlist of this cell */ Netlist netlist;
};
private HashMap checkProtos = null;
private HashMap networkLists = null;
private HashMap minAreaLayerMap = new HashMap(); // For minimum area checking
private HashMap enclosedAreaLayerMap = new HashMap(); // For enclosed area checking
private DRC.CheckDRCLayoutJob job; // Reference to running job
private HashMap cellsMap = new HashMap(); // for cell caching
private HashMap nodesMap = new HashMap(); // for node caching
private int activeBits = 0; // to caching current extra bits
private int mergeMode = GeometryHandler.ALGO_SWEEP; // .ALGO_QTREE;
private int techMode = DRCTemplate.NONE; /** To control different rules for ST and TSMC technologies */
private Map od2Layers = new HashMap(3); /** to control OD2 combination in the same die according to foundries */
public Quick(DRC.CheckDRCLayoutJob job, int mode)
{
this.job = job;
this.mergeMode = mode;
}
/**
* The InstanceInter object records interactions between two cell instances and prevents checking
* them multiple times.
*/
private static class InstanceInter
{
/** the two cell instances being compared */ Cell cell1, cell2;
/** rotation of cell instance 1 */ int rot1;
/** mirroring of cell instance 1 */ boolean mirrorX1, mirrorY1;
/** rotation of cell instance 2 */ int rot2;
/** mirroring of cell instance 2 */ boolean mirrorX2, mirrorY2;
/** distance from instance 1 to instance 2 */ double dx, dy;
/** the two NodeInst parents */ NodeInst n1Parent, n2Parent, triggerNi;
};
private List instanceInteractionList = new ArrayList();
/**
* The DRCExclusion object lists areas where Generic:DRC-Nodes exist to ignore errors.
*/
private static class DRCExclusion
{
Cell cell;
Poly poly;
NodeInst ni;
};
private List exclusionList = new ArrayList();
/** number of processes for doing DRC */ private int numberOfThreads;
/** error type search */ private int errorTypeSearch;
/** minimum output grid resolution */ private double minAllowedResolution;
/** true to ignore center cuts in large contacts. */ private boolean ignoreCenterCuts;
/** maximum area to examine (the worst spacing rule). */ private double worstInteractionDistance;
/** time stamp for numbering networks. */ private int checkTimeStamp;
/** for numbering networks. */ private int checkNetNumber;
/** total errors found in all threads. */ private int totalMsgFound;
/** a NodeInst that is too tiny for its connection. */ private NodeInst tinyNodeInst;
/** the other Geometric in "tiny" errors. */ private Geometric tinyGeometric;
/** for tracking the time of good DRC. */ private HashMap goodDRCDate = new HashMap();
/** for tracking cells that need to clean good DRC vars */ private HashMap cleanDRCDate = new HashMap();
/** for logging errors */ private ErrorLogger errorLogger;
/** for logging incremental errors */ private static ErrorLogger errorLoggerIncremental = null;
/** Top cell for DRC */ private Cell topCell;
/* for figuring out which layers are valid for DRC */
private Technology layersValidTech = null;
private boolean [] layersValid;
/* for tracking which layers interact with which nodes */
private Technology layerInterTech = null;
private HashMap layersInterNodes = null;
private HashMap layersInterArcs = null;
public static int checkDesignRules(Cell cell, Geometric[] geomsToCheck, boolean[] validity,
Rectangle2D bounds, DRC.CheckDRCLayoutJob drcJob)
{
return checkDesignRules(cell, geomsToCheck, validity, bounds, drcJob, GeometryHandler.ALGO_QTREE);
}
/**
* This is the entry point for DRC.
*
* Method to do a hierarchical DRC check on cell "cell".
* If "count" is zero, check the entire cell.
* If "count" is nonzero, only check that many instances (in "nodesToCheck") and set the
* entry in "validity" TRUE if it is DRC clean.
* @param bounds if null, check entire cell. If not null, only check area in bounds.
* @param drcJob
* @return the number of errors found
*/
public static int checkDesignRules(Cell cell, Geometric[] geomsToCheck, boolean[] validity,
Rectangle2D bounds, DRC.CheckDRCLayoutJob drcJob, int mode)
{
Quick q = new Quick(drcJob, mode);
return q.doCheck(cell, geomsToCheck, validity, bounds);
}
// returns the number of errors found
private int doCheck(Cell cell, Geometric [] geomsToCheck, boolean [] validity, Rectangle2D bounds)
{
// Check if there are DRC rules for particular tech
Technology tech = cell.getTechnology();
DRCRules rules = DRC.getRules(tech);
// caching bits
activeBits = DRC.getActiveBits();
// caching technology mode
techMode = tech.getFoundry();
// minimim resolution different from zero if flag is on otherwise stays at zero (default)
minAllowedResolution = tech.getResolution();
// Nothing to check for this particular technology
if (rules == null || rules.getNumberOfRules() == 0) return 0;
// get the current DRC options
errorTypeSearch = DRC.getErrorType();
ignoreCenterCuts = DRC.isIgnoreCenterCuts();
numberOfThreads = DRC.getNumberOfThreads();
topCell = cell; /* Especially important for minArea checking */
// if checking specific instances, adjust options and processor count
int count = (geomsToCheck != null) ? geomsToCheck.length : 0;
if (count > 0)
{
errorTypeSearch = DRC.ERROR_CHECK_CELL;
numberOfThreads = 1;
}
// cache valid layers for this technology
cacheValidLayers(tech);
buildLayerInteractions(tech);
// clean out the cache of instances
instanceInteractionList.clear();
// determine maximum DRC interaction distance
worstInteractionDistance = DRC.getWorstSpacingDistance(tech);
// determine if min area must be checked (if any layer got valid data)
minAreaLayerMap.clear();
enclosedAreaLayerMap.clear();
cellsMap.clear();
nodesMap.clear();
// No incremental neither per Cell
if (!DRC.isIgnoreAreaChecking() && errorTypeSearch != DRC.ERROR_CHECK_CELL)
{
for(Iterator it = tech.getLayers(); it.hasNext(); )
{
Layer layer = (Layer)it.next();
// Storing min areas
DRCTemplate minAreaRule = DRC.getMinValue(layer, DRCTemplate.AREA,techMode);
if (minAreaRule != null)
minAreaLayerMap.put(layer, minAreaRule);
// Storing enclosed areas
DRCTemplate enclosedAreaRule = DRC.getMinValue(layer, DRCTemplate.ENCLOSEDAREA, techMode);
if (enclosedAreaRule != null)
enclosedAreaLayerMap.put(layer, enclosedAreaRule);
}
}
// initialize all cells for hierarchical network numbering
checkProtos = new HashMap();
checkInsts = new HashMap();
// initialize cells in tree for hierarchical network numbering
Netlist netlist = cell.getNetlist(false);
CheckProto cp = checkEnumerateProtos(cell, netlist);
// see if any parameters are used below this cell
if (cp.treeParameterized && numberOfThreads > 1)
{
// parameters found: cannot use multiple processors
System.out.println("Parameterized layout being used: multiprocessor decomposition disabled");
numberOfThreads = 1;
}
// now recursively examine, setting information on all instances
cp.hierInstanceCount = 1;
checkTimeStamp = 0;
checkEnumerateInstances(cell);
// now allocate space for hierarchical network arrays
//int totalNetworks = 0;
networkLists = new HashMap();
for(Iterator it = checkProtos.entrySet().iterator(); it.hasNext(); )
{
Map.Entry e = (Map.Entry)it.next();
Cell libCell = (Cell)e.getKey();
CheckProto subCP = (CheckProto)e.getValue();
if (subCP.hierInstanceCount > 0)
{
// allocate net number lists for every net in the cell
for(Iterator nIt = subCP.netlist.getNetworks(); nIt.hasNext(); )
{
Network net = (Network)nIt.next();
Integer [] netNumbers = new Integer[subCP.hierInstanceCount];
for(int i=0; i<subCP.hierInstanceCount; i++) netNumbers[i] = new Integer(0);
networkLists.put(net, netNumbers);
//totalNetworks += subCP.hierInstanceCount;
}
}
for(Iterator nIt = libCell.getNodes(); nIt.hasNext(); )
{
NodeInst ni = (NodeInst)nIt.next();
NodeProto np = ni.getProto();
if (!(np instanceof Cell)) continue;
// ignore documentation icons
if (ni.isIconOfParent()) continue;
CheckInst ci = (CheckInst)checkInsts.get(ni);
CheckProto ocp = getCheckProto((Cell)np);
ci.offset = ocp.totalPerCell;
}
checkTimeStamp++;
for(Iterator nIt = libCell.getNodes(); nIt.hasNext(); )
{
NodeInst ni = (NodeInst)nIt.next();
NodeProto np = ni.getProto();
if (!(np instanceof Cell)) continue;
// ignore documentation icons
if (ni.isIconOfParent()) continue;
CheckProto ocp = getCheckProto((Cell)np);
if (ocp.timeStamp != checkTimeStamp)
{
CheckInst ci = (CheckInst)checkInsts.get(ni);
ocp.timeStamp = checkTimeStamp;
ocp.totalPerCell += subCP.hierInstanceCount * ci.multiplier;
}
}
}
// now fill in the hierarchical network arrays
checkTimeStamp = 0;
checkNetNumber = 1;
HashMap enumeratedNets = new HashMap();
for(Iterator nIt = cp.netlist.getNetworks(); nIt.hasNext(); )
{
Network net = (Network)nIt.next();
enumeratedNets.put(net, new Integer(checkNetNumber));
checkNetNumber++;
}
checkEnumerateNetworks(cell, cp, 0, enumeratedNets);
if (count <= 0)
System.out.println("Found " + checkNetNumber + " networks");
// now search for DRC exclusion areas
exclusionList.clear();
accumulateExclusion(cell);
// now do the DRC
boolean validVersion = true;
Version version = cell.getLibrary().getVersion();
if (version != null) validVersion = version.compareTo(Version.getVersion()) >=0;
errorLogger = null;
int logsFound = 0;
int totalErrors = 0;
if (count == 0)
{
// just do full DRC here
errorLogger = ErrorLogger.newInstance("DRC (full)");
totalErrors = checkThisCell(cell, 0, bounds, validVersion);
// sort the errors by layer
errorLogger.sortLogs();
} else
{
// check only these "count" instances (either an incremental DRC or a quiet one...from Array command)
if (validity == null)
{
// not a quiet DRC, so it must be incremental
if (errorLoggerIncremental == null) errorLoggerIncremental = ErrorLogger.newInstance("DRC (incremental)", true);
errorLoggerIncremental.clearLogs(cell);
errorLogger = errorLoggerIncremental;
logsFound = errorLoggerIncremental.getNumLogs();
}
// @TODO missing counting this number of errors.
checkTheseGeometrics(cell, count, geomsToCheck, validity);
}
if (errorLogger != null) {
errorLogger.termLogging(true);
logsFound = errorLogger.getNumLogs() - logsFound;
}
if (totalErrors != 0) goodDRCDate.clear();
// some cells were sucessfully checked: save that information in the database
// some cells don't have valid DRC date anymore and therefore they should be clean
// This is only going to happen if job was not aborted.
if ((job == null || !job.checkAbort()) && (goodDRCDate.size() > 0 || cleanDRCDate.size() > 0))
{
new UpdateDRCDates(goodDRCDate, cleanDRCDate);
}
return logsFound;
}
/**
* Class to save good DRC dates in a new thread.
*/
private static class UpdateDRCDates extends Job
{
HashMap goodDRCDate;
HashMap cleanDRCDate;
protected UpdateDRCDates(HashMap goodDRCDate, HashMap cleanDRCDate)
{
super("Remember DRC Successes and/or Delete Obsolete Dates", DRC.tool, Job.Type.CHANGE, null, null, Job.Priority.USER);
this.goodDRCDate = goodDRCDate;
this.cleanDRCDate = cleanDRCDate;
startJob();
}
public boolean doIt()
{
int bits = DRC.getActiveBits();
for(Iterator it = goodDRCDate.keySet().iterator(); it.hasNext(); )
{
Cell cell = (Cell)it.next();
Date now = (Date)goodDRCDate.get(cell);
DRC.setLastDRCDateAndBits(cell, now, bits);
}
for(Iterator it = cleanDRCDate.keySet().iterator(); it.hasNext(); )
{
Cell cell = (Cell)it.next();
DRC.cleanDRCDateAndBits(cell);
}
return true;
}
}
/*************************** QUICK DRC CELL EXAMINATION ***************************/
/**
* Method to check the contents of cell "cell" with global network index "globalIndex".
* Returns positive if errors are found, zero if no errors are found, negative on internal error.
*/
private int checkThisCell(Cell cell, int globalIndex, Rectangle2D bounds, boolean validVersion)
{
// Job aborted or scheduled for abort
if (job != null && job.checkAbort()) return -1;
// Cell already checked
if (cellsMap.get(cell) != null)
return (0);
// Previous # of errors/warnings
int prevErrors = 0;
int prevWarns = 0;
if (errorLogger != null)
{
prevErrors = errorLogger.getNumErrors();
prevWarns = errorLogger.getNumWarnings();
}
cellsMap.put(cell, cell);
// first check all subcells
boolean allSubCellsStillOK = true;
for(Iterator it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = (NodeInst)it.next();
NodeProto np = ni.getProto();
if (!(np instanceof Cell)) continue;
// ignore documentation icons
if (ni.isIconOfParent()) continue;
// ignore if not in the area
Rectangle2D subBounds = bounds; // sept30
if (subBounds != null)
{
if (!ni.getBounds().intersects(bounds)) continue;
AffineTransform trans = ni.rotateIn();
AffineTransform xTrnI = ni.translateIn();
trans.preConcatenate(xTrnI);
subBounds = new Rectangle2D.Double();
subBounds.setRect(bounds);
DBMath.transformRect(subBounds, trans);
}
CheckProto cp = getCheckProto((Cell)np);
if (cp.cellChecked && !cp.cellParameterized) continue;
// recursively check the subcell
CheckInst ci = (CheckInst)checkInsts.get(ni);
int localIndex = globalIndex * ci.multiplier + ci.localIndex + ci.offset;
int retval = checkThisCell((Cell)np, localIndex, subBounds, validVersion);
if (retval < 0)
return -1;
if (retval > 0) allSubCellsStillOK = false;
}
// prepare to check cell
CheckProto cp = getCheckProto(cell);
cp.cellChecked = true;
// if the cell hasn't changed since the last good check, stop now
if (validVersion && allSubCellsStillOK)
{
Date lastGoodDate = DRC.getLastDRCDateBasedOnBits(cell, activeBits);
if (lastGoodDate != null)
{
Date lastChangeDate = cell.getRevisionDate();
if (lastGoodDate.after(lastChangeDate)) return 0;
}
}
// announce progress
long startTime = System.currentTimeMillis();
System.out.println("Checking " + cell);
// now look at every node and arc here
totalMsgFound = 0;
// Check the area first but only when is not incremental
// Only for the most top cell
if (cell == topCell && !DRC.isIgnoreAreaChecking() && errorTypeSearch != DRC.ERROR_CHECK_CELL)
totalMsgFound = checkMinArea(cell);
//instanceInteractionList.clear(); test 1
for(Iterator it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = (NodeInst)it.next();
if (bounds != null)
{
if (!ni.getBounds().intersects(bounds)) continue;
}
boolean ret = (ni.getProto() instanceof Cell) ?
checkCellInst(ni, globalIndex) :
checkNodeInst(ni, globalIndex);
if (ret)
{
totalMsgFound++;
if (errorTypeSearch == DRC.ERROR_CHECK_CELL) break;
}
}
Technology cellTech = cell.getTechnology();
for(Iterator it = cell.getArcs(); it.hasNext(); )
{
ArcInst ai = (ArcInst)it.next();
Technology tech = ai.getProto().getTechnology();
if (tech != cellTech)
{
reportError(TECHMIXWARN, " belongs to " + tech.getTechName(), cell, 0, 0, null, null, ai, null, null, null, null);
continue;
}
if (bounds != null)
{
if (!ai.getBounds().intersects(bounds)) continue;
}
if (checkArcInst(cp, ai, globalIndex))
{
totalMsgFound++;
if (errorTypeSearch == DRC.ERROR_CHECK_CELL) break;
}
}
// If message founds, then remove any possible good date
if (totalMsgFound > 0 || !allSubCellsStillOK)
{
cleanDRCDate.put(cell, cell);
}
else
{
goodDRCDate.put(cell, new Date());
}
// if there were no errors, remember that
if (errorLogger != null)
{
int localErrors = errorLogger.getNumErrors() - prevErrors;
int localWarnings = errorLogger.getNumWarnings() - prevWarns;
long endTime = System.currentTimeMillis();
if (localErrors == 0 && localWarnings == 0)
{
System.out.println("\tNo errors/warnings found");
} else
{
if (localErrors > 0)
System.out.println("\tFOUND " + localErrors + " ERRORS");
if (localWarnings > 0)
System.out.println("\tFOUND " + localWarnings + " WARNINGS");
}
if (Main.getDebug())
System.out.println("\t(took " + TextUtils.getElapsedTime(endTime - startTime) + ")");
}
return totalMsgFound;
}
/**
* Check Poly for CIF Resolution Errors
* @param poly
* @param cell
* @param geom
* @return true if an error was found.
*/
private boolean checkResolution(PolyBase poly, Cell cell, Geometric geom)
{
if (minAllowedResolution == 0) return false;
int count = 0;
String resolutionError = "";
Point2D [] points = poly.getPoints();
for (int i=0; i<points.length; i++)
{
if (DBMath.hasRemainder(points[i].getX(), minAllowedResolution))
{
count++;
resolutionError = TextUtils.formatDouble(Math.abs(((points[i].getX()/minAllowedResolution) % 1) * minAllowedResolution)) +
"(X=" + points[i].getX() + ")";
// DBMath.hasRemainder(points[i].getX(), minAllowedResolution);
break; // with one error is enough
}
else if (DBMath.hasRemainder(points[i].getY(), minAllowedResolution))
{
count++;
resolutionError = TextUtils.formatDouble(Math.abs(((points[i].getY()/minAllowedResolution) % 1) * minAllowedResolution)) +
"(Y=" + points[i].getY() + ")";
// DBMath.hasRemainder(points[i].getY(), minAllowedResolution);
break;
}
}
if (count == 0) return false; // no error
// there was an error, for now print error
Layer layer = poly.getLayer();
reportError(RESOLUTION, " resolution of " + resolutionError + " less than " + minAllowedResolution + " on layer " + layer.getName(), cell, 0, 0, null, null, geom, null, null, null, null);
return true;
}
/**
* Method to check the design rules about nodeinst "ni".
* @param ni
* @param globalIndex
* @return true if an error was found.
*/
private boolean checkNodeInst(NodeInst ni, int globalIndex)
{
Cell cell = ni.getParent();
Netlist netlist = getCheckProto(cell).netlist;
NodeProto np = ni.getProto();
Technology tech = np.getTechnology();
AffineTransform trans = ni.rotateOut();
boolean errorsFound = false;
// Skipping special nodes
if (NodeInst.isSpecialNode(ni)) return false; // Oct 5;
if (np.getFunction() == PrimitiveNode.Function.PIN) return false; // Sept 30
// Already done
if (nodesMap.get(ni) != null)
return (false);
nodesMap.put(ni, ni);
if (np instanceof PrimitiveNode && DRC.isForbiddenNode(((PrimitiveNode)np).getPrimNodeIndexInTech(), DRCTemplate.FORBIDDEN, tech, techMode))
{
reportError(FORBIDDEN, " is not allowed by selected foundry", cell, -1, -1, null, null, ni, null, null, null, null);
if (errorTypeSearch == DRC.ERROR_CHECK_CELL) return true;
errorsFound = true;
}
// get all of the polygons on this node
Poly [] nodeInstPolyList = tech.getShapeOfNode(ni, null, null, true, ignoreCenterCuts, null);
convertPseudoLayers(ni, nodeInstPolyList);
int tot = nodeInstPolyList.length;
boolean isTransistor = np.getFunction().isTransistor();
// examine the polygons on this node
for(int j=0; j<tot; j++)
{
Poly poly = nodeInstPolyList[j];
Layer layer = poly.getLayer();
if (layer == null) continue;
// Checking combination
boolean ret = checkOD2Combination(tech, ni, layer);
if (ret)
{
// panic errors -> return regarless errorTypeSearch
return true;
}
poly.transform(trans);
// Checking resolution only after transformation
ret = checkResolution(poly, cell, ni);
if (ret)
{
if (errorTypeSearch == DRC.ERROR_CHECK_CELL) return true;
errorsFound = true;
}
// determine network for this polygon
int netNumber = getDRCNetNumber(netlist, poly.getPort(), ni, globalIndex);
ret = badBox(poly, layer, netNumber, tech, ni, trans, cell, globalIndex);
if (ret)
{
if (errorTypeSearch == DRC.ERROR_CHECK_CELL) return true;
errorsFound = true;
}
ret = checkMinWidth(ni, layer, poly, tot==1);
if (ret)
{
if (errorTypeSearch == DRC.ERROR_CHECK_CELL) return true;
errorsFound = true;
}
// Check PP.R.1 select over transistor poly
// Assumes polys on transistors fulfill condition by construction
ret = !isTransistor && checkSelectOverPolysilicon(ni, layer, poly, cell);
if (ret)
{
if (errorTypeSearch == DRC.ERROR_CHECK_CELL) return true;
errorsFound = true;
}
ret = checkExtensionRule(ni, layer, poly, cell);
if (ret)
{
if (errorTypeSearch == DRC.ERROR_CHECK_CELL) return true;
errorsFound = true;
}
if (tech == layersValidTech && !layersValid[layer.getIndex()])
{
reportError(BADLAYERERROR, null, cell, 0, 0, null,
poly, ni, layer, null, null, null);
if (errorTypeSearch == DRC.ERROR_CHECK_CELL) return true;
errorsFound = true;
}
}
// check node for minimum size
DRC.NodeSizeRule sizeRule = DRC.getMinSize(np);
if (sizeRule != null)
{
if (ni.getXSize() < sizeRule.sizeX || ni.getYSize() < sizeRule.sizeY)
{
SizeOffset so = ni.getSizeOffset();
double minSize = 0, actual = 0;
String msg = "X axis";
if (sizeRule.sizeX - ni.getXSize() > sizeRule.sizeY - ni.getYSize())
{
minSize = sizeRule.sizeX - so.getLowXOffset() - so.getHighXOffset();
actual = ni.getXSize() - so.getLowXOffset() - so.getHighXOffset();
} else
{
msg = "Y axis";
minSize = sizeRule.sizeY - so.getLowYOffset() - so.getHighYOffset();
actual = ni.getYSize() - so.getLowYOffset() - so.getHighYOffset();
}
reportError(MINSIZEERROR, msg, cell, minSize, actual, sizeRule.rule,
null, ni, null, null, null, null);
}
}
return errorsFound;
}
/**
* Method to check which combination of OD2 layers are allowed
* @param layer
* @return
*/
private boolean checkOD2Combination(Technology tech, NodeInst ni, Layer layer)
{
int funExtras = layer.getFunctionExtras();
boolean notOk = false;
if (layer.getFunction().isImplant() && (funExtras&Layer.Function.THICK) != 0)
{
// Only stores first node found
od2Layers.put(layer, ni);
// More than one type used.
if (od2Layers.size() != 1)
{
Set set = od2Layers.keySet();
Object[] keys = set.toArray();
for (int i = 0; i < set.size(); i++)
{
Layer lay1 = (Layer)keys[i];
if (lay1 == layer) continue;
int index = tech.getRuleIndex(lay1.getIndex(), layer.getIndex());
if (DRC.isForbiddenNode(index, DRCTemplate.COMBINATION, tech, techMode))
{
NodeInst node = (NodeInst)od2Layers.get(lay1);
String message = "- combination of layers '" + layer.getName() + "' and '" + lay1.getName() + "' (in '" +
node.getParent().getName() + ":" + node.getName() +"') not allowed by selected foundry";
reportError(FORBIDDEN, message, ni.getParent(), -1, -1, null, null, ni, null, null, node, null);
return true;
}
}
}
}
return notOk;
}
/**
* Method to check the design rules about arcinst "ai".
* Returns true if errors were found.
*/
private boolean checkArcInst(CheckProto cp, ArcInst ai, int globalIndex)
{
// ignore arcs with no topology
Network net = cp.netlist.getNetwork(ai, 0);
if (net == null) return false;
Integer [] netNumbers = (Integer [])networkLists.get(net);
if (nodesMap.get(ai) != null)
{
if (Main.LOCALDEBUGFLAG) System.out.println("Done already arc " + ai.getName());
return (false);
}
nodesMap.put(ai, ai);
// get all of the polygons on this arc
Technology tech = ai.getProto().getTechnology();
Poly [] arcInstPolyList = tech.getShapeOfArc(ai);
boolean errorsFound = false;
// Check resolution before cropping the
for(int j=0; j<arcInstPolyList.length; j++)
{
Poly poly = arcInstPolyList[j];
Layer layer = poly.getLayer();
if (layer == null) continue;
if (layer.isNonElectrical()) continue;
// Checking resolution
boolean ret = checkResolution(poly, ai.getParent(), ai);
if (ret)
{
if (errorTypeSearch == DRC.ERROR_CHECK_CELL) return true;
errorsFound = true;
}
}
cropActiveArc(ai, arcInstPolyList);
int tot = arcInstPolyList.length;
// examine the polygons on this arc
for(int j=0; j<tot; j++)
{
Poly poly = arcInstPolyList[j];
Layer layer = poly.getLayer();
if (layer == null) continue;
if (layer.isNonElectrical()) continue;
int layerNum = layer.getIndex();
int netNumber = netNumbers[globalIndex].intValue();
boolean ret = badBox(poly, layer, netNumber, tech, ai, DBMath.MATID, ai.getParent(), globalIndex);
if (ret)
{
if (errorTypeSearch == DRC.ERROR_CHECK_CELL) return true;
errorsFound = true;
}
ret = checkMinWidth(ai, layer, poly, tot==1);
if (ret)
{
if (errorTypeSearch == DRC.ERROR_CHECK_CELL) return true;
errorsFound = true;
}
// Check PP.R.1 select over transistor poly
ret = checkSelectOverPolysilicon(ai, layer, poly, ai.getParent());
if (ret)
{
if (errorTypeSearch == DRC.ERROR_CHECK_CELL) return true;
errorsFound = true;
}
if (tech == layersValidTech && !layersValid[layerNum])
{
reportError(BADLAYERERROR, null, ai.getParent(), 0, 0, null,
(tot==1)?null:poly, ai, layer, null, null, null);
if (errorTypeSearch == DRC.ERROR_CHECK_CELL) return true;
errorsFound = true;
}
}
return errorsFound;
}
/**
* Method to check the design rules about cell instance "ni". Only check other
* instances, and only check the parts of each that are within striking range.
* Returns true if an error was found.
*/
private boolean checkCellInst(NodeInst ni, int globalIndex)
{
// get transformation out of the instance
AffineTransform upTrans = ni.translateOut(ni.rotateOut());
// get network numbering for the instance
CheckInst ci = (CheckInst)checkInsts.get(ni);
int localIndex = globalIndex * ci.multiplier + ci.localIndex + ci.offset;
boolean errorFound = false;
// look for other instances surrounding this one
Rectangle2D nodeBounds = ni.getBounds();
Rectangle2D searchBounds = new Rectangle2D.Double(
nodeBounds.getMinX()-worstInteractionDistance,
nodeBounds.getMinY()-worstInteractionDistance,
nodeBounds.getWidth() + worstInteractionDistance*2,
nodeBounds.getHeight() + worstInteractionDistance*2);
instanceInteractionList.clear(); // part3
for(Iterator it = ni.getParent().searchIterator(searchBounds); it.hasNext(); )
{
Geometric geom = (Geometric)it.next();
if ( geom == ni ) continue; // covered by checkInteraction?
if (!(geom instanceof NodeInst)) continue;
NodeInst oNi = (NodeInst)geom;
// only check other nodes that are numerically higher (so each pair is only checked once)
if (oNi.getNodeIndex() <= ni.getNodeIndex()) continue;
if (!(oNi.getProto() instanceof Cell)) continue;
// see if this configuration of instances has already been done
if (checkInteraction(ni, null, null, oNi, null, null)) continue;
// found other instance "oNi", look for everything in "ni" that is near it
Rectangle2D nearNodeBounds = oNi.getBounds();
Rectangle2D subBounds = new Rectangle2D.Double(
nearNodeBounds.getMinX()-worstInteractionDistance,
nearNodeBounds.getMinY()-worstInteractionDistance,
nearNodeBounds.getWidth() + worstInteractionDistance*2,
nearNodeBounds.getHeight() + worstInteractionDistance*2);
// recursively search instance "ni" in the vicinity of "oNi"
boolean ret = checkCellInstContents(subBounds, ni, upTrans, localIndex, oNi, null, globalIndex, null);
if (ret) errorFound = true;
}
return errorFound;
}
/**
* Method to recursively examine the area "bounds" in cell "cell" with global index "globalIndex".
* The objects that are found are transformed by "uptrans" to be in the space of a top-level cell.
* They are then compared with objects in "oNi" (which is in that top-level cell),
* which has global index "topGlobalIndex".
*/
private boolean checkCellInstContents(Rectangle2D bounds, NodeInst thisNi, AffineTransform upTrans, int globalIndex,
NodeInst oNi, NodeInst oNiParent, int topGlobalIndex, NodeInst triggerNi)
{
// Job aborted or scheduled for abort
if (job != null && job.checkAbort()) return true;
Cell cell = (Cell)thisNi.getProto();
boolean logsFound = false;
Netlist netlist = getCheckProto(cell).netlist;
Technology cellTech = cell.getTechnology();
// Need to transform bounds coordinates first otherwise it won't
// never overlap
Rectangle2D bb = (Rectangle2D)bounds.clone();
AffineTransform downTrans = thisNi.transformIn();
DBMath.transformRect(bb, downTrans);
for(Iterator it = cell.searchIterator(bb); it.hasNext(); )
{
Geometric geom = (Geometric)it.next();
if (geom instanceof NodeInst)
{
NodeInst ni = (NodeInst)geom;
NodeProto np = ni.getProto();
if (NodeInst.isSpecialNode(ni)) continue; // Oct 5'04
if (np instanceof Cell)
{
// see if this configuration of instances has already been done
if (checkInteraction(ni, thisNi, upTrans, oNi, oNiParent, triggerNi)) continue; // Jan 27'05. Removed on May'05
// You can't discard by interaction becuase two cells could be visited many times
// during this type of checking
AffineTransform subUpTrans = ni.translateOut(ni.rotateOut());
subUpTrans.preConcatenate(upTrans);
CheckInst ci = (CheckInst)checkInsts.get(ni);
int localIndex = globalIndex * ci.multiplier + ci.localIndex + ci.offset;
// changes Sept04: subBound by bb
boolean ret = checkCellInstContents(bb, ni, subUpTrans, localIndex, oNi, oNiParent, topGlobalIndex,
(triggerNi==null)?ni:triggerNi);
if (ret)
{
if (errorTypeSearch == DRC.ERROR_CHECK_CELL) return true;
logsFound = true;
}
} else
{
AffineTransform rTrans = ni.rotateOut();
rTrans.preConcatenate(upTrans);
Technology tech = np.getTechnology();
Poly [] primPolyList = tech.getShapeOfNode(ni, null, null, true, ignoreCenterCuts, null);
convertPseudoLayers(ni, primPolyList);
int tot = primPolyList.length;
for(int j=0; j<tot; j++)
{
Poly poly = primPolyList[j];
Layer layer = poly.getLayer();
if (layer == null)
{
if (Main.LOCALDEBUGFLAG) System.out.println("When is this case?");
continue;
}
poly.transform(rTrans);
// determine network for this polygon
int net = getDRCNetNumber(netlist, poly.getPort(), ni, globalIndex);
boolean ret = badSubBox(poly, layer, net, tech, ni, rTrans,
globalIndex, oNi, topGlobalIndex);
if (ret)
{
if (errorTypeSearch == DRC.ERROR_CHECK_CELL) return true;
logsFound = true;
}
}
}
} else
{
ArcInst ai = (ArcInst)geom;
Technology tech = ai.getProto().getTechnology();
if (tech != cellTech)
{
reportError(TECHMIXWARN, " belongs to " + tech.getTechName(), cell, 0, 0, null, null, ai, null, null, null, null);
continue;
}
Poly [] arcPolyList = tech.getShapeOfArc(ai);
int tot = arcPolyList.length;
for(int j=0; j<tot; j++)
arcPolyList[j].transform(upTrans);
cropActiveArc(ai, arcPolyList);
for(int j=0; j<tot; j++)
{
Poly poly = arcPolyList[j];
Layer layer = poly.getLayer();
if (layer == null) continue;
if (layer.isNonElectrical()) continue;
Network jNet = netlist.getNetwork(ai, 0);
int net = -1;
if (jNet != null)
{
Integer [] netList = (Integer [])networkLists.get(jNet);
net = netList[globalIndex].intValue();
}
boolean ret = badSubBox(poly, layer, net, tech, ai, upTrans,
globalIndex, oNi, topGlobalIndex);
if (ret)
{
if (errorTypeSearch == DRC.ERROR_CHECK_CELL) return true;
logsFound = true;
}
}
}
}
return logsFound;
}
/**
* Method to examine polygon "poly" layer "layer" network "net" technology "tech" geometry "geom"
* which is in cell "cell" and has global index "globalIndex".
* The polygon is compared against things inside node "oNi", and that node's parent has global index "topGlobalIndex".
*/
private boolean badSubBox(Poly poly, Layer layer, int net, Technology tech, Geometric geom, AffineTransform trans,
int globalIndex, NodeInst oNi, int topGlobalIndex)
{
// see how far around the box it is necessary to search
double maxSize = poly.getMaxSize();
double bound = DRC.getMaxSurround(layer, maxSize);
if (bound < 0) return false;
// get bounds
Rectangle2D bounds = new Rectangle2D.Double();
bounds.setRect(poly.getBounds2D());
AffineTransform downTrans = oNi.rotateIn();
AffineTransform tTransI = oNi.translateIn();
downTrans.preConcatenate(tTransI);
DBMath.transformRect(bounds, downTrans);
AffineTransform upTrans = oNi.translateOut(oNi.rotateOut());
CheckInst ci = (CheckInst)checkInsts.get(oNi);
int localIndex = topGlobalIndex * ci.multiplier + ci.localIndex + ci.offset;
// determine if original object has multiple contact cuts
boolean baseMulti = false;
if (geom instanceof NodeInst)
{
baseMulti = tech.isMultiCutCase((NodeInst)geom);
}
// search in the area surrounding the box
bounds.setRect(bounds.getMinX()-bound, bounds.getMinY()-bound, bounds.getWidth()+bound*2, bounds.getHeight()+bound*2);
return (badBoxInArea(poly, layer, tech, net, geom, trans, globalIndex, bounds, (Cell)oNi.getProto(), localIndex,
oNi.getParent(), topGlobalIndex, upTrans, baseMulti, false));
// true in this case you don't want to check Geometric.objectsTouch(nGeom, geom) if nGeom and geom are in the
// same cell because they could come from different cell instances.
}
/**
* Method to examine a polygon to see if it has any errors with its surrounding area.
* The polygon is "poly" on layer "layer" on network "net" from technology "tech" from object "geom".
* Checking looks in cell "cell" global index "globalIndex".
* Object "geom" can be transformed to the space of this cell with "trans".
* Returns TRUE if a spacing error is found relative to anything surrounding it at or below
* this hierarchical level.
*/
private boolean badBox(Poly poly, Layer layer, int net, Technology tech, Geometric geom,
AffineTransform trans, Cell cell, int globalIndex)
{
// see how far around the box it is necessary to search
double maxSize = poly.getMaxSize();
double bound = DRC.getMaxSurround(layer, maxSize);
if (bound < 0) return false;
// get bounds
Rectangle2D bounds = new Rectangle2D.Double();
bounds.setRect(poly.getBounds2D());
// determine if original object has multiple contact cuts
boolean baseMulti = false;
if (geom instanceof NodeInst)
baseMulti = tech.isMultiCutCase((NodeInst)geom);
// search in the area surrounding the box
bounds.setRect(bounds.getMinX()-bound, bounds.getMinY()-bound, bounds.getWidth()+bound*2, bounds.getHeight()+bound*2);
return badBoxInArea(poly, layer, tech, net, geom, trans, globalIndex, bounds, cell, globalIndex,
cell, globalIndex, DBMath.MATID, baseMulti, true);
}
/**
* Method to recursively examine a polygon to see if it has any errors with its surrounding area.
* The polygon is "poly" on layer "layer" from technology "tech" on network "net" from object "geom"
* which is associated with global index "globalIndex".
* Checking looks in the area (lxbound-hxbound, lybound-hybound) in cell "cell" global index "cellGlobalIndex".
* The polygon coordinates are in the space of cell "topCell", global index "topGlobalIndex",
* and objects in "cell" can be transformed by "upTrans" to get to this space.
* The base object, in "geom" can be transformed by "trans" to get to this space.
* The minimum size of this polygon is "minSize" and "baseMulti" is TRUE if it comes from a multicut contact.
* If the two objects are in the same cell instance (nonhierarchical DRC), then "sameInstance" is TRUE.
* If they are from different instances, then "sameInstance" is FALSE.
*
* Returns TRUE if errors are found.
*/
private boolean badBoxInArea(Poly poly, Layer layer, Technology tech, int net, Geometric geom, AffineTransform trans,
int globalIndex, Rectangle2D bounds, Cell cell, int cellGlobalIndex,
Cell topCell, int topGlobalIndex, AffineTransform upTrans, boolean baseMulti,
boolean sameInstance)
{
Rectangle2D rBound = new Rectangle2D.Double();
rBound.setRect(bounds);
DBMath.transformRect(rBound, upTrans); // Step 1
Netlist netlist = getCheckProto(cell).netlist;
Rectangle2D subBound = new Rectangle2D.Double(); //Sept 30
boolean foundError = false;
// These nodes won't generate any DRC errors. Most of them are pins
if (geom instanceof NodeInst && NodeInst.isSpecialNode(((NodeInst)geom)))
return false;
// Sept04 changes: bounds by rBound
for(Iterator it = cell.searchIterator(bounds); it.hasNext(); )
{
Geometric nGeom = (Geometric)it.next();
// I have to check if they are the same instance otherwise I check geometry against itself
if (nGeom == geom && (sameInstance))// || nGeom.getParent() == cell))
continue;
if (nGeom instanceof NodeInst)
{
NodeInst ni = (NodeInst)nGeom;
NodeProto np = ni.getProto();
if (NodeInst.isSpecialNode(ni)) continue; // Oct 5;
// ignore nodes that are not primitive
if (np instanceof Cell)
{
// instance found: look inside it for offending geometry
AffineTransform rTransI = ni.rotateIn();
AffineTransform tTransI = ni.translateIn();
rTransI.preConcatenate(tTransI);
subBound.setRect(bounds);
DBMath.transformRect(subBound, rTransI);
CheckInst ci = (CheckInst)checkInsts.get(ni);
int localIndex = cellGlobalIndex * ci.multiplier + ci.localIndex + ci.offset;
AffineTransform subTrans = ni.translateOut(ni.rotateOut());
subTrans.preConcatenate(upTrans); //Sept 15 04
// compute localIndex
if (badBoxInArea(poly, layer, tech, net, geom, trans, globalIndex, subBound, (Cell)np, localIndex,
topCell, topGlobalIndex, subTrans, baseMulti, sameInstance))
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
} else
{
// don't check between technologies
if (np.getTechnology() != tech) continue;
// see if this type of node can interact with this layer
if (!checkLayerWithNode(layer, np)) continue;
// see if the objects directly touch but they are not
// coming from different NodeInst (not from checkCellInstContents
// because they might below to the same cell but in different instances
boolean touch = sameInstance && Geometric.objectsTouch(nGeom, geom);
// prepare to examine every layer in this nodeinst
AffineTransform rTrans = ni.rotateOut();
rTrans.preConcatenate(upTrans);
// get the shape of each nodeinst layer
Poly [] subPolyList = tech.getShapeOfNode(ni, null, null, true, ignoreCenterCuts, null);
convertPseudoLayers(ni, subPolyList);
int tot = subPolyList.length;
for(int i=0; i<tot; i++)
subPolyList[i].transform(rTrans);
/* Step 1 */
boolean multi = baseMulti;
if (!multi) multi = tech.isMultiCutCase(ni);
int multiInt = (multi) ? 1 : 0;
for(int j=0; j<tot; j++)
{
Poly npoly = subPolyList[j];
Layer nLayer = npoly.getLayer();
if (nLayer == null) continue;
//npoly.transform(rTrans);
Rectangle2D nPolyRect = npoly.getBounds2D();
// can't do this because "lxbound..." is local but the poly bounds are global
// On the corners?
- if (nPolyRect.getMinX() > rBound.getMaxX() ||
- nPolyRect.getMaxX() < rBound.getMinX() ||
- nPolyRect.getMinY() > rBound.getMaxY() ||
- nPolyRect.getMaxY() < rBound.getMinY()) continue;
+// if (nPolyRect.getMinX() > rBound.getMaxX() ||
+// nPolyRect.getMaxX() < rBound.getMinX() ||
+// nPolyRect.getMinY() > rBound.getMaxY() ||
+// nPolyRect.getMaxY() < rBound.getMinY())
+// continue;
+ if (DBMath.isGreaterThan(nPolyRect.getMinX(), rBound.getMaxX()) ||
+ DBMath.isGreaterThan(rBound.getMinX(), nPolyRect.getMaxX()) ||
+ DBMath.isGreaterThan(nPolyRect.getMinY(), rBound.getMaxY()) ||
+ DBMath.isGreaterThan(rBound.getMinY(), nPolyRect.getMaxY()))
+ continue;
// determine network for this polygon
int nNet = getDRCNetNumber(netlist, npoly.getPort(), ni, cellGlobalIndex);
// see whether the two objects are electrically connected
boolean con = false;
if (nNet >= 0 && nNet == net) con = true;
// Checking extension, it could be slow
boolean ret = checkExtensionGateRule(geom, layer, poly, nLayer, npoly, netlist);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
// check if both polys are cut and if the combine area doesn't excess cut sizes
// regardless if they are connected or not
ret = checkCutSizes(np, geom, layer, poly, nGeom, nLayer, npoly, topCell);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
// if they connect electrically and adjoin, don't check
if (con && touch)
{
// Check if there are minimum size defects
boolean maytouch = mayTouch(tech, con, layer, nLayer);
Rectangle2D trueBox1 = poly.getBox();
if (trueBox1 == null) trueBox1 = poly.getBounds2D();
Rectangle2D trueBox2 = npoly.getBox();
if (trueBox2 == null) trueBox1 = npoly.getBounds2D();
ret = checkMinDefects(cell,maytouch, geom, poly, trueBox1, layer,
nGeom, npoly, trueBox2, nLayer, topCell);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
continue;
}
boolean edge = false;
DRCTemplate theRule = getSpacingRule(layer, poly, nLayer, npoly, con, multiInt);
if (theRule == null)
{
theRule = DRC.getEdgeRule(layer, nLayer, techMode);
edge = true;
}
if (theRule != null)
{
// check the distance
ret = checkDist(tech, topCell, topGlobalIndex,
poly, layer, net, geom, trans, globalIndex,
npoly, nLayer, nNet, nGeom, rTrans, cellGlobalIndex,
con, theRule, edge);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
}
}
}
} else
{
ArcInst ai = (ArcInst)nGeom;
ArcProto ap = ai.getProto();
// don't check between technologies
if (ap.getTechnology() != tech) continue;
// see if this type of arc can interact with this layer
if (!checkLayerWithArc(layer, ap)) continue;
// see if the objects directly touch
boolean touch = sameInstance && Geometric.objectsTouch(nGeom, geom);
// see whether the two objects are electrically connected
Network jNet = netlist.getNetwork(ai, 0);
Integer [] netNumbers = (Integer [])networkLists.get(jNet);
int nNet = netNumbers[cellGlobalIndex].intValue();
boolean con = false;
if (net >= 0 && nNet == net) con = true;
// if they connect electrically and adjoin, don't check
// if (con && touch) continue;
// get the shape of each arcinst layer
Poly [] subPolyList = tech.getShapeOfArc(ai);
int tot = subPolyList.length;
for(int i=0; i<tot; i++)
subPolyList[i].transform(upTrans);
cropActiveArc(ai, subPolyList);
boolean multi = baseMulti;
int multiInt = (multi) ? 1 : 0;
for(int j=0; j<tot; j++)
{
Poly nPoly = subPolyList[j];
Layer nLayer = nPoly.getLayer();
if (nLayer == null) continue;
Rectangle2D nPolyRect = nPoly.getBounds2D();
// can't do this because "lxbound..." is local but the poly bounds are global
if (nPolyRect.getMinX() > rBound.getMaxX() ||
nPolyRect.getMaxX() < rBound.getMinX() ||
nPolyRect.getMinY() > rBound.getMaxY() ||
nPolyRect.getMaxY() < rBound.getMinY()) continue;
boolean ret = false;
// if they connect electrically and adjoin, don't check
// We must check if there are minor defects if they overlap regardless if they are connected or not
if (con && touch)
{
// Check if there are minimum size defects
boolean maytouch = mayTouch(tech, con, layer, nLayer);
Rectangle2D trueBox1 = poly.getBox();
if (trueBox1 == null) trueBox1 = poly.getBounds2D();
Rectangle2D trueBox2 = nPoly.getBox();
if (trueBox2 == null) trueBox1 = nPoly.getBounds2D();
ret = checkMinDefects(cell, maytouch, geom, poly, trueBox1, layer,
nGeom, nPoly, trueBox2, nLayer, topCell);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
continue;
}
// see how close they can get
boolean edge = false;
DRCTemplate theRule = getSpacingRule(layer, poly, nLayer, nPoly, con, multiInt);
if (theRule == null)
{
theRule = DRC.getEdgeRule(layer, nLayer, techMode);
edge = true;
}
if (theRule == null) continue;
// check the distance
ret = checkDist(tech, topCell, topGlobalIndex, poly, layer, net, geom, trans, globalIndex,
nPoly, nLayer, nNet, nGeom, upTrans, cellGlobalIndex, con, theRule, edge);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
// Checking extension, it could be slow
ret = checkExtensionGateRule(geom, layer, poly, nLayer, nPoly, netlist);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
}
}
}
return foundError;
}
/**
* Function to detect small edges due to overlapping polygons of the same material. It is valid only
* for manhattan shapes
* @return true if error was found
*/
private boolean checkMinDefects(Cell cell, boolean maytouch, Geometric geom1, Poly poly1, Rectangle2D trueBox1, Layer layer1,
Geometric geom2, Poly poly2, Rectangle2D trueBox2, Layer layer2, Cell topCell)
{
if (trueBox1 == null || trueBox2 == null) return false;
if (!maytouch) return false;
// manhattan
double pdx = Math.max(trueBox2.getMinX()-trueBox1.getMaxX(), trueBox1.getMinX()-trueBox2.getMaxX());
double pdy = Math.max(trueBox2.getMinY()-trueBox1.getMaxY(), trueBox1.getMinY()-trueBox2.getMaxY());
double pd = Math.max(pdx, pdy);
if (pdx == 0 && pdy == 0) pd = 0; // touching
boolean foundError = false;
// They have to overlap
if (pd > 0) return false;
// they are electrically connected and they overlap: look for minimum size errors
// of the overlapping region.
DRCTemplate wRule = DRC.getMinValue(layer1, DRCTemplate.MINWID, techMode);
if (wRule == null) return false; // no rule
double minWidth = wRule.value1;
double lxb = Math.max(trueBox1.getMinX(), trueBox2.getMinX());
double hxb = Math.min(trueBox1.getMaxX(), trueBox2.getMaxX());
double lyb = Math.max(trueBox1.getMinY(), trueBox2.getMinY());
double hyb = Math.min(trueBox1.getMaxY(), trueBox2.getMaxY());
Point2D lowB = new Point2D.Double(lxb, lyb);
Point2D highB = new Point2D.Double(hxb, hyb);
Rectangle2D bounds = new Rectangle2D.Double(lxb, lyb, hxb-lxb, hyb-lyb);
// If resulting bounding box is identical to one of the original polygons
// then one polygon is contained in the other one
if (bounds.equals(trueBox1) || bounds.equals(trueBox2))
{
return false;
}
//+-------------------+F
//| |
//| |
//| |B E
//| +-------+---------+
//| | | |
//|C A| | |
//+-----------+-------+ |
// | |
// D+-----------------+
// Checking A-B distance
double actual = lowB.distance(highB);
if (actual != 0 && DBMath.isGreaterThan(minWidth, actual) &&
foundSmallSizeDefect(cell, geom1, poly1, layer1, geom2, poly2, pd, lxb, lyb, hxb, hyb))
{
reportError(MINWIDTHERROR, null, topCell, minWidth, actual, wRule.ruleName, new Poly(bounds),
geom1, layer1, null, geom2, layer2);
foundError = true;
}
return foundError;
}
private boolean foundSmallSizeDefect(Cell cell, Geometric geom1, Poly poly1, Layer layer1,
Geometric geom2, Poly poly2,
double pd, double lxb, double lyb, double hxb, double hyb)
{
boolean foundError = false;
boolean [] pointsFound = new boolean[2];
pointsFound[0] = pointsFound[1] = false;
Point2D lowB = new Point2D.Double(lxb, lyb);
Point2D highB = new Point2D.Double(hxb, hyb);
Rectangle2D bounds = new Rectangle2D.Double(lxb, lyb, hxb-lxb, hyb-lyb);
Poly rebuild = new Poly(bounds);
Point2D pt1 = new Point2D.Double(lxb-TINYDELTA, lyb-TINYDELTA);
Point2D pt2 = new Point2D.Double(lxb-TINYDELTA, hyb+TINYDELTA);
Point2D pt1d = (Point2D)pt1.clone();
Point2D pt2d = (Point2D)pt2.clone();
// Search area should be bigger than bounding box otherwise it might not get the cells due to
// rounding errors.
Rectangle2D search = new Rectangle2D.Double(DBMath.round(lxb-TINYDELTA), DBMath.round(lyb-TINYDELTA),
DBMath.round(hxb-lxb+2*TINYDELTA), DBMath.round(hyb-lyb+2*TINYDELTA));
// Looking for two corners not inside bounding boxes A and B
if (pd == 0) // flat bounding box
{
pt1 = lowB;
pt2 = highB;
pt1d = lowB;
pt2d = highB;
}
else
{
Point2D[] points = rebuild.getPoints();
int[] cornerPoints = new int[2];
int corners = 0; // if more than 3 corners are found -> bounding box is flat
for (int i = 0; i < points.length && corners < 2; i++)
{
if (!DBMath.pointInsideRect(points[i], poly1.getBounds2D()) &&
!DBMath.pointInsideRect(points[i], poly2.getBounds2D()))
{
cornerPoints[corners++] = i;
}
}
if (corners != 2)
throw new Error("Wrong corners in Quick.foundSmallSizeDefect()");
pt1 = points[cornerPoints[0]];
pt2 = points[cornerPoints[1]];
double delta = ((pt2.getY() - pt1.getY())/(pt2.getX() - pt1.getX()) > 0) ? 1 : -1;
// getting point lightly out of the elements
if (pt1.getX() < pt2.getX())
{
// (y2-y1)/(x2-x1)(x1-tinydelta-x1) + y1
pt1d = new Point2D.Double(pt1.getX()-TINYDELTA, -delta*TINYDELTA+pt1.getY());
// (y2-y1)/(x2-x1)(x2+tinydelta-x2) + y2
pt2d = new Point2D.Double(pt2.getX()+TINYDELTA, delta*TINYDELTA+pt2.getY());
}
else
{
pt1d = new Point2D.Double(pt2.getX()-TINYDELTA, -delta*TINYDELTA+pt2.getY());
pt2d = new Point2D.Double(pt1.getX()+TINYDELTA, delta*TINYDELTA+pt1.getY());
}
}
if (DBMath.areEquals(pt1.getX(), pt2.getX()) || DBMath.areEquals(pt1.getY(), pt2.getY()))
{
// if (Main.LOCALDEBUGFLAG) System.out.println("Escaping this case as the points are not at opposite corners");
return false;
}
// looking if points around the overlapping area are inside another region
// to avoid the error
lookForLayerNew(geom1, poly1, geom2, poly2, cell, layer1, DBMath.MATID, search,
pt1d, pt2d, null, pointsFound, false);
// Nothing found
if (!pointsFound[0] && !pointsFound[1])
{
foundError = true;
}
return (foundError);
}
/**
* Method to determine if it is allowed to have both layers touching.
* special rule for allowing touching:
* the layers are the same and either:
* they connect and are *NOT* contact layers
* or:
* they don't connect and are implant layers (substrate/well)
* @param tech
* @param con
* @param layer1
* @param layer2
* @return
*/
private boolean mayTouch(Technology tech, boolean con, Layer layer1, Layer layer2)
{
boolean maytouch = false;
if (tech.sameLayer(layer1, layer2))
{
Layer.Function fun = layer1.getFunction();
if (con)
{
if (!fun.isContact()) maytouch = true;
} else
{
if (fun.isSubstrate()) maytouch = true;
// Special cases for thick actives
else
{
// Searching for THICK bit
int funExtras = layer1.getFunctionExtras();
if (fun.isDiff() && (funExtras&Layer.Function.THICK) != 0)
{
if (Main.LOCALDEBUGFLAG) System.out.println("Thick active found in Quick.checkDist");
maytouch = true;
}
}
}
}
return maytouch;
}
/**
* Method to compare:
* polygon "poly1" layer "layer1" network "net1" object "geom1"
* with:
* polygon "poly2" layer "layer2" network "net2" object "geom2"
* The polygons are both in technology "tech" and are in the space of cell "cell"
* which has global index "globalIndex".
* Note that to transform object "geom1" to this space, use "trans1" and to transform
* object "geom2" to this space, use "trans2".
* They are connected if "con" is nonzero.
* They cannot be less than "dist" apart (if "edge" is nonzero, check edges only)
* and the rule for this is "rule".
*
* Returns TRUE if an error has been found.
*/
private boolean checkDist(Technology tech, Cell cell, int globalIndex,
Poly poly1, Layer layer1, int net1, Geometric geom1, AffineTransform trans1, int globalIndex1,
Poly poly2, Layer layer2, int net2, Geometric geom2, AffineTransform trans2, int globalIndex2,
boolean con, DRCTemplate theRule, boolean edge)
{
// turn off flag that the nodeinst may be undersized
tinyNodeInst = null;
Poly origPoly1 = poly1;
Poly origPoly2 = poly2;
Rectangle2D isBox1 = poly1.getBox();
Rectangle2D trueBox1 = isBox1;
if (trueBox1 == null) trueBox1 = poly1.getBounds2D();
Rectangle2D isBox2 = poly2.getBox();
Rectangle2D trueBox2 = isBox2;
if (trueBox2 == null) trueBox2 = poly2.getBounds2D();
boolean errorFound = false; // remember if there was a min defect error
boolean maytouch = mayTouch(tech, con, layer1, layer2);
// special code if both polygons are manhattan
double pd = 0;
boolean overlap = false;
if (isBox1 != null && isBox2 != null)
{
// manhattan
double pdx = Math.max(trueBox2.getMinX()-trueBox1.getMaxX(), trueBox1.getMinX()-trueBox2.getMaxX());
double pdy = Math.max(trueBox2.getMinY()-trueBox1.getMaxY(), trueBox1.getMinY()-trueBox2.getMaxY());
pd = Math.max(pdx, pdy);
if (pdx == 0 && pdy == 0) pd = 0; // touching
if (maytouch)
{
// they are electrically connected: see if they touch
overlap = (pd < 0);
if (checkMinDefects(cell, maytouch, geom1, poly1, trueBox1, layer2, geom2, poly2, trueBox2, layer2, cell))
{
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
errorFound = true;
}
}
// crop out parts of any arc that is covered by an adjoining node
trueBox1 = new Rectangle2D.Double(trueBox1.getMinX(), trueBox1.getMinY(), trueBox1.getWidth(), trueBox1.getHeight());
trueBox2 = new Rectangle2D.Double(trueBox2.getMinX(), trueBox2.getMinY(), trueBox2.getWidth(), trueBox2.getHeight());
if (geom1 instanceof NodeInst)
{
if (cropNodeInst((NodeInst)geom1, globalIndex1, trans1,
layer2, net2, geom2, trueBox2))
return errorFound;
} else
{
if (cropArcInst((ArcInst)geom1, layer1, trans1, trueBox1))
return errorFound;
}
if (geom2 instanceof NodeInst)
{
if (cropNodeInst((NodeInst)geom2, globalIndex2, trans2,
layer1, net1, geom1, trueBox1))
return errorFound;
} else
{
if (cropArcInst((ArcInst)geom2, layer2, trans2, trueBox2))
return errorFound;
}
poly1 = new Poly(trueBox1);
poly1.setStyle(Poly.Type.FILLED);
poly2 = new Poly(trueBox2);
poly2.setStyle(Poly.Type.FILLED);
// compute the distance
double lX1 = trueBox1.getMinX(); double hX1 = trueBox1.getMaxX();
double lY1 = trueBox1.getMinY(); double hY1 = trueBox1.getMaxY();
double lX2 = trueBox2.getMinX(); double hX2 = trueBox2.getMaxX();
double lY2 = trueBox2.getMinY(); double hY2 = trueBox2.getMaxY();
if (edge)
{
// calculate the spacing between the box edges
double pdedge = Math.min(
Math.min(Math.min(Math.abs(lX1-lX2), Math.abs(lX1-hX2)), Math.min(Math.abs(hX1-lX2), Math.abs(hX1-hX2))),
Math.min(Math.min(Math.abs(lY1-lY2), Math.abs(lY1-hY2)), Math.min(Math.abs(hY1-lY2), Math.abs(hY1-hY2))));
pd = Math.max(pd, pdedge);
} else
{
pdx = Math.max(lX2-hX1, lX1-hX2);
pdy = Math.max(lY2-hY1, lY1-hY2);
if (pdx == 0 && pdy == 0)
pd = 0; // they are touching!!
else
{
// They are overlapping if pdx < 0 && pdy < 0
pd = DBMath.round(Math.max(pdx, pdy));
if (pd < theRule.value1 && pd > 0)
{
pd = poly1.separation(poly2);
}
}
}
} else
{
// nonmanhattan
Poly.Type style = poly1.getStyle();
if (style != Poly.Type.FILLED && style != Poly.Type.CLOSED &&
style != Poly.Type.CROSSED && style != Poly.Type.OPENED &&
style != Poly.Type.OPENEDT1 && style != Poly.Type.OPENEDT2 &&
style != Poly.Type.OPENEDT3 && style != Poly.Type.VECTORS) return errorFound;
style = poly2.getStyle();
if (style != Poly.Type.FILLED && style != Poly.Type.CLOSED &&
style != Poly.Type.CROSSED && style != Poly.Type.OPENED &&
style != Poly.Type.OPENEDT1 && style != Poly.Type.OPENEDT2 &&
style != Poly.Type.OPENEDT3 && style != Poly.Type.VECTORS) return errorFound;
// make sure polygons don't intersect
//@TODO combine this calculation otherwise Poly.intersects is called twice!
double pd1 = poly1.separation(poly2);
if (poly1.intersects(poly2)) pd = 0;
else
{
// find distance between polygons
pd = poly1.separation(poly2);
}
if (pd1 != pd)
System.out.println("Wrong case in non-nonmanhattan, Quick.");
}
int errorType = SPACINGERROR;
if (theRule.ruleType == DRCTemplate.SURROUND)
{
if (pd > 0) // layers don't overlap -> no condition to check
return errorFound;
pd = Math.abs(pd);
errorType = SURROUNDERROR;
}
// see if the design rule is met
if (pd >= theRule.value1) // default case: SPACING
{
return errorFound;
}
if (theRule.ruleType != DRCTemplate.SURROUND)
{
/*
* special case: ignore errors between two active layers connected
* to either side of a field-effect transistor that is inside of
* the error area.
*/
if (activeOnTransistor(poly1, layer1, net1, poly2, layer2, net2, cell, globalIndex))
return errorFound;
/**
* Special case: ignore spacing errors generated by rule VT{H/L}_{P/N}.S.2 if poly is already
* part of a VTH-transistors. Not very elegant solution but should work for now.
*/
if (polyCoverByAnyVTLayer(cell, theRule, tech, new Poly[]{poly1, poly2}, new Layer[]{layer1, layer2}, new Geometric[]{geom1, geom2}))
return errorFound;
// special cases if the layers are the same
if (tech.sameLayer(layer1, layer2))
{
// special case: check for "notch"
if (maytouch)
{
// if they touch, it is acceptable
if (pd <= 0) return errorFound;
// see if the notch is filled
boolean newR = lookForCrossPolygons(geom1, poly1, geom2, poly2, layer1, cell, overlap);
if (Main.LOCALDEBUGFLAG)
{
Point2D pt1 = new Point2D.Double();
Point2D pt2 = new Point2D.Double();
int intervening = findInterveningPoints(poly1, poly2, pt1, pt2, false);
if (intervening == 0)
{
if (!newR)
{
System.out.println("DIfferent");
lookForCrossPolygons(geom1, poly1, geom2, poly2, layer1, cell, overlap);
}
//return false;
}
boolean needBoth = true;
if (intervening == 1) needBoth = false;
if (lookForPoints(pt1, pt2, layer1, cell, needBoth))
{
if (!newR)
{
System.out.println("DIfferent");
lookForPoints(pt1, pt2, layer1, cell, needBoth);
lookForCrossPolygons(geom1, poly1, geom2, poly2, layer1, cell, overlap);
//return false;
}
}
boolean oldR = lookForPoints(pt1, pt2, layer1, cell, needBoth);
if (oldR != newR)
System.out.println("DIfferent 2");
}
if (newR) return errorFound;
// look further if on the same net and diagonally separate (1 intervening point)
//if (net1 == net2 && intervening == 1) return false;
errorType = NOTCHERROR;
}
}
}
String msg = null;
if (tinyNodeInst != null)
{
// see if the node/arc that failed was involved in the error
if ((tinyNodeInst == geom1 || tinyNodeInst == geom2) &&
(tinyGeometric == geom1 || tinyGeometric == geom2))
{
msg = tinyNodeInst + " is too small for the " + tinyGeometric;
}
}
reportError(errorType, msg, cell, theRule.value1, pd, theRule.ruleName, origPoly1, geom1, layer1, origPoly2, geom2, layer2);
return true;
}
private static final List vtLayers = new ArrayList(2);
static {
vtLayers.add(Layer.Function.IMPLANTP);
vtLayers.add(Layer.Function.IMPLANTN);
};
/**
* This method determines if one of the polysilicon polygons is covered by a vth layer. If yes, VT{H/L}_{P/N}.S.2
* doesn't apply
* @param polys
* @param layers
* @param geoms
* @return
*/
private boolean polyCoverByAnyVTLayer(Cell cell, DRCTemplate theRule, Technology tech, Poly[] polys, Layer[] layers, Geometric[] geoms)
{
// Not the correct rule
if (theRule.ruleType != DRCTemplate.UCONSPA || !theRule.ruleName.equalsIgnoreCase("VT{H/L}_{P/N}.S.2"))
return false;
int polyIndex = -1, vtIndex = -1;
for (int i = 0; i < polys.length; i++)
{
Layer.Function fun = layers[i].getFunction();
int funExtras = layers[i].getFunctionExtras();
if (fun.isGatePoly())
polyIndex = i;
else if (fun.isImplant() && (funExtras&Layer.Function.HLVT) != 0)
vtIndex = i;
}
// Not the correct layers
if (polyIndex == -1 || vtIndex == -1)
return false;
if (geoms[polyIndex] instanceof NodeInst)
{
NodeProto np = ((NodeInst)geoms[polyIndex]).getProto();
if (np instanceof PrimitiveNode && ((PrimitiveNode)np).getSpecialType() == PrimitiveNode.HIGHLOWVT)
return true; // condition valid by construction
}
Rectangle2D searchBounds = polys[polyIndex].getBounds2D();
// Searches for any posible VTH/VTH that fully covers the polysilicon.
// It has to be recursive and could be expensive
for (Iterator it = cell.searchIterator(searchBounds); it.hasNext(); )
{
Geometric geom = (Geometric)it.next();
if (geom == geoms[vtIndex]) continue; // skipping original VT node
if (geom instanceof ArcInst) continue; // no arcs with such layer
NodeInst oNi = (NodeInst)geom;
if (oNi.getProto() instanceof Cell)
System.out.println("Recursive checking no implemented in polyCoverByAnyVTLayer");
else
{
Poly[] vtPolys = tech.getShapeOfNode(oNi, null, null, true, ignoreCenterCuts, vtLayers);
for (int i = 0; i < vtPolys.length; i++)
{
Poly poly = vtPolys[i];
// An approximation. Bounding box contains the given polygon associated to the poly
if (polys[polyIndex].isInside(poly.getBounds2D()))
return true;
}
}
}
return false;
}
/*************************** QUICK DRC SEE IF GEOMETRICS CAUSE ERRORS ***************************/
/**
* Method to examine, in cell "cell", the "count" instances in "geomsToCheck".
* If they are DRC clean, set the associated entry in "validity" to TRUE.
*/
private void checkTheseGeometrics(Cell cell, int count, Geometric [] geomsToCheck, boolean [] validity)
{
CheckProto cp = getCheckProto(cell);
// loop through all of the objects to be checked
for(int i=0; i<count; i++)
{
Geometric geomToCheck = geomsToCheck[i];
boolean errors = false;
if (geomToCheck instanceof NodeInst)
{
NodeInst ni = (NodeInst)geomToCheck;
if (ni.getProto() instanceof Cell)
{
errors = checkThisCellPlease(ni);
} else
{
errors = checkNodeInst(ni, 0);
}
} else
{
ArcInst ai = (ArcInst)geomToCheck;
errors = checkArcInst(cp, ai, 0);
}
if (validity != null) validity[i] = !errors;
}
}
private boolean checkThisCellPlease(NodeInst ni)
{
Cell cell = ni.getParent();
Netlist netlist = getCheckProto(cell).netlist;
int globalIndex = 0;
// get transformation out of this instance
AffineTransform upTrans = ni.translateOut(ni.rotateOut());
// get network numbering information for this instance
CheckInst ci = (CheckInst)checkInsts.get(ni);
if (ci == null) return false;
int localIndex = globalIndex * ci.multiplier + ci.localIndex + ci.offset;
// look for other objects surrounding this one
Rectangle2D nodeBounds = ni.getBounds();
Rectangle2D searchBounds = new Rectangle2D.Double(
nodeBounds.getMinX() - worstInteractionDistance,
nodeBounds.getMinY() - worstInteractionDistance,
nodeBounds.getWidth() + worstInteractionDistance*2,
nodeBounds.getHeight() + worstInteractionDistance*2);
for(Iterator it = cell.searchIterator(searchBounds); it.hasNext(); )
{
Geometric geom = (Geometric)it.next();
if ( geom == ni ) continue;
if (geom instanceof ArcInst)
{
if (checkGeomAgainstInstance(netlist, geom, ni)) return true;
continue;
}
NodeInst oNi = (NodeInst)geom;
if (oNi.getProto() instanceof PrimitiveNode)
{
// found a primitive node: check it against the instance contents
if (checkGeomAgainstInstance(netlist, geom, ni)) return true;
continue;
}
// found other instance "oNi", look for everything in "ni" that is near it
Rectangle2D subNodeBounds = oNi.getBounds();
Rectangle2D subBounds = new Rectangle2D.Double(
subNodeBounds.getMinX() - worstInteractionDistance,
subNodeBounds.getMinY() - worstInteractionDistance,
subNodeBounds.getWidth() + worstInteractionDistance*2,
subNodeBounds.getHeight() + worstInteractionDistance*2);
// recursively search instance "ni" in the vicinity of "oNi"
if (checkCellInstContents(subBounds, ni, upTrans, localIndex, oNi, null, globalIndex, null)) return true;
}
return false;
}
/**
* Method to check primitive object "geom" (an arcinst or primitive nodeinst) against cell instance "ni".
* Returns TRUE if there are design-rule violations in their interaction.
*/
private boolean checkGeomAgainstInstance(Netlist netlist, Geometric geom, NodeInst ni)
{
NodeProto np = ni.getProto();
int globalIndex = 0;
Cell subCell = geom.getParent();
boolean baseMulti = false;
Technology tech = null;
Poly [] nodeInstPolyList = null;
AffineTransform trans = DBMath.MATID;
if (geom instanceof NodeInst)
{
// get all of the polygons on this node
NodeInst oNi = (NodeInst)geom;
tech = oNi.getProto().getTechnology();
trans = oNi.rotateOut();
nodeInstPolyList = tech.getShapeOfNode(oNi, null, null, true, ignoreCenterCuts, null);
convertPseudoLayers(oNi, nodeInstPolyList);
baseMulti = tech.isMultiCutCase(oNi);
} else
{
ArcInst oAi = (ArcInst)geom;
tech = oAi.getProto().getTechnology();
nodeInstPolyList = tech.getShapeOfArc(oAi);
}
if (nodeInstPolyList == null) return false;
int tot = nodeInstPolyList.length;
CheckInst ci = (CheckInst)checkInsts.get(ni);
if (ci == null) return false;
int localIndex = globalIndex * ci.multiplier + ci.localIndex + ci.offset;
// examine the polygons on this node
for(int j=0; j<tot; j++)
{
Poly poly = nodeInstPolyList[j];
Layer polyLayer = poly.getLayer();
if (polyLayer == null) continue;
// see how far around the box it is necessary to search
double maxSize = poly.getMaxSize();
double bound = DRC.getMaxSurround(polyLayer, maxSize);
if (bound < 0) continue;
// determine network for this polygon
int net;
if (geom instanceof NodeInst)
{
net = getDRCNetNumber(netlist, poly.getPort(), (NodeInst)geom, globalIndex);
} else
{
ArcInst oAi = (ArcInst)geom;
Network jNet = netlist.getNetwork(oAi, 0);
Integer [] netNumbers = (Integer [])networkLists.get(jNet);
net = netNumbers[globalIndex].intValue();
}
// determine area to search inside of cell to check this layer
Rectangle2D polyBounds = poly.getBounds2D();
Rectangle2D subBounds = new Rectangle2D.Double(polyBounds.getMinX() - bound,
polyBounds.getMinY()-bound, polyBounds.getWidth()+bound*2, polyBounds.getHeight()+bound*2);
AffineTransform tempTrans = ni.rotateIn();
AffineTransform tTransI = ni.translateIn();
tempTrans.preConcatenate(tTransI);
DBMath.transformRect(subBounds, tempTrans);
AffineTransform subTrans = ni.translateOut(ni.rotateOut());
// see if this polygon has errors in the cell
if (badBoxInArea(poly, polyLayer, tech, net, geom, trans, globalIndex, subBounds, (Cell)np, localIndex,
subCell, globalIndex, subTrans, baseMulti, false)) return true;
}
return false;
}
/*************************** QUICK DRC CACHE OF INSTANCE INTERACTIONS ***************************/
/**
* Method to look for an interaction between instances "ni1" and "ni2". If it is found,
* return TRUE. If not found, add to the list and return FALSE.
*/
private boolean checkInteraction(NodeInst ni1, NodeInst n1Parent, AffineTransform n1UpTrans,
NodeInst ni2, NodeInst n2Parent, NodeInst triggerNi)
{
if (errorTypeSearch == DRC.ERROR_CHECK_EXHAUSTIVE) return false;
// must recheck parameterized instances always
CheckProto cp = getCheckProto((Cell)ni1.getProto());
if (cp.cellParameterized) return false;
cp = getCheckProto((Cell)ni2.getProto());
if (cp.cellParameterized) return false;
// keep the instances in proper numeric order
InstanceInter dii = new InstanceInter();
if (ni1.getNodeIndex() < ni2.getNodeIndex())
{
NodeInst swapni = ni1; ni1 = ni2; ni2 = swapni;
} else if (ni1 == ni2)
{
int node1Orientation = ni1.getAngle();
if (ni1.isMirroredAboutXAxis()) node1Orientation += 3600;
if (ni1.isMirroredAboutYAxis()) node1Orientation += 7200;
int node2Orientation = ni2.getAngle();
if (ni2.isMirroredAboutXAxis()) node2Orientation += 3600;
if (ni2.isMirroredAboutYAxis()) node2Orientation += 7200;
if (node1Orientation < node2Orientation)
{
NodeInst swapNI = ni1; ni1 = ni2; ni2 = swapNI;
System.out.println("Check this case in Quick.checkInteraction");
}
}
// get essential information about their interaction
dii.cell1 = (Cell)ni1.getProto();
dii.rot1 = ni1.getAngle();
dii.mirrorX1 = ni1.isMirroredAboutXAxis();
dii.mirrorY1 = ni1.isMirroredAboutYAxis();
dii.cell2 = (Cell)ni2.getProto();
dii.rot2 = ni2.getAngle();
dii.mirrorX2 = ni2.isMirroredAboutXAxis();
dii.mirrorY2 = ni2.isMirroredAboutYAxis();
// This has to be calculated before the swap
dii.dx = ni2.getAnchorCenterX() - ni1.getAnchorCenterX();
dii.dy = ni2.getAnchorCenterY() - ni1.getAnchorCenterY();
dii.n1Parent = n1Parent;
dii.n2Parent = n2Parent;
dii.triggerNi = triggerNi;
// if found, stop now
if (findInteraction(dii)) return true;
// insert it now
instanceInteractionList.add(dii);
return false;
}
/**
* Method to look for the instance-interaction in "dii" in the global list of instances interactions
* that have already been checked. Returns the entry if it is found, NOINSTINTER if not.
*/
private boolean findInteraction(InstanceInter dii)
{
for(Iterator it = instanceInteractionList.iterator(); it.hasNext(); )
{
InstanceInter thisII = (InstanceInter)it.next();
if (thisII.cell1 == dii.cell1 && thisII.cell2 == dii.cell2 &&
thisII.rot1 == dii.rot1 && thisII.rot2 == dii.rot2 &&
thisII.mirrorX1 == dii.mirrorX1 && thisII.mirrorX2 == dii.mirrorX2 &&
thisII.mirrorY1 == dii.mirrorY1 && thisII.mirrorY2 == dii.mirrorY2 &&
thisII.dx == dii.dx && thisII.dy == dii.dy &&
thisII.n1Parent == dii.n1Parent && thisII.n2Parent == dii.n2Parent)
{
if (dii.triggerNi == thisII.triggerNi)
{
// System.out.println("NEW case");
return true;
}
}
}
return false;
}
/************************* QUICK DRC HIERARCHICAL NETWORK BUILDING *************************/
/**
* Method to recursively examine the hierarchy below cell "cell" and create
* CheckProto and CheckInst objects on every cell instance.
*/
private CheckProto checkEnumerateProtos(Cell cell, Netlist netlist)
{
CheckProto cp = getCheckProto(cell);
if (cp != null) return cp;
cp = new CheckProto();
cp.instanceCount = 0;
cp.timeStamp = 0;
cp.hierInstanceCount = 0;
cp.totalPerCell = 0;
cp.cellChecked = false;
cp.cellParameterized = false;
cp.treeParameterized = false;
cp.netlist = netlist;
for(Iterator vIt = cell.getVariables(); vIt.hasNext(); )
{
Variable var = (Variable)vIt.next();
if (var.isParam())
{
cp.cellParameterized = true;
cp.treeParameterized = true;
break;
}
}
checkProtos.put(cell, cp);
for(Iterator nIt = cell.getNodes(); nIt.hasNext(); )
{
NodeInst ni = (NodeInst)nIt.next();
if (!(ni.getProto() instanceof Cell)) continue;
// ignore documentation icons
if (ni.isIconOfParent()) continue;
Cell subCell = (Cell)ni.getProto();
CheckInst ci = new CheckInst();
checkInsts.put(ni, ci);
CheckProto subCP = checkEnumerateProtos(subCell, netlist.getNetlist(ni));
if (subCP.treeParameterized)
cp.treeParameterized = true;
}
return cp;
}
/**
* Method to return CheckProto of a Cell.
* @param cell Cell to get its CheckProto.
* @return CheckProto of a Cell.
*/
private final CheckProto getCheckProto(Cell cell)
{
return (CheckProto) checkProtos.get(cell);
}
/**
* Method to recursively examine the hierarchy below cell "cell" and fill in the
* CheckInst objects on every cell instance. Uses the CheckProto objects
* to keep track of cell usage.
*/
private void checkEnumerateInstances(Cell cell)
{
if (job != null && job.checkAbort()) return;
// number all of the instances in this cell
checkTimeStamp++;
List subCheckProtos = new ArrayList();
for(Iterator it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = (NodeInst)it.next();
NodeProto np = ni.getProto();
if (!(np instanceof Cell)) continue;
// ignore documentation icons
if (ni.isIconOfParent()) continue;
CheckProto cp = getCheckProto((Cell)np);
if (cp.timeStamp != checkTimeStamp)
{
cp.timeStamp = checkTimeStamp;
cp.instanceCount = 0;
cp.nodesInCell = new ArrayList();
subCheckProtos.add(cp);
}
CheckInst ci = (CheckInst)checkInsts.get(ni);
ci.localIndex = cp.instanceCount++;
cp.nodesInCell.add(ci);
}
// update the counts for this cell
for(Iterator it = subCheckProtos.iterator(); it.hasNext(); )
{
CheckProto cp = (CheckProto)it.next();
cp.hierInstanceCount += cp.instanceCount;
for(Iterator nIt = cp.nodesInCell.iterator(); nIt.hasNext(); )
{
CheckInst ci = (CheckInst)nIt.next();
ci.multiplier = cp.instanceCount;
}
}
// now recurse
for(Iterator it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = (NodeInst)it.next();
NodeProto np = ni.getProto();
if (!(np instanceof Cell)) continue;
// ignore documentation icons
if (ni.isIconOfParent()) continue;
checkEnumerateInstances((Cell)np);
}
}
private void checkEnumerateNetworks(Cell cell, CheckProto cp, int globalIndex, HashMap enumeratedNets)
{
// store all network information in the appropriate place
for(Iterator nIt = cp.netlist.getNetworks(); nIt.hasNext(); )
{
Network net = (Network)nIt.next();
Integer netNumber = (Integer)enumeratedNets.get(net);
Integer [] netNumbers = (Integer [])networkLists.get(net);
netNumbers[globalIndex] = netNumber;
}
for(Iterator it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = (NodeInst)it.next();
NodeProto np = ni.getProto();
if (!(np instanceof Cell)) continue;
// ignore documentation icons
if (ni.isIconOfParent()) continue;
// compute the index of this instance
CheckInst ci = (CheckInst)checkInsts.get(ni);
int localIndex = globalIndex * ci.multiplier + ci.localIndex + ci.offset;
// propagate down the hierarchy
Cell subCell = (Cell)np;
CheckProto subCP = getCheckProto(subCell);
HashMap subEnumeratedNets = new HashMap();
for(Iterator pIt = ni.getPortInsts(); pIt.hasNext(); )
{
PortInst pi = (PortInst)pIt.next();
Export subPP = (Export)pi.getPortProto();
Network net = cp.netlist.getNetwork(ni, subPP, 0);
if (net == null) continue;
Integer netNumber = (Integer)enumeratedNets.get(net);
Network subNet = subCP.netlist.getNetwork(subPP, 0);
subEnumeratedNets.put(subNet, netNumber);
}
for(Iterator nIt = subCP.netlist.getNetworks(); nIt.hasNext(); )
{
Network net = (Network)nIt.next();
if (subEnumeratedNets.get(net) == null)
subEnumeratedNets.put(net, new Integer(checkNetNumber++));
}
checkEnumerateNetworks(subCell, subCP, localIndex, subEnumeratedNets);
}
}
/*********************************** QUICK DRC SUPPORT ***********************************/
/**
* Method to determine if neighbor would help to cover the minimum conditions
* @return true if error was found (not warning)
*/
private boolean checkExtensionWithNeighbors(Cell cell, Geometric geom, Poly poly, Layer layer, Rectangle2D bounds,
DRCTemplate minWidthRule, int dir, boolean onlyOne)
{
double actual = 0;
Point2D left1, left2, left3, right1, right2, right3;
//if (bounds.getWidth() < minWidthRule.value)
String msg = "";
// potential problem along X
if (dir == 0)
{
actual = bounds.getWidth();
msg = "(X axis)";
double leftW = bounds.getMinX() - TINYDELTA;
left1 = new Point2D.Double(leftW, bounds.getMinY());
left2 = new Point2D.Double(leftW, bounds.getMaxY());
left3 = new Point2D.Double(leftW, bounds.getCenterY());
double rightW = bounds.getMaxX() + TINYDELTA;
right1 = new Point2D.Double(rightW, bounds.getMinY());
right2 = new Point2D.Double(rightW, bounds.getMaxY());
right3 = new Point2D.Double(rightW, bounds.getCenterY());
} else
{
actual = bounds.getHeight();
msg = "(Y axis)";
double leftH = bounds.getMinY() - TINYDELTA;
left1 = new Point2D.Double(bounds.getMinX(), leftH);
left2 = new Point2D.Double(bounds.getMaxX(), leftH);
left3 = new Point2D.Double(bounds.getCenterX(), leftH);
double rightH = bounds.getMaxY() + TINYDELTA;
right1 = new Point2D.Double(bounds.getMinX(), rightH);
right2 = new Point2D.Double(bounds.getMaxX(), rightH);
right3 = new Point2D.Double(bounds.getCenterX(), rightH);
}
// see if there is more of this layer adjoining on either side
boolean [] pointsFound = new boolean[3];
pointsFound[0] = pointsFound[1] = pointsFound[2] = false;
Rectangle2D newBounds = new Rectangle2D.Double(bounds.getMinX()-TINYDELTA, bounds.getMinY()-TINYDELTA,
bounds.getWidth()+TINYDELTA*2, bounds.getHeight()+TINYDELTA*2);
boolean zeroWide = (bounds.getWidth() == 0 || bounds.getHeight() == 0);
boolean overlapLayer = lookForLayer(poly, cell, layer, DBMath.MATID, newBounds,
left1, left2, left3, pointsFound); //) return false;
if (overlapLayer && !zeroWide) return false;
// Try the other corner
pointsFound[0] = pointsFound[1] = pointsFound[2] = false;
overlapLayer = lookForLayer(poly, cell, layer, DBMath.MATID, newBounds,
right1, right2, right3, pointsFound); //) return false;
if (overlapLayer && !zeroWide) return false;
int errorType = MINWIDTHERROR;
String extraMsg = msg;
String rule = minWidthRule.ruleName;
if (zeroWide)
{
if (overlapLayer) extraMsg = " but covered by other layer";
errorType = ZEROLENGTHARCWARN;
rule = null;
}
reportError(errorType, extraMsg, cell, minWidthRule.value1, actual, rule,
(onlyOne) ? null : poly, geom, layer, null, null, null);
return !overlapLayer;
}
/**
* Method to ensure that polygon "poly" on layer "layer" from object "geom" in
* technology "tech" meets minimum width rules. If it is too narrow, other layers
* in the vicinity are checked to be sure it is indeed an error. Returns true
* if an error is found.
*/
private boolean checkMinWidth(Geometric geom, Layer layer, Poly poly, boolean onlyOne)
{
Cell cell = geom.getParent();
DRCTemplate minWidthRule = DRC.getMinValue(layer, DRCTemplate.MINWID, techMode);
if (minWidthRule == null) return false;
// simpler analysis if manhattan
Rectangle2D bounds = poly.getBox();
if (bounds != null)
{
boolean tooSmallWidth = DBMath.isGreaterThan(minWidthRule.value1, bounds.getWidth());
boolean tooSmallHeight = DBMath.isGreaterThan(minWidthRule.value1, bounds.getHeight());
if (!tooSmallWidth && !tooSmallHeight) return false;
boolean foundError = false;
if (tooSmallWidth && checkExtensionWithNeighbors(cell, geom, poly, layer, bounds, minWidthRule, 0, onlyOne))
foundError = true;
if (tooSmallHeight && checkExtensionWithNeighbors(cell, geom, poly, layer, bounds, minWidthRule, 1, onlyOne))
foundError = true;
return foundError;
}
// nonmanhattan polygon: stop now if it has no size
Poly.Type style = poly.getStyle();
if (style != Poly.Type.FILLED && style != Poly.Type.CLOSED && style != Poly.Type.CROSSED &&
style != Poly.Type.OPENED && style != Poly.Type.OPENEDT1 && style != Poly.Type.OPENEDT2 &&
style != Poly.Type.OPENEDT3 && style != Poly.Type.VECTORS) return false;
// simple check of nonmanhattan polygon for minimum width
bounds = poly.getBounds2D();
double actual = Math.min(bounds.getWidth(), bounds.getHeight());
if (actual < minWidthRule.value1)
{
reportError(MINWIDTHERROR, null, cell, minWidthRule.value1, actual, minWidthRule.ruleName,
(onlyOne) ? null : poly, geom, layer, null, null, null);
return true;
}
// check distance of each line's midpoint to perpendicular opposite point
Point2D [] points = poly.getPoints();
int count = points.length;
for(int i=0; i<count; i++)
{
Point2D from;
if (i == 0) from = points[count-1]; else
from = points[i-1];
Point2D to = points[i];
if (from.equals(to)) continue;
double ang = DBMath.figureAngleRadians(from, to);
Point2D center = new Point2D.Double((from.getX() + to.getX()) / 2, (from.getY() + to.getY()) / 2);
double perpang = ang + Math.PI / 2;
for(int j=0; j<count; j++)
{
if (j == i) continue;
Point2D oFrom;
if (j == 0) oFrom = points[count-1]; else
oFrom = points[j-1];
Point2D oTo = points[j];
if (oFrom.equals(oTo)) continue;
double oAng = DBMath.figureAngleRadians(oFrom, oTo);
double rAng = ang; while (rAng > Math.PI) rAng -= Math.PI;
double rOAng = oAng; while (rOAng > Math.PI) rOAng -= Math.PI;
if (DBMath.doublesEqual(oAng, rOAng))
{
// lines are parallel: see if they are colinear
if (DBMath.isOnLine(from, to, oFrom)) continue;
if (DBMath.isOnLine(from, to, oTo)) continue;
if (DBMath.isOnLine(oFrom, oTo, from)) continue;
if (DBMath.isOnLine(oFrom, oTo, to)) continue;
}
Point2D inter = DBMath.intersectRadians(center, perpang, oFrom, oAng);
if (inter == null) continue;
if (inter.getX() < Math.min(oFrom.getX(), oTo.getX()) || inter.getX() > Math.max(oFrom.getX(), oTo.getX())) continue;
if (inter.getY() < Math.min(oFrom.getY(), oTo.getY()) || inter.getY() > Math.max(oFrom.getY(), oTo.getY())) continue;
double fdx = center.getX() - inter.getX();
double fdy = center.getY() - inter.getY();
actual = DBMath.round(Math.sqrt(fdx*fdx + fdy*fdy));
// becuase this is done in integer, accuracy may suffer
// actual += 2;
if (actual < minWidthRule.value1)
{
// look between the points to see if it is minimum width or notch
if (poly.isInside(new Point2D.Double((center.getX()+inter.getX())/2, (center.getY()+inter.getY())/2)))
{
reportError(MINWIDTHERROR, null, cell, minWidthRule.value1,
actual, minWidthRule.ruleName, (onlyOne) ? null : poly, geom, layer, null, null, null);
} else
{
reportError(NOTCHERROR, null, cell, minWidthRule.value1,
actual, minWidthRule.ruleName, (onlyOne) ? null : poly, geom, layer, poly, geom, layer);
}
return true;
}
}
}
return false;
}
private int checkMinAreaLayer(GeometryHandler merge, Cell cell, Layer layer)
{
int errorFound = 0;
DRCTemplate minAreaRule = (DRCTemplate)minAreaLayerMap.get(layer);
DRCTemplate encloseAreaRule = (DRCTemplate)enclosedAreaLayerMap.get(layer);
// Layer doesn't have min area
if (minAreaRule == null && encloseAreaRule == null) return 0;
Collection set = merge.getObjects(layer, false, true);
if (set == null) return 0; // layer is not present in this cell
for(Iterator pIt = set.iterator(); pIt.hasNext(); )
{
Object obj = pIt.next();
if (obj == null) throw new Error("wrong condition in Quick.checkMinArea()");
List list = null;
if (mergeMode == GeometryHandler.ALGO_QTREE)
list = ((PolyQTree.PolyNode)obj).getSortedLoops();
else
list = ((PolyBase)obj).getSortedLoops();
// Order depends on area comparison done. First element is the smallest.
// and depending on # polygons it could be minArea or encloseArea
DRCTemplate evenRule = (list.size()%2==0) ? encloseAreaRule : minAreaRule;
DRCTemplate oddRule = (evenRule == minAreaRule) ? encloseAreaRule : minAreaRule;
// Looping over simple polygons. Possible problems with disconnected elements
// polyArray.length = Maximum number of distintic loops
for (int i = 0; i < list.size(); i++)
{
Object listObj = list.get(i);
//PolyQTree.PolyNode simplePn = (PolyQTree.PolyNode)list.get(i);
double area = 0;
if (mergeMode == GeometryHandler.ALGO_QTREE)
area = ((PolyQTree.PolyNode)listObj).getArea();
else
area = ((PolyBase)listObj).getArea();
DRCTemplate minRule = (i%2 == 0) ? evenRule : oddRule;
if (minRule == null) continue;
// isGreaterThan doesn't consider equals condition therefore negate condition is used
if (!DBMath.isGreaterThan(minRule.value1, area)) continue;
//if (!layer.getName().equals("Metal-1")) continue;
errorFound++;
int errorType = (minRule == minAreaRule) ? MINAREAERROR : ENCLOSEDAREAERROR;
PolyBase simplePn = ((mergeMode == GeometryHandler.ALGO_QTREE))
? new PolyBase(((PolyQTree.PolyNode)listObj).getPoints(true))
: (PolyBase)listObj;
reportError(errorType, null, cell, minRule.value1, area, minRule.ruleName,
simplePn, null /*ni*/, layer, null, null, null);
}
}
return errorFound;
}
/**
* Method to ensure that polygon "poly" on layer "layer" from object "geom" in
* technology "tech" meets minimum area rules. Returns true
* if an error is found.
*/
private int checkMinAreaNew(Cell cell)
{
CheckProto cp = getCheckProto(cell);
int errorFound = 0;
// Nothing to check
if (minAreaLayerMap.isEmpty() && enclosedAreaLayerMap.isEmpty())
return 0;
// Select/well regions
HashMap selectMergeMap = new HashMap();
CheckAreaEnumerator quickArea = new CheckAreaEnumerator(selectMergeMap, mergeMode);
HierarchyEnumerator.enumerateCell(cell, VarContext.globalContext, cp.netlist, quickArea);
GeometryHandler geom = (GeometryHandler)quickArea.mainMergeMap.get(cell);
// Get merged areas. Only valid for layers that have connections (metals/polys). No valid for NP/PP.A.1 rule
for(Iterator layerIt = cell.getTechnology().getLayers(); layerIt.hasNext(); )
{
Layer layer = (Layer)layerIt.next();
if (minAreaLayerMap.get(layer) == null && enclosedAreaLayerMap.get(layer) == null)
continue;
// Job aborted
if (job != null && job.checkAbort()) return 0;
errorFound += checkMinAreaLayer(geom, cell, layer);
}
// Checking nodes not exported down in the hierarchy. Probably good enought not to collect networks first
// quickArea = new CheckAreaEnumerator(notExportedNodes, checkedNodes, job.mergeMode);
// HierarchyEnumerator.enumerateCell(cell, VarContext.globalContext, cp.netlist, quickArea);
// Non exported nodes
// for(Iterator it = quickArea.mainMerge.getKeyIterator(); it.hasNext(); )
// {
// Layer layer = (Layer)it.next();
// boolean localError = checkMinAreaLayer(quickArea.mainMerge, cell, layer);
// if (!errorFound) errorFound = localError;
// }
// Special cases for select areas. You can't evaluate based on networks
GeometryHandler selectMerge = (GeometryHandler)selectMergeMap.get(cell);
for(Iterator it = selectMerge.getKeyIterator(); it.hasNext(); )
{
Layer layer = (Layer)it.next();
errorFound += checkMinAreaLayer(selectMerge, cell, layer);
}
return errorFound;
}
/**
* Method to ensure that polygon "poly" on layer "layer" from object "geom" in
* technology "tech" meets minimum area rules. Returns true
* if an error is found.
*/
private int checkMinArea(Cell cell)
{
CheckProto cp = getCheckProto(cell);
int errorFound = 0;
// Nothing to check
if (minAreaLayerMap.isEmpty() && enclosedAreaLayerMap.isEmpty())
return 0;
// Select/well regions
GeometryHandler selectMerge = GeometryHandler.createGeometryHandler(mergeMode, 0, cell.getBounds()); //new PolyQTree(cell.getBounds());
HashMap notExportedNodes = new HashMap();
HashMap checkedNodes = new HashMap();
// Get merged areas. Only valid for layers that have connections (metals/polys). No valid for NP/PP.A.1 rule
for(Iterator netIt = cp.netlist.getNetworks(); netIt.hasNext(); )
{
Network net = (Network)netIt.next();
QuickAreaEnumerator quickArea = new QuickAreaEnumerator(net, selectMerge, notExportedNodes, checkedNodes,
mergeMode);
HierarchyEnumerator.enumerateCell(cell, VarContext.globalContext, cp.netlist, quickArea);
quickArea.mainMerge.postProcess(true);
// Job aborted
if (job != null && job.checkAbort()) return 0;
for(Iterator it = quickArea.mainMerge.getKeyIterator(); it.hasNext(); )
{
Layer layer = (Layer)it.next();
errorFound += checkMinAreaLayer(quickArea.mainMerge, cell, layer);
}
}
// Checking nodes not exported down in the hierarchy. Probably good enought not to collect networks first
QuickAreaEnumerator quickArea = new QuickAreaEnumerator(notExportedNodes, checkedNodes, mergeMode);
HierarchyEnumerator.enumerateCell(cell, VarContext.globalContext, cp.netlist, quickArea);
// Non exported nodes
// for(Iterator it = quickArea.mainMerge.getKeyIterator(); it.hasNext(); )
// {
// Layer layer = (Layer)it.next();
// boolean localError = checkMinAreaLayer(quickArea.mainMerge, cell, layer);
// if (!errorFound) errorFound = localError;
// }
selectMerge.postProcess(true);
// Special cases for select areas. You can't evaluate based on networks
for(Iterator it = selectMerge.getKeyIterator(); it.hasNext(); )
{
Layer layer = (Layer)it.next();
errorFound += checkMinAreaLayer(selectMerge, cell, layer);
}
return errorFound;
}
/**
* Method to find two points between polygons "poly1" and "poly2" that can be used to test
* for notches. The points are returned in (xf1,yf1) and (xf2,yf2). Returns zero if no
* points exist in the gap between the polygons (becuase they don't have common facing edges).
* Returns 1 if only one of the reported points needs to be filled (because the polygons meet
* at a point). Returns 2 if both reported points need to be filled.
*/
private int findInterveningPoints(Poly poly1, Poly poly2, Point2D pt1, Point2D pt2, boolean newFix)
{
Rectangle2D isBox1 = poly1.getBox();
Rectangle2D isBox2 = poly2.getBox();
// Better to treat serpentine cases with bouding box
if (newFix)
{
if (isBox1 == null)
isBox1 = poly1.getBounds2D();
if (isBox2 == null)
isBox2 = poly2.getBounds2D();
}
if (isBox1 != null && isBox2 != null)
{
// handle vertical gap between polygons
if (isBox1.getMinX() > isBox2.getMaxX() || isBox2.getMinX() > isBox1.getMaxX())
{
// see if the polygons are horizontally aligned
if (isBox1.getMinY() <= isBox2.getMaxY() && isBox2.getMinY() <= isBox1.getMaxY())
{
double yf1 = Math.max(isBox1.getMinY(), isBox2.getMinY());
double yf2 = Math.min(isBox1.getMaxY(), isBox2.getMaxY());
if (isBox1.getMinX() > isBox2.getMaxX())
{
double x = (isBox1.getMinX() + isBox2.getMaxX()) / 2;
pt1.setLocation(x, yf1);
pt2.setLocation(x, yf2);
} else
{
double x = (isBox2.getMinX() + isBox1.getMaxX()) / 2;
pt1.setLocation(x, yf1);
pt2.setLocation(x, yf2);
}
return 2;
}
} else if (isBox1.getMinY() > isBox2.getMaxY() || isBox2.getMinY() > isBox1.getMaxY())
{
// see if the polygons are horizontally aligned
if (isBox1.getMinX() <= isBox2.getMaxX() && isBox2.getMinX() <= isBox1.getMaxX())
{
double xf1 = Math.max(isBox1.getMinX(), isBox2.getMinX());
double xf2 = Math.min(isBox1.getMaxX(), isBox2.getMaxX());
if (isBox1.getMinY() > isBox2.getMaxY())
{
double y = (isBox1.getMinY() + isBox2.getMaxY()) / 2;
pt1.setLocation(xf1, y);
pt2.setLocation(xf2, y);
} else
{
double y = (isBox2.getMinY() + isBox1.getMaxY()) / 2;
pt1.setLocation(xf1, y);
pt2.setLocation(xf2, y);
}
return 2;
}
} else if ((isBox1.getMinX() == isBox2.getMaxX() || isBox2.getMinX() == isBox1.getMaxX()) || (isBox1.getMinY() == isBox2.getMaxY() || isBox2.getMinY() == isBox2.getMaxY()))
{
// handle touching at a point
double xc = isBox2.getMinX();
if (isBox1.getMinX() == isBox2.getMaxX()) xc = isBox1.getMinX();
double yc = isBox2.getMinY();
if (isBox1.getMinY() == isBox2.getMaxY()) yc = isBox1.getMinY();
double xPlus = xc + TINYDELTA;
double yPlus = yc + TINYDELTA;
pt1.setLocation(xPlus, yPlus);
pt2.setLocation(xPlus, yPlus);
if ((xPlus < isBox1.getMinX() || xPlus > isBox1.getMaxX() || yPlus < isBox1.getMinY() || yPlus > isBox1.getMaxY()) &&
(xPlus < isBox2.getMinX() || xPlus > isBox2.getMaxX() || yPlus < isBox2.getMinY() || yPlus > isBox2.getMaxY())) return 1;
pt1.setLocation(xc + TINYDELTA, yc - TINYDELTA);
pt2.setLocation(xc - TINYDELTA, yc + TINYDELTA);
return 1;
}
// handle manhattan objects that are on a diagonal
if (isBox1.getMinX() > isBox2.getMaxX())
{
if (isBox1.getMinY() > isBox2.getMaxY())
{
pt1.setLocation(isBox1.getMinX(), isBox1.getMinY());
pt2.setLocation(isBox2.getMaxX(), isBox2.getMaxY());
return 1;
}
if (isBox2.getMinY() > isBox1.getMaxY())
{
pt1.setLocation(isBox1.getMinX(), isBox1.getMaxY());
pt2.setLocation(isBox2.getMaxX(), isBox2.getMinY());
return 1;
}
}
if (isBox2.getMinX() > isBox1.getMaxX())
{
if (isBox1.getMinY() > isBox2.getMaxY())
{
pt1.setLocation(isBox1.getMaxX(), isBox1.getMinY());
pt2.setLocation(isBox2.getMinX(), isBox2.getMaxY());
return 1;
}
if (isBox2.getMinY() > isBox1.getMaxY())
{
pt1.setLocation(isBox1.getMaxX(), isBox1.getMaxY());
pt2.setLocation(isBox2.getMinX(), isBox2.getMinY());
return 1;
}
}
}
// boxes don't line up or this is a nonmanhattan situation
isBox1 = poly1.getBounds2D();
isBox2 = poly2.getBounds2D();
pt1.setLocation((isBox1.getMinX() + isBox1.getMaxX()) / 2, (isBox2.getMinY() + isBox2.getMaxY()) / 2);
pt2.setLocation((isBox2.getMinX() + isBox2.getMaxX()) / 2, (isBox1.getMinY() + isBox1.getMaxY()) / 2);
return 1;
}
/**
* Method to explore the points (xf1,yf1) and (xf2,yf2) to see if there is
* geometry on layer "layer" (in or below cell "cell"). Returns true if there is.
* If "needBoth" is true, both points must have geometry, otherwise only 1 needs it.
*/
private boolean lookForPoints(Point2D pt1, Point2D pt2, Layer layer, Cell cell, boolean needBoth)
{
Point2D pt3 = new Point2D.Double((pt1.getX()+pt2.getX()) / 2, (pt1.getY()+pt2.getY()) / 2);
// compute bounds for searching inside cells
double flx = Math.min(pt1.getX(), pt2.getX()); double fhx = Math.max(pt1.getX(), pt2.getX());
double fly = Math.min(pt1.getY(), pt2.getY()); double fhy = Math.max(pt1.getY(), pt2.getY());
Rectangle2D bounds = new Rectangle2D.Double(flx, fly, fhx-flx, fhy-fly);
// search the cell for geometry that fills the notch
boolean [] pointsFound = new boolean[3];
pointsFound[0] = pointsFound[1] = pointsFound[2] = false;
boolean allFound = lookForLayer(null, cell, layer, DBMath.MATID, bounds,
pt1, pt2, pt3, pointsFound);
if (needBoth)
{
if (allFound) return true;
} else
{
if (pointsFound[0] || pointsFound[1]) return true;
}
return false;
}
/**
* Method to explore the points (xf1,yf1) and (xf2,yf2) to see if there is
* geometry on layer "layer" (in or below cell "cell"). Returns true if there is.
* If "needBoth" is true, both points must have geometry, otherwise only 1 needs it.
*/
private boolean lookForCrossPolygons(Geometric geo1, Poly poly1, Geometric geo2, Poly poly2, Layer layer,
Cell cell, boolean overlap)
{
Point2D pt1 = new Point2D.Double();
Point2D pt2 = new Point2D.Double();
findInterveningPoints(poly1, poly2, pt1, pt2, true);
// compute bounds for searching inside cells
double flx = Math.min(pt1.getX(), pt2.getX()); double fhx = Math.max(pt1.getX(), pt2.getX());
double fly = Math.min(pt1.getY(), pt2.getY()); double fhy = Math.max(pt1.getY(), pt2.getY());
Rectangle2D bounds = new Rectangle2D.Double(DBMath.round(flx-TINYDELTA), DBMath.round(fly-TINYDELTA),
DBMath.round(fhx-flx+2*TINYDELTA), DBMath.round(fhy-fly+2*TINYDELTA));
// Adding delta otherwise it won't consider points along edges.
// Mind bounding boxes could have zero width or height
// search the cell for geometry that fills the notch
boolean [] pointsFound = new boolean[2];
pointsFound[0] = pointsFound[1] = false;
boolean allFound = lookForLayerNew(geo1, poly1, geo2, poly2, cell, layer, DBMath.MATID, bounds,
pt1, pt2, null, pointsFound, overlap);
return allFound;
}
/**
* Method to examine cell "cell" in the area (lx<=X<=hx, ly<=Y<=hy) for objects
* on layer "layer". Apply transformation "moreTrans" to the objects. If polygons are
* found at (xf1,yf1) or (xf2,yf2) or (xf3,yf3) then sets "p1found/p2found/p3found" to 1.
* If all locations are found, returns true.
*/
private boolean lookForLayer(Poly thisPoly, Cell cell, Layer layer, AffineTransform moreTrans,
Rectangle2D bounds, Point2D pt1, Point2D pt2, Point2D pt3, boolean [] pointsFound)
{
int j;
boolean skip = false;
Rectangle2D newBounds = new Rectangle2D.Double(); // sept 30
for(Iterator it = cell.searchIterator(bounds); it.hasNext(); )
{
Geometric g = (Geometric)it.next();
if (g instanceof NodeInst)
{
NodeInst ni = (NodeInst)g;
if (NodeInst.isSpecialNode(ni)) continue; // Nov 16, no need for checking pins or other special nodes;
if (ni.getProto() instanceof Cell)
{
// compute bounding area inside of sub-cell
AffineTransform rotI = ni.rotateIn();
AffineTransform transI = ni.translateIn();
rotI.preConcatenate(transI);
newBounds.setRect(bounds);
DBMath.transformRect(newBounds, rotI);
// compute new matrix for sub-cell examination
AffineTransform trans = ni.translateOut(ni.rotateOut());
trans.preConcatenate(moreTrans);
if (lookForLayer(thisPoly, (Cell)ni.getProto(), layer, trans, newBounds,
pt1, pt2, pt3, pointsFound))
return true;
continue;
}
AffineTransform bound = ni.rotateOut();
bound.preConcatenate(moreTrans);
Technology tech = ni.getProto().getTechnology();
Poly [] layerLookPolyList = tech.getShapeOfNode(ni, null, null, false, ignoreCenterCuts, null);
int tot = layerLookPolyList.length;
for(int i=0; i<tot; i++)
{
Poly poly = layerLookPolyList[i];
if (!tech.sameLayer(poly.getLayer(), layer)) continue;
if (thisPoly != null && poly.polySame(thisPoly)) continue;
poly.transform(bound);
if (poly.isInside(pt1)) pointsFound[0] = true;
if (poly.isInside(pt2)) pointsFound[1] = true;
if (pt3 != null && poly.isInside(pt3)) pointsFound[2] = true;
for (j = 0; j < pointsFound.length && pointsFound[j]; j++);
boolean newR = (j == pointsFound.length);
if (newR)
{
return true;
}
// No need of checking rest of the layers?
//break;
}
} else
{
ArcInst ai = (ArcInst)g;
Technology tech = ai.getProto().getTechnology();
Poly [] layerLookPolyList = tech.getShapeOfArc(ai);
int tot = layerLookPolyList.length;
for(int i=0; i<tot; i++)
{
Poly poly = layerLookPolyList[i];
if (!tech.sameLayer(poly.getLayer(), layer)) continue;
poly.transform(moreTrans);
if (poly.isInside(pt1)) pointsFound[0] = true;
if (poly.isInside(pt2)) pointsFound[1] = true;
if (pt3 != null && poly.isInside(pt3)) pointsFound[2] = true;
for (j = 0; j < pointsFound.length && pointsFound[j]; j++);
boolean newR = (j == pointsFound.length);
if (newR)
return true;
// No need of checking rest of the layers
//break;
}
}
for (j = 0; j < pointsFound.length && pointsFound[j]; j++);
if (j == pointsFound.length)
{
System.out.println("When?");
return true;
}
}
if (skip) System.out.println("This case in lookForLayerNew antes");
return false;
}
/**
* Method to examine cell "cell" in the area (lx<=X<=hx, ly<=Y<=hy) for objects
* on layer "layer". Apply transformation "moreTrans" to the objects. If polygons are
* found at (xf1,yf1) or (xf2,yf2) or (xf3,yf3) then sets "p1found/p2found/p3found" to 1.
* If all locations are found, returns true.
*/
private boolean lookForLayerNew(Geometric geo1, Poly poly1, Geometric geo2, Poly poly2, Cell cell,
Layer layer, AffineTransform moreTrans, Rectangle2D bounds,
Point2D pt1, Point2D pt2, Point2D pt3, boolean[] pointsFound,
boolean overlap)
{
int j;
Rectangle2D newBounds = new Rectangle2D.Double(); // Sept 30
for(Iterator it = cell.searchIterator(bounds); it.hasNext(); )
{
Geometric g = (Geometric)it.next();
// Skipping the same geometry only when looking for notches in min distance
// if (ignoreSameGeometry && (g == geo1 || g == geo2)) //not valid condition
// continue;
// I can't skip geometries to exclude from the search
if (g instanceof NodeInst)
{
NodeInst ni = (NodeInst)g;
if (NodeInst.isSpecialNode(ni)) continue; // Nov 16, no need for checking pins or other special nodes;
if (ni.getProto() instanceof Cell)
{
// compute bounding area inside of sub-cell
AffineTransform rotI = ni.rotateIn();
AffineTransform transI = ni.translateIn();
rotI.preConcatenate(transI);
newBounds.setRect(bounds);
DBMath.transformRect(newBounds, rotI);
// compute new matrix for sub-cell examination
AffineTransform trans = ni.translateOut(ni.rotateOut());
trans.preConcatenate(moreTrans);
if (lookForLayerNew(geo1, poly1, geo2, poly2, (Cell)ni.getProto(), layer, trans, newBounds,
pt1, pt2, pt3, pointsFound, overlap))
return true;
continue;
}
AffineTransform bound = ni.rotateOut();
bound.preConcatenate(moreTrans);
Technology tech = ni.getProto().getTechnology();
// I have to ask for electrical layers otherwise it will retrieve one polygon for polysilicon
// and poly.polySame(poly1) will never be true.
Poly [] layerLookPolyList = tech.getShapeOfNode(ni, null, null, false, ignoreCenterCuts, null);
int tot = layerLookPolyList.length;
for(int i=0; i<tot; i++)
{
Poly poly = layerLookPolyList[i];
if (!tech.sameLayer(poly.getLayer(), layer)) continue;
// Should be the transform before?
poly.transform(bound);
if (poly1 != null && !overlap && poly.polySame(poly1))
continue;
if (poly2 != null && !overlap && poly.polySame(poly2))
continue;
if (poly.isInside(pt1)) pointsFound[0] = true; // @TODO Should still evaluate isInside if pointsFound[i] is already valid?
if (poly.isInside(pt2)) pointsFound[1] = true;
if (pt3 != null && poly.isInside(pt3)) pointsFound[2] = true;
for (j = 0; j < pointsFound.length && pointsFound[j]; j++);
if (j == pointsFound.length) return true;
// No need of checking rest of the layers
break;
}
} else
{
ArcInst ai = (ArcInst)g;
Technology tech = ai.getProto().getTechnology();
Poly [] layerLookPolyList = tech.getShapeOfArc(ai);
int tot = layerLookPolyList.length;
for(int i=0; i<tot; i++)
{
Poly poly = layerLookPolyList[i];
if (!tech.sameLayer(poly.getLayer(), layer)) continue;
poly.transform(moreTrans); // @TODO Should still evaluate isInside if pointsFound[i] is already valid?
if (poly.isInside(pt1)) pointsFound[0] = true;
if (poly.isInside(pt2)) pointsFound[1] = true;
if (pt3 != null && poly.isInside(pt3)) pointsFound[2] = true;
for (j = 0; j < pointsFound.length && pointsFound[j]; j++);
if (j == pointsFound.length) return true;
// No need of checking rest of the layers
break;
}
}
for (j = 0; j < pointsFound.length && pointsFound[j]; j++);
if (j == pointsFound.length)
{
System.out.println("When?");
return true;
}
}
return false;
}
// checkCutSizes
/****************************** Cut Rule Functions ***************************/
private boolean checkCutSizes(NodeProto np, Geometric geom, Layer layer, Poly poly,
Geometric nGeom, Layer nLayer, Poly nPoly, Cell topCell)
{
// None of them is cut
if (!(np instanceof PrimitiveNode) || layer != nLayer ||
!layer.getFunction().isContact() || !nLayer.getFunction().isContact())
return false;
PrimitiveNode nty = (PrimitiveNode)np;
double[] specValues = nty.getSpecialValues();
// 0 and 1 hold CUTSIZE
if (specValues == null) return false; // no values
Rectangle2D box1 = poly.getBounds2D();
Rectangle2D box2 = nPoly.getBounds2D();
double pdx = Math.max(box2.getMinX()-box1.getMaxX(), box1.getMinX()-box2.getMaxX());
double pdy = Math.max(box2.getMinY()-box1.getMaxY(), box1.getMinY()-box2.getMaxY());
double pd = Math.max(pdx, pdy);
if (pdx == 0 && pdy == 0) pd = 0; // touching
// They have to overlap
if (pd > 0) return false;
boolean foundError = false;
double minX = Math.min(box1.getMinX(), box2.getMinX());
double minY = Math.min(box1.getMinY(), box2.getMinY());
double maxX = Math.max(box1.getMaxX(), box2.getMaxX());
double maxY = Math.max(box1.getMaxY(), box2.getMaxY());
Rectangle2D rect = new Rectangle2D.Double(minX, minY, maxX-minX, maxY-minY);
DRCTemplate rule = DRC.getRules(nty.getTechnology()).getCutRule(nty.getPrimNodeIndexInTech(), DRCTemplate.CUTSIZE, techMode);
String ruleName = (rule != null) ? rule.ruleName : "for contacts";
if (DBMath.isGreaterThan(rect.getWidth(), specValues[0]))
{
reportError(CUTERROR, "along X", topCell, specValues[0], rect.getWidth(),
ruleName, new Poly(rect), geom, layer, null, nGeom, nLayer);
foundError = true;
}
if (DBMath.isGreaterThan(rect.getHeight(), specValues[1]))
{
reportError(CUTERROR, "along Y", topCell, specValues[1], rect.getHeight(),
ruleName, new Poly(rect), geom, layer, null, geom, layer);
foundError = true;
}
return foundError;
}
/****************************** Extension Rule Functions ***************************/
private boolean checkExtensionGateRule(Geometric geom, Layer layer, Poly poly, Layer nLayer,
Poly nPoly, Netlist netlist)
{
return false;
// if(DRC.isIgnoreExtensionRuleChecking()) return false;
//
// DRCTemplate extensionRule = DRC.getExtensionRule(layer, nLayer, techMode, true);
// // Checking extension, it could be slow
// if (extensionRule == null) return false;
//
// List list = extensionRule.getNodesInRule();
// // Layers order is revelant, the first element is the one to check for the extension in the second one
// if (list != null && list.size() == 2)
// {
// // Not the correct order
// if (list.get(0) != layer || list.get(1) != nLayer) return false;
// }
//
// Area firstArea = new Area(poly);
// Area nPolyArea = new Area(nPoly);
// Area inter = (Area)nPolyArea.clone();
// inter.intersect(firstArea);
// nPolyArea.subtract(inter); // get original nPoly without the intersection
// boolean found = true; // areas that don't insert are not subject to this test.
// if (!nPolyArea.isEmpty())
// {
// // Searching from the corresponding net on geom
// Poly portPoly = null;
// Poly[] primPolyList = getShapeOfGeometric(geom, nLayer);
// for (int i = 0; i < primPolyList.length; i++)
// {
// // Look for Poly that overlaps with original nPoly to get the port
// if (nPoly.intersects(primPolyList[i]))
// {
// portPoly = primPolyList[i];
// break;
// }
// }
// assert portPoly != null;
// Network net = getDRCNetNumber(netlist, geom, portPoly);
// found = searchTransistor(net, geom);
// }
//
// if (!found)
// reportError(FORBIDDEN, " does not comply with rule '" + extensionRule.ruleName + "'.", geom.getParent(), -1, -1, null, null, geom, null, null, null, null);
// return false;
}
/**
* Method to retrieve Poly objects from Geometric object (NodeInst, ArcInst)
* @param geom
* @param layer
* @return
*/
private Poly[] getShapeOfGeometric(Geometric geom, Layer layer)
{
Poly [] primPolyList = null;
List drcLayers = new ArrayList(1);
drcLayers.add(layer.getFunction());
if (geom instanceof NodeInst)
{
NodeInst ni = (NodeInst)geom;
NodeProto np = ni.getProto();
Technology tech = np.getTechnology();
primPolyList = tech.getShapeOfNode(ni, null, null, true, ignoreCenterCuts, drcLayers);
}
else if (geom instanceof ArcInst)
{
ArcInst ai = (ArcInst)geom;
primPolyList = ai.getProto().getTechnology().getShapeOfArc(ai, null, null, drcLayers);
}
return primPolyList;
}
/**
* Method to search for a transistor connected to this network that is not geom. This is to implement
* special rule in 90nm technology. MOVE TO TECHNOLOGY class!! to be cleaner
* @param network
* @param geom
* @return
*/
private boolean searchTransistor(Network network, Geometric geom)
{
// checking if any port in that network belongs to a transistor
// No need of checking arcs?
for (Iterator it = network.getPorts(); it.hasNext();)
{
PortInst pi = (PortInst)it.next();
NodeInst ni = pi.getNodeInst();
if (ni != geom && ni.getProto() instanceof PrimitiveNode)
{
PrimitiveNode pn = (PrimitiveNode)ni.getProto();
if (pn.getFunction().isTransistor())
return true; // found a transistor!
}
}
return false;
}
/**
* Method to check extension rules in general
*/
private boolean checkExtensionRule(Geometric geom, Layer layer, Poly poly, Cell cell)
{
return false;
// if(DRC.isIgnoreExtensionRuleChecking()) return false;
//
// Rectangle2D polyBnd = poly.getBounds2D();
// Set layerSet = new HashSet(); // to avoid repeated elements
//
// // Search among all possible neighbors and to get the layers
// for(Iterator sIt = cell.searchIterator(polyBnd); sIt.hasNext();)
// {
// Geometric g = (Geometric)sIt.next();
// if (g == geom) continue;
// if ((g instanceof ArcInst))
// {
// ArcProto ap = ((ArcInst)g).getProto();
// for (int i = 0; i < ap.getLayers().length; i++)
// layerSet.add(pa.getLayers()[i].getLayer());
// }
// else
// {
// NodeInst ni = (NodeInst)g;
// NodeProto np = ni.getProto();
// if (NodeInst.isSpecialNode(ni)) continue; // Nov 4;
// if (np instanceof Cell)
// {
// System.out.println("Not implemented in checkExtensionRule");
// }
// else
// {
// if (np instanceof PrimitiveNode)
// {
// PrimitiveNode pn = (PrimitiveNode)np;
// for (int i = 0; i < pn.getLayers().length; i++)
// layerSet.add(pn.getLayers()[i].getLayer());
// }
// else
// System.out.println("When do we have this case");
// }
// }
// }
// boolean error = false;
//
// Object[] layerArray = layerSet.toArray();
// for (int i = 0; i < layerArray.length; i++)
// {
// Layer nLayer = (Layer)layerArray[i];
// DRCTemplate extensionRule = DRC.getExtensionRule(layer, nLayer, techMode, false);
// // Checking extension, it could be slow
// if (extensionRule == null) continue;
//
// List list = extensionRule.getNodesInRule();
// // Layers order is revelant, the first element is the one to check for the extension in the second one
// if (list != null && list.size() == 2)
// {
// // Not the correct order
// if (list.get(0) != layer || list.get(1) != nLayer) continue;
// }
//
// Area baseArea = new Area(poly);
// Area overlapArea = new Area(); // start empty
// Area extensionArea = new Area(); // start empty
//
// checkExtensionOverlapRule(geom, nLayer, cell, baseArea, extensionArea, overlapArea, polyBnd);
//
// // get the area outside nLayer
// if (!extensionArea.isEmpty())
// {
// List polyList = PolyBase.getPointsInArea(extensionArea, layer, true, true, null);
//
// for (Iterator it = polyList.iterator(); it.hasNext(); )
// {
// PolyBase nPoly = (PolyBase)it.next();
// Rectangle2D rect = nPoly.getBounds2D();
// int dir = 0; // X assume the intersection edge is Y oriented
// // Determine how they touch. This is to get the perpendicular direction to the common edge.
// if ((rect.getMaxY() == poly.getBounds2D().getMinY()) ||
// (rect.getMinY() == poly.getBounds2D().getMaxY()) )
// dir = 1; // Y
//
// // not easy to determine along which axis they are touching
// if ((dir == 1 && rect.getHeight() < extensionRule.value) || (dir == 0 && rect.getWidth() < extensionRule.value))
// {
// reportError(LAYERSURROUNDERROR, "No enough extension, ", cell, extensionRule.value, -1, extensionRule.ruleName,
// nPoly, geom, layer, null, null, nLayer);
// error = true;
// }
// }
// }
//
// // There is overlap
// if (!overlapArea.isEmpty())
// {
// List polyList = PolyBase.getPointsInArea(overlapArea, layer, true, true, null);
//
// for (Iterator it = polyList.iterator(); it.hasNext(); )
// {
// PolyBase nPoly = (PolyBase)it.next();
// Rectangle2D rect = nPoly.getBounds2D();
// // not easy to determine along which axis they are touching
// if (rect.getHeight() < extensionRule.value || rect.getWidth() < extensionRule.value)
// {
// reportError(LAYERSURROUNDERROR, "No enough overlap, ", cell, extensionRule.value, -1, extensionRule.ruleName,
// nPoly, geom, layer, null, null, nLayer);
// error = true;
// }
// }
// }
// }
// return (error);
}
/**
*
* @param geom
* @param cell
* @param extensionArea contains information about poly area outside of nLayer
* @param overlapArea
* @param polyBnd
*/
private void checkExtensionOverlapRule(Geometric geom, Layer layer, Cell cell, Area baseArea,
Area extensionArea, Area overlapArea,
Rectangle2D polyBnd)
{
for(Iterator sIt = cell.searchIterator(polyBnd); sIt.hasNext(); )
{
Geometric g = (Geometric)sIt.next();
if (g == geom) continue;
if ((g instanceof NodeInst))
{
NodeInst ni = (NodeInst)g;
NodeProto np = ni.getProto();
if (NodeInst.isSpecialNode(ni)) continue; // Nov 4;
if (np instanceof Cell)
{
AffineTransform cellDownTrans = ni.transformIn();
AffineTransform cellUpTrans = ni.transformOut();
DBMath.transformRect(polyBnd, cellDownTrans);
extensionArea.transform(cellDownTrans);
overlapArea.transform(cellDownTrans);
checkExtensionOverlapRule(geom, layer, (Cell)np, baseArea, extensionArea, overlapArea, polyBnd);
DBMath.transformRect(polyBnd, cellUpTrans);
extensionArea.transform(cellUpTrans);
overlapArea.transform(cellUpTrans);
continue;
}
}
Poly [] primPolyList = getShapeOfGeometric(g, layer);
int tot = primPolyList.length;
for(int j=0; j<tot; j++)
{
Poly nPoly = primPolyList[j];
// Checking if are covered by select is surrounded by minOverlapRule
Area nPolyArea = new Area(nPoly);
Area interPolyArea = (Area)nPolyArea.clone();
interPolyArea.intersect(baseArea);
overlapArea.add(interPolyArea);
Area extenPolyArea = (Area)nPolyArea.clone();
extenPolyArea.subtract(interPolyArea);
extensionArea.add(extenPolyArea);
}
}
}
/****************************** Select Over Polysilicon Functions ***************************/
/**
* Method to check if non-transistor polysilicons are completed covered by N++/P++ regions
*/
private boolean checkSelectOverPolysilicon(Geometric geom, Layer layer, Poly poly, Cell cell)
{
if(DRC.isIgnoreExtensionRuleChecking()) return false;
if (!layer.getFunction().isPoly()) return false;
// One layer must be select and other polysilicon. They are not connected
DRCTemplate minOverlapRule = DRC.getMinValue(layer, DRCTemplate.EXTENSION, techMode);
if (minOverlapRule == null) return false;
Rectangle2D polyBnd = poly.getBounds2D();
Area polyArea = new Area(poly);
boolean found = polyArea.isEmpty();
List checkExtraPoints = new ArrayList();
found = checkThisCellExtensionRule(geom, layer, poly, null, cell, polyArea, polyBnd, minOverlapRule,
found, checkExtraPoints);
// error if the merged area doesn't contain 100% the search area.
if (!found)
{
List polyList = PolyBase.getPointsInArea(polyArea, layer, true, true, null);
for (Iterator it = polyList.iterator(); it.hasNext(); )
{
PolyBase nPoly = (PolyBase)it.next();
reportError(LAYERSURROUNDERROR, "Polysilicon not covered, ", cell, minOverlapRule.value1, -1, minOverlapRule.ruleName,
nPoly, geom, layer, null, null, null);
}
}
else
{
// Checking if not enough coverage
Point2D[] extraPoints = new Point2D[checkExtraPoints.size()];
checkExtraPoints.toArray(extraPoints);
boolean[] founds = new boolean[checkExtraPoints.size()];
Arrays.fill(founds, false);
Rectangle2D ruleBnd = new Rectangle2D.Double(polyBnd.getMinX()-minOverlapRule.value1,
polyBnd.getMinY()-minOverlapRule.value1,
polyBnd.getWidth() + minOverlapRule.value1*2,
polyBnd.getHeight() + minOverlapRule.value1*2);
boolean foundAll = allPointsContainedInLayer(geom, cell, ruleBnd, null, extraPoints, founds);
if (!foundAll)
reportError(LAYERSURROUNDERROR, "No enough surround, ", geom.getParent(), minOverlapRule.value1, -1, minOverlapRule.ruleName,
poly, geom, layer, null, null, null);
}
return (!found);
}
private boolean checkThisCellExtensionRule(Geometric geom, Layer layer, Poly poly, List drcLayers, Cell cell, Area polyArea,
Rectangle2D polyBnd, DRCTemplate minOverlapRule, boolean found,
List checkExtraPoints)
{
boolean[] founds = new boolean[4];
for(Iterator sIt = cell.searchIterator(polyBnd); !found && sIt.hasNext(); )
{
Geometric g = (Geometric)sIt.next();
if (g == geom) continue;
if (!(g instanceof NodeInst))
{
if (Main.LOCALDEBUGFLAG && !DRC.isIgnoreExtensionRuleChecking())
System.out.println("Skipping arcs!");
continue; // Skipping arcs!!!!
}
NodeInst ni = (NodeInst)g;
NodeProto np = ni.getProto();
if (NodeInst.isSpecialNode(ni)) continue; // Nov 4;
if (np instanceof Cell)
{
AffineTransform cellDownTrans = ni.transformIn();
AffineTransform cellUpTrans = ni.transformOut();
DBMath.transformRect(polyBnd, cellDownTrans);
polyArea.transform(cellDownTrans);
poly.transform(cellDownTrans);
List newExtraPoints = new ArrayList();
found = checkThisCellExtensionRule(geom, layer, poly, drcLayers, (Cell)np, polyArea, polyBnd, minOverlapRule,
found, newExtraPoints);
for (Iterator it = newExtraPoints.iterator(); it.hasNext();)
{
Point2D point = (Point2D)it.next();
cellUpTrans.transform(point, point);
checkExtraPoints.add(point);
}
DBMath.transformRect(polyBnd, cellUpTrans);
polyArea.transform(cellUpTrans);
poly.transform(cellUpTrans);
}
else
{
Technology tech = np.getTechnology();
Poly [] primPolyList = tech.getShapeOfNode(ni, null, null, true, ignoreCenterCuts, drcLayers);
int tot = primPolyList.length;
for(int j=0; j<tot; j++)
{
Poly nPoly = primPolyList[j];
if (drcLayers == null)
if (!nPoly.getLayer().getFunction().isImplant()) continue;
// Checking if are covered by select is surrounded by minOverlapRule
Area distPolyArea = (Area)polyArea.clone();
Area nPolyArea = new Area(nPoly);
polyArea.subtract(nPolyArea);
distPolyArea.subtract(polyArea);
if (distPolyArea.isEmpty())
continue; // no intersection
Rectangle2D interRect = distPolyArea.getBounds2D();
Rectangle2D ruleBnd = new Rectangle2D.Double(interRect.getMinX()-minOverlapRule.value1,
interRect.getMinY()-minOverlapRule.value1,
interRect.getWidth() + minOverlapRule.value1*2,
interRect.getHeight() + minOverlapRule.value1*2);
PolyBase extPoly = new PolyBase(ruleBnd);
PolyBase distPoly = new PolyBase(interRect);
Arrays.fill(founds, false);
// Removing points on original polygon. No very efficient though
Point2D[] points = extPoly.getPoints();
Point2D[] distPoints = distPoly.getPoints();
// Only valid for 4-point polygons!!
if (distPoints.length != points.length)
System.out.println("This case is not valid in Quick.checkThisCellExtensionRule");
for (int i = 0; i < points.length; i++)
{
// Check if point is corner
found = poly.isPointOnCorner(distPoints[i]);
// Point along edge
if (!found)
founds[i] = true;
}
boolean foundAll = allPointsContainedInLayer(geom, cell, ruleBnd, drcLayers, points, founds);
if (!foundAll)
{
// Points that should be checked from geom parent
for (int i = 0; i < founds.length; i++)
{
if (!founds[i]) checkExtraPoints.add(points[i]);
}
}
}
}
found = polyArea.isEmpty();
}
return (found);
}
/**
* Method to check if certain poly rectangle is fully covered by any select regoin
*/
private boolean allPointsContainedInLayer(Geometric geom, Cell cell, Rectangle2D ruleBnd, List drcLayers, Point2D[] points, boolean[] founds)
{
for(Iterator sIt = cell.searchIterator(ruleBnd); sIt.hasNext(); )
{
Geometric g = (Geometric)sIt.next();
if (g == geom) continue;
if (!(g instanceof NodeInst)) continue;
NodeInst ni = (NodeInst)g;
NodeProto np = ni.getProto();
if (NodeInst.isSpecialNode(ni)) continue; // Nov 4;
if (np instanceof Cell)
{
AffineTransform cellDownTrans = ni.transformIn();
AffineTransform cellUpTrans = ni.transformOut();
DBMath.transformRect(ruleBnd, cellDownTrans);
cellDownTrans.transform(points, 0, points, 0, points.length);
boolean allFound = allPointsContainedInLayer(geom, (Cell)np, ruleBnd, drcLayers, points, founds);
DBMath.transformRect(ruleBnd, cellUpTrans);
cellUpTrans.transform(points, 0, points, 0, points.length);
if (allFound)
return true;
}
else
{
Technology tech = np.getTechnology();
Poly [] primPolyList = tech.getShapeOfNode(ni, null, null, true, ignoreCenterCuts, drcLayers);
int tot = primPolyList.length;
for(int j=0; j<tot; j++)
{
Poly nPoly = primPolyList[j];
if (!nPoly.getLayer().getFunction().isImplant()) continue;
boolean allFound = true;
// No need of looping if one of them is already out
for (int i = 0; i < points.length; i++)
{
if (!founds[i]) founds[i] = nPoly.contains(points[i]);
if (!founds[i]) allFound = false;
}
if (allFound) return true;
}
}
}
return (false);
}
/***************************END of Select Over Polysilicn Functions ************************************/
/**
* Method to see if the two boxes are active elements, connected to opposite
* sides of a field-effect transistor that resides inside of the box area.
* Returns true if so.
*/
private boolean activeOnTransistor(Poly poly1, Layer layer1, int net1,
Poly poly2, Layer layer2, int net2, Cell cell, int globalIndex)
{
// networks must be different
if (net1 == net2) return false;
// layers must be active or active contact
Layer.Function fun = layer1.getFunction();
int funExtras = layer1.getFunctionExtras();
if (!fun.isDiff())
{
if (!fun.isContact() || (funExtras&Layer.Function.CONDIFF) == 0) return false;
}
funExtras = layer2.getFunctionExtras();
fun = layer2.getFunction();
if (!fun.isDiff())
{
if (!fun.isContact() || (funExtras&Layer.Function.CONDIFF) == 0) return false;
}
// search for intervening transistor in the cell
Rectangle2D bounds1 = poly1.getBounds2D();
Rectangle2D bounds2 = poly2.getBounds2D();
Rectangle2D.union(bounds1, bounds2, bounds1);
return activeOnTransistorRecurse(bounds1, net1, net2, cell, globalIndex, DBMath.MATID);
}
private boolean activeOnTransistorRecurse(Rectangle2D bounds,
int net1, int net2, Cell cell, int globalIndex, AffineTransform trans)
{
Netlist netlist = getCheckProto(cell).netlist;
Rectangle2D subBounds = new Rectangle2D.Double();
for(Iterator sIt = cell.searchIterator(bounds); sIt.hasNext(); )
{
Geometric g = (Geometric)sIt.next();
if (!(g instanceof NodeInst)) continue;
NodeInst ni = (NodeInst)g;
NodeProto np = ni.getProto();
if (np instanceof Cell)
{
AffineTransform rTransI = ni.rotateIn();
AffineTransform tTransI = ni.translateIn();
rTransI.preConcatenate(tTransI);
subBounds.setRect(bounds);
DBMath.transformRect(subBounds, rTransI);
CheckInst ci = (CheckInst)checkInsts.get(ni);
int localIndex = globalIndex * ci.multiplier + ci.localIndex + ci.offset;
boolean ret = activeOnTransistorRecurse(subBounds,
net1, net2, (Cell)np, localIndex, trans);
if (ret) return true;
continue;
}
// must be a transistor
if (!ni.isFET()) continue;
// must be inside of the bounding box of the desired layers
Rectangle2D nodeBounds = ni.getBounds();
double cX = nodeBounds.getCenterX();
double cY = nodeBounds.getCenterY();
if (cX < bounds.getMinX() || cX > bounds.getMaxX() ||
cY < bounds.getMinY() || cY > bounds.getMaxY()) continue;
// determine the poly port (MUST BE BETTER WAY!!!!)
PortProto badport = np.getPort(0);
Network badNet = netlist.getNetwork(ni, badport, 0);
boolean on1 = false, on2 = false;
for(Iterator it = ni.getPortInsts(); it.hasNext(); )
{
PortInst pi = (PortInst)it.next();
PortProto po = pi.getPortProto();
String name = po.getName();
boolean found = false;
boolean oldFound = false;
Network piNet = netlist.getNetwork(pi);
// ignore connections on poly/gate
if (name.indexOf("poly") != -1)
{
found = true;
//continue;
}
if (piNet == badNet)
oldFound = true;
if (Main.LOCALDEBUGFLAG && oldFound != found)
System.out.println("Here is different in activeOnTransistorRecurse");
if (found)
continue;
Integer [] netNumbers = (Integer [])networkLists.get(piNet);
int net = netNumbers[globalIndex].intValue();
if (net < 0) continue;
if (net == net1) on1 = true;
if (net == net2) on2 = true;
}
// if either side is not connected, ignore this
if (!on1 || !on2) continue;
// transistor found that connects to both actives
return true;
}
return false;
}
/**
* Method to crop the box on layer "nLayer", electrical index "nNet"
* and bounds (lx-hx, ly-hy) against the nodeinst "ni". The geometry in nodeinst "ni"
* that is being checked runs from (nlx-nhx, nly-nhy). Only those layers
* in the nodeinst that are the same layer and the same electrical network
* are checked. Returns true if the bounds are reduced
* to nothing.
*/
private boolean cropNodeInst(NodeInst ni, int globalIndex, AffineTransform trans,
Layer nLayer, int nNet, Geometric nGeom, Rectangle2D bound)
{
Technology tech = ni.getProto().getTechnology();
Poly [] cropNodePolyList = tech.getShapeOfNode(ni, null, null, true, ignoreCenterCuts, null);
convertPseudoLayers(ni, cropNodePolyList);
int tot = cropNodePolyList.length;
if (tot < 0) return false;
// Change #1
// for(int j=0; j<tot; j++)
// cropNodePolyList[j].transform(trans);
boolean [] rotated = new boolean[tot];
Arrays.fill(rotated, false);
boolean isConnected = false;
Netlist netlist = getCheckProto(ni.getParent()).netlist;
for(int j=0; j<tot; j++)
{
Poly poly = cropNodePolyList[j];
if (!tech.sameLayer(poly.getLayer(), nLayer)) continue;
//only transform when poly is valid
poly.transform(trans); // change 1
rotated[j] = true;
if (nNet >= 0)
{
if (poly.getPort() == null) continue;
// determine network for this polygon
int net = getDRCNetNumber(netlist, poly.getPort(), ni, globalIndex);
if (net >= 0 && net != nNet) continue;
}
isConnected = true;
break;
}
if (!isConnected) return false;
// get the description of the nodeinst layers
boolean allgone = false;
for(int j=0; j<tot; j++)
{
Poly poly = cropNodePolyList[j];
if (!tech.sameLayer(poly.getLayer(), nLayer)) continue;
if (!rotated[j]) poly.transform(trans); // change 1
// warning: does not handle arbitrary polygons, only boxes
Rectangle2D polyBox = poly.getBox();
if (polyBox == null) continue;
int temp = Poly.cropBox(bound, polyBox);
if (temp > 0) { allgone = true; break; }
if (temp < 0)
{
tinyNodeInst = ni;
tinyGeometric = nGeom;
}
}
return allgone;
}
/**
* Method to crop away any part of layer "lay" of arcinst "ai" that coincides
* with a similar layer on a connecting nodeinst. The bounds of the arcinst
* are in the reference parameters (lx-hx, ly-hy). Returns false
* normally, 1 if the arcinst is cropped into oblivion.
*/
private boolean cropArcInst(ArcInst ai, Layer lay, AffineTransform inTrans, Rectangle2D bounds)
{
for(int i=0; i<2; i++)
{
// find the primitive nodeinst at the true end of the portinst
PortInst pi = ai.getPortInst(i);
PortOriginal fp = new PortOriginal(pi, inTrans);
NodeInst ni = fp.getBottomNodeInst();
NodeProto np = ni.getProto();
AffineTransform trans = fp.getTransformToTop();
Technology tech = np.getTechnology();
Poly [] cropArcPolyList = tech.getShapeOfNode(ni, null, null, false, ignoreCenterCuts, null);
int tot = cropArcPolyList.length;
for(int j=0; j<tot; j++)
{
Poly poly = cropArcPolyList[j];
if (!tech.sameLayer(poly.getLayer(), lay)) continue;
poly.transform(trans);
// warning: does not handle arbitrary polygons, only boxes
Rectangle2D polyBox = poly.getBox();
if (polyBox == null) continue;
int temp = Poly.halfCropBox(bounds, polyBox);
if (temp > 0) return true;
if (temp < 0)
{
tinyNodeInst = ni;
tinyGeometric = ai;
}
}
}
return false;
}
/**
* Method to see if polygons in "pList" (describing arc "ai") should be cropped against a
* connecting transistor. Crops the polygon if so.
*/
private void cropActiveArc(ArcInst ai, Poly [] pList)
{
// look for an active layer in this arc
int tot = pList.length;
int diffPoly = -1;
for(int j=0; j<tot; j++)
{
Poly poly = pList[j];
Layer layer = poly.getLayer();
if (layer == null) continue;
Layer.Function fun = layer.getFunction();
if (fun.isDiff()) { diffPoly = j; break; }
}
if (diffPoly < 0) return;
Poly poly = pList[diffPoly];
// must be manhattan
Rectangle2D polyBounds = poly.getBox();
if (polyBounds == null) return;
polyBounds = new Rectangle2D.Double(polyBounds.getMinX(), polyBounds.getMinY(), polyBounds.getWidth(), polyBounds.getHeight());
// search for adjoining transistor in the cell
boolean cropped = false;
boolean halved = false;
for(int i=0; i<2; i++)
{
PortInst pi = ai.getPortInst(i);
NodeInst ni = pi.getNodeInst();
if (!ni.isFET()) continue;
// crop the arc against this transistor
AffineTransform trans = ni.rotateOut();
Technology tech = ni.getProto().getTechnology();
Poly [] activeCropPolyList = tech.getShapeOfNode(ni, null, null, false, ignoreCenterCuts, null);
int nTot = activeCropPolyList.length;
for(int k=0; k<nTot; k++)
{
Poly nPoly = activeCropPolyList[k];
if (nPoly.getLayer() != poly.getLayer()) continue;
nPoly.transform(trans);
Rectangle2D nPolyBounds = nPoly.getBox();
if (nPolyBounds == null) continue;
// @TODO Why only one half is half crop?
// Should I change cropBox by cropBoxComplete?
int result = (halved) ?
Poly.cropBox(polyBounds, nPolyBounds) :
Poly.halfCropBox(polyBounds, nPolyBounds);
if (result == 1)
{
// remove this polygon from consideration
poly.setLayer(null);
return;
}
cropped = true;
halved = true;
}
}
if (cropped)
{
Poly.Type style = poly.getStyle();
Layer layer = poly.getLayer();
poly = new Poly(polyBounds);
poly.setStyle(style);
poly.setLayer(layer);
pList[diffPoly] = poly;
}
}
/**
* Method to convert all Layer information in the Polys to be non-pseudo.
* This is only done for pins that have exports but no arcs.
* @param ni the NodeInst being converted.
* @param pList an array of Polys with Layer information for the NodeInst.
*/
private void convertPseudoLayers(NodeInst ni, Poly [] pList)
{
if (ni.getProto().getFunction() != PrimitiveNode.Function.PIN) return;
if (ni.getNumConnections() != 0) return;
if (ni.getNumExports() == 0) return;
// for pins that are unconnected but have exports, convert them to real layers
int tot = pList.length;
for(int i=0; i<tot; i++)
{
Poly poly = pList[i];
Layer layer = poly.getLayer();
if (layer != null)
poly.setLayer(layer.getNonPseudoLayer());
}
}
/**
* Method to determine which layers in a Technology are valid.
*/
private void cacheValidLayers(Technology tech)
{
if (tech == null) return;
if (layersValidTech == tech) return;
layersValidTech = tech;
// determine the layers that are being used
int numLayers = tech.getNumLayers();
layersValid = new boolean[numLayers];
for(int i=0; i < numLayers; i++)
layersValid[i] = false;
for(Iterator it = tech.getNodes(); it.hasNext(); )
{
PrimitiveNode np = (PrimitiveNode)it.next();
if (np.isNotUsed()) continue;
Technology.NodeLayer [] layers = np.getLayers();
for(int i=0; i<layers.length; i++)
{
Layer layer = layers[i].getLayer();
layersValid[layer.getIndex()] = true;
}
}
for(Iterator it = tech.getArcs(); it.hasNext(); )
{
ArcProto ap = (ArcProto)it.next();
if (ap.isNotUsed()) continue;
Technology.ArcLayer [] layers = ap.getLayers();
for(int i=0; i<layers.length; i++)
{
Layer layer = layers[i].getLayer();
layersValid[layer.getIndex()] = true;
}
}
}
/**
* Method to determine the minimum distance between "layer1" and "layer2" in technology
* "tech" and library "lib". If "con" is true, the layers are connected. Also forces
* connectivity for same-implant layers.
*/
private DRCTemplate getSpacingRule(Layer layer1, Poly poly1, Layer layer2, Poly poly2,
boolean con, int multi)
{
// if they are implant on the same layer, they connect
if (!con && layer1 == layer2)
{
Layer.Function fun = layer1.getFunction();
// treat all wells as connected
con = fun.isSubstrate();
}
double[] values = layer1.getTechnology().getSpacingDistances(poly1, poly2);
return (DRC.getSpacingRule(layer1, layer2, con, multi, values[0], values[1], techMode));
}
/**
* Method to retrieve network from a Geometric object (NodeInst, ArcInst)
* @param netlist
* @param geom
* @param poly
* @return
*/
private Network getDRCNetNumber(Netlist netlist, Geometric geom, Poly poly)
{
Network jNet = null;
if (geom instanceof ArcInst)
{
ArcInst ai = (ArcInst)geom;
jNet = netlist.getNetwork(ai, 0);
} else if (geom instanceof NodeInst)
jNet = netlist.getNetwork((NodeInst)geom, poly.getPort(), 0);
return jNet;
}
/**
* Method to return the network number for port "pp" on node "ni", given that the node is
* in a cell with global index "globalIndex".
*/
private int getDRCNetNumber(Netlist netlist, PortProto pp, NodeInst ni, int globalIndex)
{
if (pp == null) return -1;
//@TODO REPLACE BY getNetwork(Nodable no, PortProto portProto, int busIndex)
// or getNetIndex(Nodable no, PortProto portProto, int busIndex)
// see if there is an arc connected
Network net = netlist.getNetwork(ni, pp, 0);
Integer [] nets = (Integer [])networkLists.get(net);
if (nets == null) return -1;
return nets[globalIndex].intValue();
}
/***************** LAYER INTERACTIONS ******************/
/**
* Method to build the internal data structures that tell which layers interact with
* which primitive nodes in technology "tech".
*/
private void buildLayerInteractions(Technology tech)
{
Technology old = layerInterTech;
if (layerInterTech == tech) return;
layerInterTech = tech;
int numLayers = tech.getNumLayers();
// build the node table
if (layersInterNodes != null && old != null && job != null)
{
errorLogger.logWarning("Switching from '" + old.getTechName() +
"' to '" + tech.getTechName() + "' in DRC process. Check for non desired nodes in " +
job.cell, null, -1);
}
layersInterNodes = new HashMap();
for(Iterator it = tech.getNodes(); it.hasNext(); )
{
PrimitiveNode np = (PrimitiveNode)it.next();
if (np.isNotUsed()) continue;
boolean [] layersInNode = new boolean[numLayers];
Arrays.fill(layersInNode, false);
Technology.NodeLayer [] layers = np.getLayers();
Technology.NodeLayer [] eLayers = np.getElectricalLayers();
if (eLayers != null) layers = eLayers;
for(int i=0; i<layers.length; i++)
{
Layer layer = layers[i].getLayer();
for(Iterator lIt = tech.getLayers(); lIt.hasNext(); )
{
Layer oLayer = (Layer)lIt.next();
if (DRC.isAnyRule(layer, oLayer))
layersInNode[oLayer.getIndex()] = true;
}
}
layersInterNodes.put(np, layersInNode);
}
// build the arc table
layersInterArcs = new HashMap();
for(Iterator it = tech.getArcs(); it.hasNext(); )
{
ArcProto ap = (ArcProto)it.next();
boolean [] layersInArc = new boolean[numLayers];
for(int i=0; i<numLayers; i++) layersInArc[i] = false;
Technology.ArcLayer [] layers = ap.getLayers();
for(int i=0; i<layers.length; i++)
{
Layer layer = layers[i].getLayer();
for(Iterator lIt = tech.getLayers(); lIt.hasNext(); )
{
Layer oLayer = (Layer)lIt.next();
if (DRC.isAnyRule(layer, oLayer))
layersInArc[oLayer.getIndex()] = true;
}
}
layersInterArcs.put(ap, layersInArc);
}
}
/**
* Method to determine whether layer "layer" interacts in any way with a node of type "np".
* If not, returns FALSE.
*/
private boolean checkLayerWithNode(Layer layer, NodeProto np)
{
buildLayerInteractions(np.getTechnology());
// find this node in the table
boolean [] validLayers = (boolean [])layersInterNodes.get(np);
if (validLayers == null) return false;
return validLayers[layer.getIndex()];
}
/**
* Method to determine whether layer "layer" interacts in any way with an arc of type "ap".
* If not, returns FALSE.
*/
private boolean checkLayerWithArc(Layer layer, ArcProto ap)
{
buildLayerInteractions(ap.getTechnology());
// find this node in the table
boolean [] validLayers = (boolean [])layersInterArcs.get(ap);
if (validLayers == null) return false;
return validLayers[layer.getIndex()];
}
/**
* Method to recursively scan cell "cell" (transformed with "trans") searching
* for DRC Exclusion nodes. Each node is added to the global list "exclusionList".
*/
private void accumulateExclusion(Cell cell)
{
for(Iterator it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = (NodeInst)it.next();
NodeProto np = ni.getProto();
if (np == Generic.tech.drcNode)
{
DRCExclusion dex = new DRCExclusion();
dex.cell = cell;
// extract the information about this DRC exclusion node
dex.poly = new Poly(ni.getBounds());
/*
AffineTransform subUpTrans = ni.rotateOut();
subUpTrans.preConcatenate(upTrans);
dex.poly.transform(subUpTrans);
*/
dex.poly.setStyle(Poly.Type.FILLED);
dex.ni = ni;
// see if it is already in the list
boolean found = false;
for(Iterator dIt = exclusionList.iterator(); dIt.hasNext(); )
{
DRCExclusion oDex = (DRCExclusion)dIt.next();
if (oDex.cell != cell) continue;
if (oDex.poly.polySame(dex.poly))
{
found = true;
break;
}
}
if (!found) exclusionList.add(dex);
continue;
}
if (np instanceof Cell)
{
// examine contents
// AffineTransform tTrans = ni.translateOut(ni.rotateOut());
accumulateExclusion((Cell)np);
}
}
}
/*********************************** QUICK DRC ERROR REPORTING ***********************************/
/* Adds details about an error to the error list */
private void reportError(int errorType, String msg,
Cell cell, double limit, double actual, String rule,
PolyBase poly1, Geometric geom1, Layer layer1,
PolyBase poly2, Geometric geom2, Layer layer2)
{
if (errorLogger == null) return;
// if this error is in an ignored area, don't record it
StringBuffer DRCexclusionMsg = new StringBuffer();
if (exclusionList.size() > 0)
{
// determine the bounding box of the error
List polyList = new ArrayList(2);
List geomList = new ArrayList(2);
polyList.add(poly1); geomList.add(geom1);
if (poly2 != null)
{
polyList.add(poly2);
geomList.add(geom2);
}
for(Iterator it = exclusionList.iterator(); it.hasNext(); )
{
DRCExclusion dex = (DRCExclusion)it.next();
if (cell != dex.cell) continue;
Poly poly = dex.poly;
int count = 0;
for (int i = 0; i < polyList.size(); i++)
{
Poly thisPoly = (Poly)polyList.get(i);
if (thisPoly == null)
continue; // MinNode case
boolean found = poly.contains(thisPoly.getBounds2D());
if (found) count++;
else DRCexclusionMsg.append("\n\t(DRC Exclusion '" + dex.ni.getName() + "' does not completely contain " +
((Geometric)geomList.get(i)) + ")");
}
// At least one DRC exclusion that contains both
if (count == polyList.size())
return;
}
}
// describe the error
Cell np1 = (geom1 != null) ? geom1.getParent() : null;
Cell np2 = (geom2 != null) ? geom2.getParent() : null;
// Message already logged
boolean onlyWarning = (errorType == ZEROLENGTHARCWARN || errorType == TECHMIXWARN);
// Until a decent algorithm is in place for detecting repeated errors, ERROR_CHECK_EXHAUSTIVE might report duplicate errros
if ( geom2 != null && errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE && errorLogger.findMessage(cell, geom1, geom2.getParent(), geom2, !onlyWarning))
return;
StringBuffer errorMessage = new StringBuffer();
int sortLayer = cell.hashCode(); // 0;
if (errorType == SPACINGERROR || errorType == NOTCHERROR || errorType == SURROUNDERROR)
{
// describe spacing width error
if (errorType == SPACINGERROR)
errorMessage.append("Spacing");
else if (errorType == SURROUNDERROR)
errorMessage.append("Surround");
else
errorMessage.append("Notch");
if (layer1 == layer2)
errorMessage.append(" (layer '" + layer1.getName() + "')");
errorMessage.append(": ");
if (np1 != np2)
{
errorMessage.append(np1 + ", ");
} else if (np1 != cell)
{
errorMessage.append("[in " + np1 + "] ");
}
errorMessage.append(geom1);
if (layer1 != layer2)
errorMessage.append(", layer '" + layer1.getName() + "'");
if (actual < 0) errorMessage.append(" OVERLAPS ");
else if (actual == 0) errorMessage.append(" TOUCHES ");
else errorMessage.append(" LESS (BY " + TextUtils.formatDouble(limit-actual) + ") THAN " + TextUtils.formatDouble(limit) + " TO ");
if (np1 != np2)
errorMessage.append(np2 + ", ");
errorMessage.append(geom2);
if (layer1 != layer2)
errorMessage.append(", layer '" + layer2.getName() + "'");
if (msg != null)
errorMessage.append("; " + msg);
} else
{
// describe minimum width/size or layer error
StringBuffer errorMessagePart2 = null;
switch (errorType)
{
case RESOLUTION:
errorMessage.append("Resolution error:");
errorMessagePart2 = new StringBuffer(msg);
break;
case FORBIDDEN:
errorMessage.append("Forbidden error:");
errorMessagePart2 = new StringBuffer(msg);
break;
case MINAREAERROR:
errorMessage.append("Minimum area error:");
errorMessagePart2 = new StringBuffer(", layer '" + layer1.getName() + "'");
errorMessagePart2.append(" LESS THAN " + TextUtils.formatDouble(limit) + " IN AREA (IS " + TextUtils.formatDouble(actual) + ")");
break;
case ENCLOSEDAREAERROR:
errorMessage.append("Enclosed area error:");
errorMessagePart2 = new StringBuffer(", layer '" + layer1.getName() + "'");
errorMessagePart2.append(" LESS THAN " + TextUtils.formatDouble(limit) + " IN AREA (IS " + TextUtils.formatDouble(actual) + ")");
break;
case TECHMIXWARN:
errorMessage.append("Technology mixture warning:");
errorMessagePart2 = new StringBuffer(msg);
break;
case ZEROLENGTHARCWARN:
errorMessage.append("Zero width warning:");
errorMessagePart2 = new StringBuffer(msg); break;
case CUTERROR:
errorMessage.append("Maximum cut error" + ((msg != null) ? ("(" + msg + "):") : ""));
errorMessagePart2 = new StringBuffer(", layer '" + layer1.getName() + "'");
errorMessagePart2.append(" BIGGER THAN " + TextUtils.formatDouble(limit) + " WIDE (IS " + TextUtils.formatDouble(actual) + ")");
break;
case MINWIDTHERROR:
errorMessage.append("Minimum width/heigh error" + ((msg != null) ? ("(" + msg + "):") : ""));
errorMessagePart2 = new StringBuffer(", layer '" + layer1.getName() + "'");
errorMessagePart2.append(" LESS THAN " + TextUtils.formatDouble(limit) + " WIDE (IS " + TextUtils.formatDouble(actual) + ")");
break;
case MINSIZEERROR:
errorMessage.append("Minimum size error on " + msg + ":");
errorMessagePart2 = new StringBuffer(" LESS THAN " + TextUtils.formatDouble(limit) + " IN SIZE (IS " + TextUtils.formatDouble(actual) + ")");
break;
case BADLAYERERROR:
errorMessage.append("Invalid layer ('" + layer1.getName() + "'):");
break;
case LAYERSURROUNDERROR:
errorMessage.append("Layer surround error: " + msg);
errorMessagePart2 = new StringBuffer(", layer '" + layer1.getName() + "'");
String layerName = (layer2 != null) ? layer2.getName() : "Select";
errorMessagePart2.append(" NEEDS SURROUND OF LAYER '" + layerName + "' BY " + limit);
break;
}
errorMessage.append(" " + cell + " ");
if (geom1 != null)
{
errorMessage.append(geom1);
}
if (layer1 != null) sortLayer = layer1.getIndex();
errorMessage.append(errorMessagePart2);
}
if (rule != null && rule.length() > 0) errorMessage.append(" [rule '" + rule + "']");
errorMessage.append(DRCexclusionMsg);
ErrorLogger.MessageLog err = (onlyWarning) ?
errorLogger.logWarning(errorMessage.toString(), cell, sortLayer) :
errorLogger.logError(errorMessage.toString(), cell, sortLayer);
boolean showGeom = true;
if (poly1 != null) { showGeom = false; err.addPoly(poly1, true, cell); }
if (poly2 != null) { showGeom = false; err.addPoly(poly2, true, cell); }
if (geom1 != null) err.addGeom(geom1, showGeom, cell, null);
if (geom2 != null) err.addGeom(geom2, showGeom, cell, null);
}
/**************************************************************************************************************
* QuickAreaEnumerator class
**************************************************************************************************************/
// Extra functions to check area
private class QuickAreaEnumerator extends HierarchyEnumerator.Visitor
{
private Network jNet;
private GeometryHandler mainMerge;
private GeometryHandler otherTypeMerge;
private Layer polyLayer;
private HashMap notExportedNodes;
private HashMap checkedNodes;
private int mode; // geometrical merge algorithm
public QuickAreaEnumerator(Network jNet, GeometryHandler selectMerge, HashMap notExportedNodes,
HashMap checkedNodes, int mode)
{
this.jNet = jNet;
this.otherTypeMerge = selectMerge;
this.notExportedNodes = notExportedNodes;
this.checkedNodes = checkedNodes;
this.mode = mode;
}
public QuickAreaEnumerator(HashMap notExportedNodes, HashMap checkedNodes, int mode)
{
this.notExportedNodes = notExportedNodes;
this.checkedNodes = checkedNodes;
this.mode = mode;
}
/**
*/
public boolean enterCell(HierarchyEnumerator.CellInfo info)
{
if (job != null && job.checkAbort()) return false;
if (mainMerge == null)
{
//mainMerge = new PolyQTree(info.getCell().getBounds());
mainMerge = GeometryHandler.createGeometryHandler(mode, info.getCell().getTechnology().getNumLayers(),
info.getCell().getBounds());
}
AffineTransform rTrans = info.getTransformToRoot();
// Check Arcs too if network is not null
if (jNet != null)
{
for(Iterator it = info.getCell().getArcs(); it.hasNext(); )
{
ArcInst ai = (ArcInst)it.next();
Technology tech = ai.getProto().getTechnology();
Network aNet = info.getNetlist().getNetwork(ai, 0);
boolean found = false;
// aNet is null if ArcProto is Artwork
if (aNet != null)
{
for (Iterator arcIt = aNet.getExports(); !found && arcIt.hasNext();)
{
Export exp = (Export)arcIt.next();
Network net = info.getNetlist().getNetwork(exp, 0);
found = HierarchyEnumerator.searchNetworkInParent(net, info, jNet);
}
}
if (!found && aNet != jNet)
continue; // no same net
Poly [] arcInstPolyList = tech.getShapeOfArc(ai);
int tot = arcInstPolyList.length;
for(int i=0; i<tot; i++)
{
Poly poly = arcInstPolyList[i];
Layer layer = poly.getLayer();
// No area associated
if (minAreaLayerMap.get(layer) == null && enclosedAreaLayerMap.get(layer) == null)
continue;
// it has to take into account poly and transistor poly as one layer
if (layer.getFunction().isPoly())
{
if (polyLayer == null)
polyLayer = layer;
layer = polyLayer;
}
poly.transform(rTrans);
addElement(poly, layer, false);
// if (layer.getFunction().isMetal() || layer.getFunction().isPoly())
// mainMerge.add(layer, new PolyQTree.PolyNode(poly.getBounds2D()), false);
// else
// otherTypeMerge.add(layer, new PolyQTree.PolyNode(poly.getBounds2D()), false);
}
}
}
return true;
}
/**
*/
public void exitCell(HierarchyEnumerator.CellInfo info)
{
// if (mergeMode == GeometryHandler.ALGO_SWEEP)
// {
// ((PolySweepMerge)mainMerge).postProcess();
// ((PolySweepMerge)otherTypeMerge).postProcess();
// }
}
/**
*/
public boolean visitNodeInst(Nodable no, HierarchyEnumerator.CellInfo info)
{
if (job != null && job.checkAbort()) return false;
Cell cell = info.getCell();
NodeInst ni = no.getNodeInst();
AffineTransform trans = ni.rotateOut();
NodeProto np = ni.getProto();
AffineTransform root = info.getTransformToRoot();
if (root.getType() != AffineTransform.TYPE_IDENTITY)
trans.preConcatenate(root);
// Cells
if (!(np instanceof PrimitiveNode)) return (true);
PrimitiveNode pNp = (PrimitiveNode)np;
boolean found = false;
boolean forceChecking = false;
if (jNet != null)
{
boolean pureNode = (pNp.getFunction() == PrimitiveNode.Function.NODE);
if (np instanceof PrimitiveNode)
{
if (NodeInst.isSpecialNode(ni)) return (false);
forceChecking = pNp.isPureSubstrateNode(); // forcing the checking
}
boolean notExported = false;
Network thisNet = null;
for(Iterator pIt = ni.getPortInsts(); !found && pIt.hasNext(); )
{
PortInst pi = (PortInst)pIt.next();
PortProto pp = pi.getPortProto();
boolean isExported = (pp instanceof Export) && ((Export)pp).getParent() == cell;
thisNet = info.getNetlist().getNetwork(pi);
//found = searchNetworkInParent(thisNet, info);
found = HierarchyEnumerator.searchNetworkInParent(thisNet, info, jNet);
if (!isExported) notExported = true;
}
// Substrate layers are special so we must check node regardless network
notExported = notExported && !forceChecking && !pureNode && info.getParentInfo() != null;
if (!found && !forceChecking)
{
if (notExportedNodes != null && notExported)
{
//addNodeInst(ni, pNp, forceChecking, null, trans, nonExportedMerge, nonExportedMerge);
notExportedNodes.put(ni, ni);
}
//else
return (false);
}
// Removing node if it was found included in a network
notExportedNodes.remove(ni);
checkedNodes.put(ni, ni);
}
else
{
if (!notExportedNodes.containsKey(ni))
return (false); // not to consider
if (checkedNodes.containsKey(ni))
return (false);
}
Technology tech = pNp.getTechnology();
// electrical should not be null due to ports but causes
// problems with poly and transistor-poly
Poly [] nodeInstPolyList = tech.getShapeOfNode(ni, null, null, true, true, null);
int tot = nodeInstPolyList.length;
for(int i=0; i<tot; i++)
{
Poly poly = nodeInstPolyList[i];
Layer layer = poly.getLayer();
// No area rule associated
if (minAreaLayerMap.get(layer) == null && enclosedAreaLayerMap.get(layer) == null)
continue;
// make sure this layer connects electrically to the desired port
// but only when checking networks, no nonExported.
if (jNet != null)
{
PortProto pp = poly.getPort();
found = forceChecking && layer.getFunction().isSubstrate();
if (!found && pp != null)
{
Network net = info.getNetlist().getNetwork(ni, pp, 0);
found = HierarchyEnumerator.searchNetworkInParent(net, info, jNet);
}
// if (!forceChecking && !found) continue;
if (!found) continue;
}
// it has to take into account poly and transistor poly as one layer
if (layer.getFunction().isPoly())
{
if (polyLayer == null)
polyLayer = layer;
layer = polyLayer;
}
poly.roundPoints(); // Trying to avoid mismatches while joining areas.
poly.transform(trans);
addElement(poly, layer, true);
// // otherTypeMerge is null if nonExported nodes are analyzed
// if (otherTypeMerge == null || layer.getFunction().isMetal() || layer.getFunction().isPoly())
// mainMerge.add(layer, new PolyQTree.PolyNode(poly.getBounds2D()), false);
// else
// otherTypeMerge.add(layer, new PolyQTree.PolyNode(poly.getBounds2D()), false);
}
return true;
}
private void addElement(Poly poly, Layer layer, boolean isNode)
{
Object obj = null;
if (mode == GeometryHandler.ALGO_QTREE)
obj = new PolyQTree.PolyNode(poly.getBounds2D());
else
obj = poly;
// otherTypeMerge is null if nonExported nodes are analyzed
if ((isNode && otherTypeMerge == null) || layer.getFunction().isMetal() || layer.getFunction().isPoly())
mainMerge.add(layer, obj, false);
else
otherTypeMerge.add(layer, obj, false);
// if (layer.getFunction().isMetal() || layer.getFunction().isPoly())
// mainMerge.add(layer, new PolyQTree.PolyNode(poly.getBounds2D()), false);
// else
// otherTypeMerge.add(layer, new PolyQTree.PolyNode(poly.getBounds2D()), false);
}
}
/**************************************************************************************************************
* QuickAreaEnumerator class
**************************************************************************************************************/
// Extra functions to check area
private class CheckAreaEnumerator extends HierarchyEnumerator.Visitor
{
HashMap mainMergeMap = new HashMap();
private HashMap otherTypeMergeMap;
private HashMap doneCells = new HashMap(); // Mark if cells are done already.
private Layer polyLayer;
private int mode; // geometrical merge algorithm
public CheckAreaEnumerator(HashMap selectMergeMap, int mode)
{
this.otherTypeMergeMap = selectMergeMap;
this.mode = mode;
}
public CheckAreaEnumerator(int mode)
{
this.mode = mode;
}
/**
*/
public boolean enterCell(HierarchyEnumerator.CellInfo info)
{
if (job != null && job.checkAbort()) return false;
Cell cell = info.getCell();
GeometryHandler thisMerge = (GeometryHandler)(mainMergeMap.get(cell));
GeometryHandler thisOtherMerge = (GeometryHandler)(otherTypeMergeMap.get(cell));
boolean firstTime = false;
if (thisMerge == null)
{
thisMerge = GeometryHandler.createGeometryHandler(mode, cell.getTechnology().getNumLayers(), cell.getBounds());
thisOtherMerge = GeometryHandler.createGeometryHandler(mode, 4, cell.getBounds());
mainMergeMap.put(cell, thisMerge);
otherTypeMergeMap.put(cell, thisOtherMerge);
firstTime = true;
}
// Check Arcs too if network is not null
if (firstTime)
{
for(Iterator it = cell.getArcs(); it.hasNext(); )
{
ArcInst ai = (ArcInst)it.next();
Technology tech = ai.getProto().getTechnology();
Poly [] arcInstPolyList = tech.getShapeOfArc(ai);
int tot = arcInstPolyList.length;
for(int i=0; i<tot; i++)
{
Poly poly = arcInstPolyList[i];
Layer layer = poly.getLayer();
// No area associated
if (minAreaLayerMap.get(layer) == null && enclosedAreaLayerMap.get(layer) == null)
continue;
// it has to take into account poly and transistor poly as one layer
if (layer.getFunction().isPoly())
{
if (polyLayer == null)
polyLayer = layer;
layer = polyLayer;
}
addElement(thisMerge, thisOtherMerge, poly, layer, false);
}
}
}
return true;
}
/**
*/
public void exitCell(HierarchyEnumerator.CellInfo info)
{
Cell cell = info.getCell();
boolean done = doneCells.get(cell) != null;
if (!done)
{
GeometryHandler thisMerge = (GeometryHandler)mainMergeMap.get(info.getCell());
GeometryHandler thisOtherMerge = (GeometryHandler)otherTypeMergeMap.get(info.getCell());
thisMerge.postProcess(true);
thisOtherMerge.postProcess(true);
// merge everything sub trees
for(Iterator it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = (NodeInst)it.next();
NodeProto subNp = ni.getProto();
if (subNp instanceof PrimitiveNode) continue;
// get sub-merge information for the cell instance
GeometryHandler subMerge = (GeometryHandler)mainMergeMap.get(subNp);
if (subMerge != null)
{
AffineTransform tTrans = ni.translateOut(ni.rotateOut());
thisMerge.addAll(subMerge, tTrans);
}
GeometryHandler subOtherMerge = (GeometryHandler)otherTypeMergeMap.get(subNp);
if (subOtherMerge != null)
{
AffineTransform tTrans = ni.translateOut(ni.rotateOut());
thisOtherMerge.addAll(subOtherMerge, tTrans);
}
}
}
// To mark if cell is already done
doneCells.put(cell, cell);
}
/**
*/
public boolean visitNodeInst(Nodable no, HierarchyEnumerator.CellInfo info)
{
if (job != null && job.checkAbort()) return false;
Cell cell = info.getCell();
NodeInst ni = no.getNodeInst();
AffineTransform trans = ni.rotateOut();
NodeProto np = ni.getProto();
// Cells
if (!(np instanceof PrimitiveNode)) return (true);
// No done yet
if (doneCells.get(cell) == null)
{
GeometryHandler thisMerge = (GeometryHandler)mainMergeMap.get(cell);
GeometryHandler thisOtherMerge = (GeometryHandler)otherTypeMergeMap.get(cell);
PrimitiveNode pNp = (PrimitiveNode)np;
if (np instanceof PrimitiveNode)
{
if (NodeInst.isSpecialNode(ni)) return (false);
}
Technology tech = pNp.getTechnology();
// electrical should not be null due to ports but causes
// problems with poly and transistor-poly
Poly [] nodeInstPolyList = tech.getShapeOfNode(ni, null, null, true, true, null);
int tot = nodeInstPolyList.length;
for(int i=0; i<tot; i++)
{
Poly poly = nodeInstPolyList[i];
Layer layer = poly.getLayer();
// No area rule associated
if (minAreaLayerMap.get(layer) == null && enclosedAreaLayerMap.get(layer) == null)
continue;
// it has to take into account poly and transistor poly as one layer
if (layer.getFunction().isPoly())
{
if (polyLayer == null)
polyLayer = layer;
layer = polyLayer;
}
poly.roundPoints(); // Trying to avoid mismatches while joining areas.
poly.transform(trans);
addElement(thisMerge, thisOtherMerge, poly, layer, false);
}
}
return true;
}
private void addElement(GeometryHandler mainMerge, GeometryHandler otherTypeMerge, Poly poly,
Layer layer, boolean isNode)
{
Object obj = null;
if (mode == GeometryHandler.ALGO_QTREE)
obj = new PolyQTree.PolyNode(poly.getBounds2D());
else
obj = poly;
// otherTypeMerge is null if nonExported nodes are analyzed
if ((isNode && otherTypeMerge == null) || layer.getFunction().isMetal() || layer.getFunction().isPoly())
mainMerge.add(layer, obj, false);
else
otherTypeMerge.add(layer, obj, false);
}
}
}
| true | true | private boolean badBoxInArea(Poly poly, Layer layer, Technology tech, int net, Geometric geom, AffineTransform trans,
int globalIndex, Rectangle2D bounds, Cell cell, int cellGlobalIndex,
Cell topCell, int topGlobalIndex, AffineTransform upTrans, boolean baseMulti,
boolean sameInstance)
{
Rectangle2D rBound = new Rectangle2D.Double();
rBound.setRect(bounds);
DBMath.transformRect(rBound, upTrans); // Step 1
Netlist netlist = getCheckProto(cell).netlist;
Rectangle2D subBound = new Rectangle2D.Double(); //Sept 30
boolean foundError = false;
// These nodes won't generate any DRC errors. Most of them are pins
if (geom instanceof NodeInst && NodeInst.isSpecialNode(((NodeInst)geom)))
return false;
// Sept04 changes: bounds by rBound
for(Iterator it = cell.searchIterator(bounds); it.hasNext(); )
{
Geometric nGeom = (Geometric)it.next();
// I have to check if they are the same instance otherwise I check geometry against itself
if (nGeom == geom && (sameInstance))// || nGeom.getParent() == cell))
continue;
if (nGeom instanceof NodeInst)
{
NodeInst ni = (NodeInst)nGeom;
NodeProto np = ni.getProto();
if (NodeInst.isSpecialNode(ni)) continue; // Oct 5;
// ignore nodes that are not primitive
if (np instanceof Cell)
{
// instance found: look inside it for offending geometry
AffineTransform rTransI = ni.rotateIn();
AffineTransform tTransI = ni.translateIn();
rTransI.preConcatenate(tTransI);
subBound.setRect(bounds);
DBMath.transformRect(subBound, rTransI);
CheckInst ci = (CheckInst)checkInsts.get(ni);
int localIndex = cellGlobalIndex * ci.multiplier + ci.localIndex + ci.offset;
AffineTransform subTrans = ni.translateOut(ni.rotateOut());
subTrans.preConcatenate(upTrans); //Sept 15 04
// compute localIndex
if (badBoxInArea(poly, layer, tech, net, geom, trans, globalIndex, subBound, (Cell)np, localIndex,
topCell, topGlobalIndex, subTrans, baseMulti, sameInstance))
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
} else
{
// don't check between technologies
if (np.getTechnology() != tech) continue;
// see if this type of node can interact with this layer
if (!checkLayerWithNode(layer, np)) continue;
// see if the objects directly touch but they are not
// coming from different NodeInst (not from checkCellInstContents
// because they might below to the same cell but in different instances
boolean touch = sameInstance && Geometric.objectsTouch(nGeom, geom);
// prepare to examine every layer in this nodeinst
AffineTransform rTrans = ni.rotateOut();
rTrans.preConcatenate(upTrans);
// get the shape of each nodeinst layer
Poly [] subPolyList = tech.getShapeOfNode(ni, null, null, true, ignoreCenterCuts, null);
convertPseudoLayers(ni, subPolyList);
int tot = subPolyList.length;
for(int i=0; i<tot; i++)
subPolyList[i].transform(rTrans);
/* Step 1 */
boolean multi = baseMulti;
if (!multi) multi = tech.isMultiCutCase(ni);
int multiInt = (multi) ? 1 : 0;
for(int j=0; j<tot; j++)
{
Poly npoly = subPolyList[j];
Layer nLayer = npoly.getLayer();
if (nLayer == null) continue;
//npoly.transform(rTrans);
Rectangle2D nPolyRect = npoly.getBounds2D();
// can't do this because "lxbound..." is local but the poly bounds are global
// On the corners?
if (nPolyRect.getMinX() > rBound.getMaxX() ||
nPolyRect.getMaxX() < rBound.getMinX() ||
nPolyRect.getMinY() > rBound.getMaxY() ||
nPolyRect.getMaxY() < rBound.getMinY()) continue;
// determine network for this polygon
int nNet = getDRCNetNumber(netlist, npoly.getPort(), ni, cellGlobalIndex);
// see whether the two objects are electrically connected
boolean con = false;
if (nNet >= 0 && nNet == net) con = true;
// Checking extension, it could be slow
boolean ret = checkExtensionGateRule(geom, layer, poly, nLayer, npoly, netlist);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
// check if both polys are cut and if the combine area doesn't excess cut sizes
// regardless if they are connected or not
ret = checkCutSizes(np, geom, layer, poly, nGeom, nLayer, npoly, topCell);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
// if they connect electrically and adjoin, don't check
if (con && touch)
{
// Check if there are minimum size defects
boolean maytouch = mayTouch(tech, con, layer, nLayer);
Rectangle2D trueBox1 = poly.getBox();
if (trueBox1 == null) trueBox1 = poly.getBounds2D();
Rectangle2D trueBox2 = npoly.getBox();
if (trueBox2 == null) trueBox1 = npoly.getBounds2D();
ret = checkMinDefects(cell,maytouch, geom, poly, trueBox1, layer,
nGeom, npoly, trueBox2, nLayer, topCell);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
continue;
}
boolean edge = false;
DRCTemplate theRule = getSpacingRule(layer, poly, nLayer, npoly, con, multiInt);
if (theRule == null)
{
theRule = DRC.getEdgeRule(layer, nLayer, techMode);
edge = true;
}
if (theRule != null)
{
// check the distance
ret = checkDist(tech, topCell, topGlobalIndex,
poly, layer, net, geom, trans, globalIndex,
npoly, nLayer, nNet, nGeom, rTrans, cellGlobalIndex,
con, theRule, edge);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
}
}
}
} else
{
ArcInst ai = (ArcInst)nGeom;
ArcProto ap = ai.getProto();
// don't check between technologies
if (ap.getTechnology() != tech) continue;
// see if this type of arc can interact with this layer
if (!checkLayerWithArc(layer, ap)) continue;
// see if the objects directly touch
boolean touch = sameInstance && Geometric.objectsTouch(nGeom, geom);
// see whether the two objects are electrically connected
Network jNet = netlist.getNetwork(ai, 0);
Integer [] netNumbers = (Integer [])networkLists.get(jNet);
int nNet = netNumbers[cellGlobalIndex].intValue();
boolean con = false;
if (net >= 0 && nNet == net) con = true;
// if they connect electrically and adjoin, don't check
// if (con && touch) continue;
// get the shape of each arcinst layer
Poly [] subPolyList = tech.getShapeOfArc(ai);
int tot = subPolyList.length;
for(int i=0; i<tot; i++)
subPolyList[i].transform(upTrans);
cropActiveArc(ai, subPolyList);
boolean multi = baseMulti;
int multiInt = (multi) ? 1 : 0;
for(int j=0; j<tot; j++)
{
Poly nPoly = subPolyList[j];
Layer nLayer = nPoly.getLayer();
if (nLayer == null) continue;
Rectangle2D nPolyRect = nPoly.getBounds2D();
// can't do this because "lxbound..." is local but the poly bounds are global
if (nPolyRect.getMinX() > rBound.getMaxX() ||
nPolyRect.getMaxX() < rBound.getMinX() ||
nPolyRect.getMinY() > rBound.getMaxY() ||
nPolyRect.getMaxY() < rBound.getMinY()) continue;
boolean ret = false;
// if they connect electrically and adjoin, don't check
// We must check if there are minor defects if they overlap regardless if they are connected or not
if (con && touch)
{
// Check if there are minimum size defects
boolean maytouch = mayTouch(tech, con, layer, nLayer);
Rectangle2D trueBox1 = poly.getBox();
if (trueBox1 == null) trueBox1 = poly.getBounds2D();
Rectangle2D trueBox2 = nPoly.getBox();
if (trueBox2 == null) trueBox1 = nPoly.getBounds2D();
ret = checkMinDefects(cell, maytouch, geom, poly, trueBox1, layer,
nGeom, nPoly, trueBox2, nLayer, topCell);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
continue;
}
// see how close they can get
boolean edge = false;
DRCTemplate theRule = getSpacingRule(layer, poly, nLayer, nPoly, con, multiInt);
if (theRule == null)
{
theRule = DRC.getEdgeRule(layer, nLayer, techMode);
edge = true;
}
if (theRule == null) continue;
// check the distance
ret = checkDist(tech, topCell, topGlobalIndex, poly, layer, net, geom, trans, globalIndex,
nPoly, nLayer, nNet, nGeom, upTrans, cellGlobalIndex, con, theRule, edge);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
// Checking extension, it could be slow
ret = checkExtensionGateRule(geom, layer, poly, nLayer, nPoly, netlist);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
}
}
}
return foundError;
}
| private boolean badBoxInArea(Poly poly, Layer layer, Technology tech, int net, Geometric geom, AffineTransform trans,
int globalIndex, Rectangle2D bounds, Cell cell, int cellGlobalIndex,
Cell topCell, int topGlobalIndex, AffineTransform upTrans, boolean baseMulti,
boolean sameInstance)
{
Rectangle2D rBound = new Rectangle2D.Double();
rBound.setRect(bounds);
DBMath.transformRect(rBound, upTrans); // Step 1
Netlist netlist = getCheckProto(cell).netlist;
Rectangle2D subBound = new Rectangle2D.Double(); //Sept 30
boolean foundError = false;
// These nodes won't generate any DRC errors. Most of them are pins
if (geom instanceof NodeInst && NodeInst.isSpecialNode(((NodeInst)geom)))
return false;
// Sept04 changes: bounds by rBound
for(Iterator it = cell.searchIterator(bounds); it.hasNext(); )
{
Geometric nGeom = (Geometric)it.next();
// I have to check if they are the same instance otherwise I check geometry against itself
if (nGeom == geom && (sameInstance))// || nGeom.getParent() == cell))
continue;
if (nGeom instanceof NodeInst)
{
NodeInst ni = (NodeInst)nGeom;
NodeProto np = ni.getProto();
if (NodeInst.isSpecialNode(ni)) continue; // Oct 5;
// ignore nodes that are not primitive
if (np instanceof Cell)
{
// instance found: look inside it for offending geometry
AffineTransform rTransI = ni.rotateIn();
AffineTransform tTransI = ni.translateIn();
rTransI.preConcatenate(tTransI);
subBound.setRect(bounds);
DBMath.transformRect(subBound, rTransI);
CheckInst ci = (CheckInst)checkInsts.get(ni);
int localIndex = cellGlobalIndex * ci.multiplier + ci.localIndex + ci.offset;
AffineTransform subTrans = ni.translateOut(ni.rotateOut());
subTrans.preConcatenate(upTrans); //Sept 15 04
// compute localIndex
if (badBoxInArea(poly, layer, tech, net, geom, trans, globalIndex, subBound, (Cell)np, localIndex,
topCell, topGlobalIndex, subTrans, baseMulti, sameInstance))
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
} else
{
// don't check between technologies
if (np.getTechnology() != tech) continue;
// see if this type of node can interact with this layer
if (!checkLayerWithNode(layer, np)) continue;
// see if the objects directly touch but they are not
// coming from different NodeInst (not from checkCellInstContents
// because they might below to the same cell but in different instances
boolean touch = sameInstance && Geometric.objectsTouch(nGeom, geom);
// prepare to examine every layer in this nodeinst
AffineTransform rTrans = ni.rotateOut();
rTrans.preConcatenate(upTrans);
// get the shape of each nodeinst layer
Poly [] subPolyList = tech.getShapeOfNode(ni, null, null, true, ignoreCenterCuts, null);
convertPseudoLayers(ni, subPolyList);
int tot = subPolyList.length;
for(int i=0; i<tot; i++)
subPolyList[i].transform(rTrans);
/* Step 1 */
boolean multi = baseMulti;
if (!multi) multi = tech.isMultiCutCase(ni);
int multiInt = (multi) ? 1 : 0;
for(int j=0; j<tot; j++)
{
Poly npoly = subPolyList[j];
Layer nLayer = npoly.getLayer();
if (nLayer == null) continue;
//npoly.transform(rTrans);
Rectangle2D nPolyRect = npoly.getBounds2D();
// can't do this because "lxbound..." is local but the poly bounds are global
// On the corners?
// if (nPolyRect.getMinX() > rBound.getMaxX() ||
// nPolyRect.getMaxX() < rBound.getMinX() ||
// nPolyRect.getMinY() > rBound.getMaxY() ||
// nPolyRect.getMaxY() < rBound.getMinY())
// continue;
if (DBMath.isGreaterThan(nPolyRect.getMinX(), rBound.getMaxX()) ||
DBMath.isGreaterThan(rBound.getMinX(), nPolyRect.getMaxX()) ||
DBMath.isGreaterThan(nPolyRect.getMinY(), rBound.getMaxY()) ||
DBMath.isGreaterThan(rBound.getMinY(), nPolyRect.getMaxY()))
continue;
// determine network for this polygon
int nNet = getDRCNetNumber(netlist, npoly.getPort(), ni, cellGlobalIndex);
// see whether the two objects are electrically connected
boolean con = false;
if (nNet >= 0 && nNet == net) con = true;
// Checking extension, it could be slow
boolean ret = checkExtensionGateRule(geom, layer, poly, nLayer, npoly, netlist);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
// check if both polys are cut and if the combine area doesn't excess cut sizes
// regardless if they are connected or not
ret = checkCutSizes(np, geom, layer, poly, nGeom, nLayer, npoly, topCell);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
// if they connect electrically and adjoin, don't check
if (con && touch)
{
// Check if there are minimum size defects
boolean maytouch = mayTouch(tech, con, layer, nLayer);
Rectangle2D trueBox1 = poly.getBox();
if (trueBox1 == null) trueBox1 = poly.getBounds2D();
Rectangle2D trueBox2 = npoly.getBox();
if (trueBox2 == null) trueBox1 = npoly.getBounds2D();
ret = checkMinDefects(cell,maytouch, geom, poly, trueBox1, layer,
nGeom, npoly, trueBox2, nLayer, topCell);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
continue;
}
boolean edge = false;
DRCTemplate theRule = getSpacingRule(layer, poly, nLayer, npoly, con, multiInt);
if (theRule == null)
{
theRule = DRC.getEdgeRule(layer, nLayer, techMode);
edge = true;
}
if (theRule != null)
{
// check the distance
ret = checkDist(tech, topCell, topGlobalIndex,
poly, layer, net, geom, trans, globalIndex,
npoly, nLayer, nNet, nGeom, rTrans, cellGlobalIndex,
con, theRule, edge);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
}
}
}
} else
{
ArcInst ai = (ArcInst)nGeom;
ArcProto ap = ai.getProto();
// don't check between technologies
if (ap.getTechnology() != tech) continue;
// see if this type of arc can interact with this layer
if (!checkLayerWithArc(layer, ap)) continue;
// see if the objects directly touch
boolean touch = sameInstance && Geometric.objectsTouch(nGeom, geom);
// see whether the two objects are electrically connected
Network jNet = netlist.getNetwork(ai, 0);
Integer [] netNumbers = (Integer [])networkLists.get(jNet);
int nNet = netNumbers[cellGlobalIndex].intValue();
boolean con = false;
if (net >= 0 && nNet == net) con = true;
// if they connect electrically and adjoin, don't check
// if (con && touch) continue;
// get the shape of each arcinst layer
Poly [] subPolyList = tech.getShapeOfArc(ai);
int tot = subPolyList.length;
for(int i=0; i<tot; i++)
subPolyList[i].transform(upTrans);
cropActiveArc(ai, subPolyList);
boolean multi = baseMulti;
int multiInt = (multi) ? 1 : 0;
for(int j=0; j<tot; j++)
{
Poly nPoly = subPolyList[j];
Layer nLayer = nPoly.getLayer();
if (nLayer == null) continue;
Rectangle2D nPolyRect = nPoly.getBounds2D();
// can't do this because "lxbound..." is local but the poly bounds are global
if (nPolyRect.getMinX() > rBound.getMaxX() ||
nPolyRect.getMaxX() < rBound.getMinX() ||
nPolyRect.getMinY() > rBound.getMaxY() ||
nPolyRect.getMaxY() < rBound.getMinY()) continue;
boolean ret = false;
// if they connect electrically and adjoin, don't check
// We must check if there are minor defects if they overlap regardless if they are connected or not
if (con && touch)
{
// Check if there are minimum size defects
boolean maytouch = mayTouch(tech, con, layer, nLayer);
Rectangle2D trueBox1 = poly.getBox();
if (trueBox1 == null) trueBox1 = poly.getBounds2D();
Rectangle2D trueBox2 = nPoly.getBox();
if (trueBox2 == null) trueBox1 = nPoly.getBounds2D();
ret = checkMinDefects(cell, maytouch, geom, poly, trueBox1, layer,
nGeom, nPoly, trueBox2, nLayer, topCell);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
continue;
}
// see how close they can get
boolean edge = false;
DRCTemplate theRule = getSpacingRule(layer, poly, nLayer, nPoly, con, multiInt);
if (theRule == null)
{
theRule = DRC.getEdgeRule(layer, nLayer, techMode);
edge = true;
}
if (theRule == null) continue;
// check the distance
ret = checkDist(tech, topCell, topGlobalIndex, poly, layer, net, geom, trans, globalIndex,
nPoly, nLayer, nNet, nGeom, upTrans, cellGlobalIndex, con, theRule, edge);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
// Checking extension, it could be slow
ret = checkExtensionGateRule(geom, layer, poly, nLayer, nPoly, netlist);
if (ret)
{
foundError = true;
if (errorTypeSearch != DRC.ERROR_CHECK_EXHAUSTIVE) return true;
}
}
}
}
return foundError;
}
|
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/FileContentsHolder.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/FileContentsHolder.java
index f2ccc3b5d..b53d8bac7 100755
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/FileContentsHolder.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/FileContentsHolder.java
@@ -1,64 +1,65 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2010 Oliver Burn
//
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks;
import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.FileContents;
/**
* Holds the current file contents for global access when configured
* as a TreeWalker sub-module. For example,
* a filter can access the current file contents through this module.
* @author Mike McMahon
* @author Rick Giles
*/
public class FileContentsHolder
extends Check
{
/** The current file contents. */
private static final ThreadLocal<FileContents> FILE_CONTENTS =
new ThreadLocal<FileContents>();
/** @return the current file contents. */
public static FileContents getContents()
{
return FILE_CONTENTS.get();
}
@Override
public int[] getDefaultTokens()
{
return new int[0];
}
@Override
public void beginTree(DetailAST aRootAST)
{
FILE_CONTENTS.set(getFileContents());
}
@Override
- public void finishTree(DetailAST aRootAST)
+ public void destroy()
{
- // This seems like the right thing to do, but is called before
- // the messages are passed to the filters.
- //sFileContents.set(null);
+ // This needs to be called in destroy, rather than finishTree()
+ // as finishTree() is called before the messages are passed to the
+ // filters. Without calling remove, there is a memory leak.
+ FILE_CONTENTS.remove();
}
}
| false | true | public void finishTree(DetailAST aRootAST)
{
// This seems like the right thing to do, but is called before
// the messages are passed to the filters.
//sFileContents.set(null);
}
| public void destroy()
{
// This needs to be called in destroy, rather than finishTree()
// as finishTree() is called before the messages are passed to the
// filters. Without calling remove, there is a memory leak.
FILE_CONTENTS.remove();
}
|
diff --git a/software/newtermform/src/java/gov/nih/nci/evs/browser/bean/SuggestionRequest.java b/software/newtermform/src/java/gov/nih/nci/evs/browser/bean/SuggestionRequest.java
index f2ada15..aab345f 100644
--- a/software/newtermform/src/java/gov/nih/nci/evs/browser/bean/SuggestionRequest.java
+++ b/software/newtermform/src/java/gov/nih/nci/evs/browser/bean/SuggestionRequest.java
@@ -1,99 +1,99 @@
package gov.nih.nci.evs.browser.bean;
import gov.nih.nci.evs.browser.properties.*;
import gov.nih.nci.evs.browser.utils.*;
import javax.servlet.http.*;
public class SuggestionRequest extends NewTermRequest {
// List of session attribute name(s):
private static final String EMAIL = "email";
private static final String OTHER = "other";
private static final String VOCABULARY = "vocabulary";
private static final String TERM = "term";
private static final String SYNONYMS = "synonyms";
private static final String NEAREST_CODE = "nearestCode";
private static final String DEFINITION = "definition";
private static final String REASON = "reason";
public SuggestionRequest(HttpServletRequest request) {
super(request, VOCABULARY);
setParameters(new String[] { EMAIL, OTHER, VOCABULARY,
TERM, SYNONYMS, NEAREST_CODE, DEFINITION, REASON });
}
public String submitForm() {
_request.getSession().setAttribute(WARNINGS, null);
_request.getSession().setAttribute(MESSAGE, null);
updateSessionAttributes();
String warnings = validate();
if (warnings.length() > 0) {
_request.getSession().setAttribute(WARNINGS, warnings);
return WARNING_STATE;
}
AppProperties appProperties = AppProperties.getInstance();
String vocabulary = _parametersHashMap.get(VOCABULARY);
String mailServer = appProperties.getMailSmtpServer();
String from = _parametersHashMap.get(EMAIL);
String[] recipients = appProperties.getVocabularyEmails(vocabulary);
String subject = getSubject();
String emailMsg = getEmailMesage();
try {
if (_isSendEmail)
MailUtils.postMail(mailServer, from, recipients, subject, emailMsg);
} catch (Exception e) {
_request.getSession().setAttribute(WARNINGS,
e.getLocalizedMessage());
e.printStackTrace();
return WARNING_STATE;
}
clearSessionAttributes(new String[] { /* EMAIL, OTHER, VOCABULARY, */
TERM, SYNONYMS, NEAREST_CODE, DEFINITION, REASON });
String msg = "FYI: The following request has been sent:\n";
msg += " * " + getSubject();
_request.getSession().setAttribute(MESSAGE, msg);
printSendEmailWarning();
- return SUCCESSFUL_STATE;
+ return "message"; //DYEE: SUCCESSFUL_STATE;
}
private String validate() {
StringBuffer buffer = new StringBuffer();
String email = _parametersHashMap.get(EMAIL);
validate(buffer, MailUtils.isValidEmailAddress(email),
"* Please enter a valid email address.");
String vocabulary = _parametersHashMap.get(VOCABULARY);
validate(buffer, vocabulary != null && vocabulary.length() > 0,
"* Please select a vocabulary.");
String term = _parametersHashMap.get(TERM);
validate(buffer, term != null && term.length() > 0,
"* Please enter a term.");
return buffer.toString();
}
private String getSubject() {
String term = _parametersHashMap.get(TERM);
String value = "Term Suggestion for";
if (term.length() > 0)
value += ": " + term;
return value;
}
private String getEmailMesage() {
StringBuffer buffer = new StringBuffer();
buffer.append(getSubject() + "\n\n");
itemizeParameters(buffer, "Contact information:",
new String[] { EMAIL, OTHER });
itemizeParameters(buffer, "Term Information:",
new String[] { VOCABULARY, TERM, SYNONYMS, NEAREST_CODE, DEFINITION });
itemizeParameters(buffer, "Additional information:",
new String[] { REASON });
return buffer.toString();
}
}
| true | true | public String submitForm() {
_request.getSession().setAttribute(WARNINGS, null);
_request.getSession().setAttribute(MESSAGE, null);
updateSessionAttributes();
String warnings = validate();
if (warnings.length() > 0) {
_request.getSession().setAttribute(WARNINGS, warnings);
return WARNING_STATE;
}
AppProperties appProperties = AppProperties.getInstance();
String vocabulary = _parametersHashMap.get(VOCABULARY);
String mailServer = appProperties.getMailSmtpServer();
String from = _parametersHashMap.get(EMAIL);
String[] recipients = appProperties.getVocabularyEmails(vocabulary);
String subject = getSubject();
String emailMsg = getEmailMesage();
try {
if (_isSendEmail)
MailUtils.postMail(mailServer, from, recipients, subject, emailMsg);
} catch (Exception e) {
_request.getSession().setAttribute(WARNINGS,
e.getLocalizedMessage());
e.printStackTrace();
return WARNING_STATE;
}
clearSessionAttributes(new String[] { /* EMAIL, OTHER, VOCABULARY, */
TERM, SYNONYMS, NEAREST_CODE, DEFINITION, REASON });
String msg = "FYI: The following request has been sent:\n";
msg += " * " + getSubject();
_request.getSession().setAttribute(MESSAGE, msg);
printSendEmailWarning();
return SUCCESSFUL_STATE;
}
| public String submitForm() {
_request.getSession().setAttribute(WARNINGS, null);
_request.getSession().setAttribute(MESSAGE, null);
updateSessionAttributes();
String warnings = validate();
if (warnings.length() > 0) {
_request.getSession().setAttribute(WARNINGS, warnings);
return WARNING_STATE;
}
AppProperties appProperties = AppProperties.getInstance();
String vocabulary = _parametersHashMap.get(VOCABULARY);
String mailServer = appProperties.getMailSmtpServer();
String from = _parametersHashMap.get(EMAIL);
String[] recipients = appProperties.getVocabularyEmails(vocabulary);
String subject = getSubject();
String emailMsg = getEmailMesage();
try {
if (_isSendEmail)
MailUtils.postMail(mailServer, from, recipients, subject, emailMsg);
} catch (Exception e) {
_request.getSession().setAttribute(WARNINGS,
e.getLocalizedMessage());
e.printStackTrace();
return WARNING_STATE;
}
clearSessionAttributes(new String[] { /* EMAIL, OTHER, VOCABULARY, */
TERM, SYNONYMS, NEAREST_CODE, DEFINITION, REASON });
String msg = "FYI: The following request has been sent:\n";
msg += " * " + getSubject();
_request.getSession().setAttribute(MESSAGE, msg);
printSendEmailWarning();
return "message"; //DYEE: SUCCESSFUL_STATE;
}
|
diff --git a/cobertura/src/net/sourceforge/cobertura/reporting/ComplexityCalculator.java b/cobertura/src/net/sourceforge/cobertura/reporting/ComplexityCalculator.java
index 252c5e9..01e07de 100644
--- a/cobertura/src/net/sourceforge/cobertura/reporting/ComplexityCalculator.java
+++ b/cobertura/src/net/sourceforge/cobertura/reporting/ComplexityCalculator.java
@@ -1,268 +1,272 @@
/*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2005 Mark Doliner
* Copyright (C) 2005 Jeremy Thomerson
* Copyright (C) 2005 Grzegorz Lukasik
* Copyright (C) 2008 Tri Bao Ho
* Copyright (C) 2009 John Lewis
*
* Cobertura 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.
*
* Cobertura 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 Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.reporting;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import net.sourceforge.cobertura.coveragedata.ClassData;
import net.sourceforge.cobertura.coveragedata.PackageData;
import net.sourceforge.cobertura.coveragedata.ProjectData;
import net.sourceforge.cobertura.coveragedata.SourceFileData;
import net.sourceforge.cobertura.javancss.Javancss;
import net.sourceforge.cobertura.javancss.JavancssConstants;
import net.sourceforge.cobertura.util.FileFinder;
import net.sourceforge.cobertura.util.Source;
import org.apache.log4j.Logger;
/**
* Allows complexity computing for source files, packages and a whole project. Average
* McCabe's number for methods contained in the specified entity is returned. This class
* depends on FileFinder which is used to map source file names to existing files.
*
* <p>One instance of this class should be used for the same set of source files - an
* object of this class can cache computed results.</p>
*
* @author Grzegorz Lukasik
*/
public class ComplexityCalculator {
private static final Logger logger = Logger.getLogger(ComplexityCalculator.class);
public static final Complexity ZERO_COMPLEXITY = new Complexity();
// Finder used to map source file names to existing files
private final FileFinder finder;
// Contains pairs (String sourceFileName, Complexity complexity)
private Map sourceFileCNNCache = new HashMap();
// Contains pairs (String packageName, Complexity complexity)
private Map packageCNNCache = new HashMap();
/**
* Creates new calculator. Passed {@link FileFinder} will be used to
* map source file names to existing files when needed.
*
* @param finder {@link FileFinder} that allows to find source files
* @throws NullPointerException if finder is null
*/
public ComplexityCalculator( FileFinder finder) {
if( finder==null)
throw new NullPointerException();
this.finder = finder;
}
/**
* Calculates the code complexity number for an input stream.
* "CCN" stands for "code complexity number." This is
* sometimes referred to as McCabe's number. This method
* calculates the average cyclomatic code complexity of all
* methods of all classes in a given directory.
*
* @param file The input stream for which you want to calculate
* the complexity
* @return average complexity for the specified input stream
*/
private Complexity getAccumlatedCCNForSource(String sourceFileName, Source source) {
if (source == null)
{
return ZERO_COMPLEXITY;
}
+ if (!sourceFileName.endsWith(".java"))
+ {
+ return ZERO_COMPLEXITY;
+ }
Javancss javancss = new Javancss(source.getInputStream());
if (javancss.getLastErrorMessage() != null)
{
//there is an error while parsing the java file. log it
logger.warn("JavaNCSS got an error while parsing the java " + source.getOriginDesc() + "\n"
+ javancss.getLastErrorMessage());
}
Vector methodMetrics = javancss.getFunctionMetrics();
int classCcn = 0;
for( Enumeration method = methodMetrics.elements(); method.hasMoreElements();)
{
Vector singleMethodMetrics = (Vector)method.nextElement();
classCcn += ((Integer)singleMethodMetrics.elementAt(JavancssConstants.FCT_CCN)).intValue();
}
return new Complexity( classCcn, methodMetrics.size());
}
/**
* Calculates the code complexity number for single source file.
* "CCN" stands for "code complexity number." This is
* sometimes referred to as McCabe's number. This method
* calculates the average cyclomatic code complexity of all
* methods of all classes in a given directory.
* @param sourceFileName
*
* @param file The source file for which you want to calculate
* the complexity
* @return average complexity for the specified source file
* @throws IOException
*/
private Complexity getAccumlatedCCNForSingleFile(String sourceFileName) throws IOException {
Source source = finder.getSource(sourceFileName);
try
{
return getAccumlatedCCNForSource(sourceFileName, source);
}
finally
{
if (source != null)
{
source.close();
}
}
}
/**
* Computes CCN for all sources contained in the project.
* CCN for whole project is an average CCN for source files.
* All source files for which CCN cannot be computed are ignored.
*
* @param projectData project to compute CCN for
* @throws NullPointerException if projectData is null
* @return CCN for project or 0 if no source files were found
*/
public double getCCNForProject( ProjectData projectData) {
// Sum complexity for all packages
Complexity act = new Complexity();
for( Iterator it = projectData.getPackages().iterator(); it.hasNext();) {
PackageData packageData = (PackageData)it.next();
act.add( getCCNForPackageInternal( packageData));
}
// Return average CCN for source files
return act.averageCCN();
}
/**
* Computes CCN for all sources contained in the specified package.
* All source files that cannot be mapped to existing files are ignored.
*
* @param packageData package to compute CCN for
* @throws NullPointerException if <code>packageData</code> is <code>null</code>
* @return CCN for the specified package or 0 if no source files were found
*/
public double getCCNForPackage(PackageData packageData) {
return getCCNForPackageInternal(packageData).averageCCN();
}
private Complexity getCCNForPackageInternal(PackageData packageData) {
// Return CCN if computed earlier
Complexity cachedCCN = (Complexity) packageCNNCache.get( packageData.getName());
if( cachedCCN!=null) {
return cachedCCN;
}
// Compute CCN for all source files inside package
Complexity act = new Complexity();
for( Iterator it = packageData.getSourceFiles().iterator(); it.hasNext();) {
SourceFileData sourceData = (SourceFileData)it.next();
act.add( getCCNForSourceFileNameInternal( sourceData.getName()));
}
// Cache result and return it
packageCNNCache.put( packageData.getName(), act);
return act;
}
/**
* Computes CCN for single source file.
*
* @param sourceFile source file to compute CCN for
* @throws NullPointerException if <code>sourceFile</code> is <code>null</code>
* @return CCN for the specified source file, 0 if cannot map <code>sourceFile</code> to existing file
*/
public double getCCNForSourceFile(SourceFileData sourceFile) {
return getCCNForSourceFileNameInternal( sourceFile.getName()).averageCCN();
}
private Complexity getCCNForSourceFileNameInternal(String sourceFileName) {
// Return CCN if computed earlier
Complexity cachedCCN = (Complexity) sourceFileCNNCache.get( sourceFileName);
if( cachedCCN!=null) {
return cachedCCN;
}
// Compute CCN and cache it for further use
Complexity result = ZERO_COMPLEXITY;
try {
result = getAccumlatedCCNForSingleFile( sourceFileName );
} catch( IOException ex) {
logger.info( "Cannot find source file during CCN computation, source=["+sourceFileName+"]");
}
sourceFileCNNCache.put( sourceFileName, result);
return result;
}
/**
* Computes CCN for source file the specified class belongs to.
*
* @param classData package to compute CCN for
* @return CCN for source file the specified class belongs to
* @throws NullPointerException if <code>classData</code> is <code>null</code>
*/
public double getCCNForClass(ClassData classData) {
return getCCNForSourceFileNameInternal( classData.getSourceFileName()).averageCCN();
}
/**
* Represents complexity of source file, package or project. Stores the number of
* methods inside entity and accumlated complexity for these methods.
*/
private static class Complexity {
private double accumlatedCCN;
private int methodsNum;
public Complexity(double accumlatedCCN, int methodsNum) {
this.accumlatedCCN = accumlatedCCN;
this.methodsNum = methodsNum;
}
public Complexity() {
this(0,0);
}
public double averageCCN() {
if( methodsNum==0) {
return 0;
}
return accumlatedCCN/methodsNum;
}
public void add( Complexity second) {
accumlatedCCN += second.accumlatedCCN;
methodsNum += second.methodsNum;
}
}
}
| true | true | private Complexity getAccumlatedCCNForSource(String sourceFileName, Source source) {
if (source == null)
{
return ZERO_COMPLEXITY;
}
Javancss javancss = new Javancss(source.getInputStream());
if (javancss.getLastErrorMessage() != null)
{
//there is an error while parsing the java file. log it
logger.warn("JavaNCSS got an error while parsing the java " + source.getOriginDesc() + "\n"
+ javancss.getLastErrorMessage());
}
Vector methodMetrics = javancss.getFunctionMetrics();
int classCcn = 0;
for( Enumeration method = methodMetrics.elements(); method.hasMoreElements();)
{
Vector singleMethodMetrics = (Vector)method.nextElement();
classCcn += ((Integer)singleMethodMetrics.elementAt(JavancssConstants.FCT_CCN)).intValue();
}
return new Complexity( classCcn, methodMetrics.size());
}
| private Complexity getAccumlatedCCNForSource(String sourceFileName, Source source) {
if (source == null)
{
return ZERO_COMPLEXITY;
}
if (!sourceFileName.endsWith(".java"))
{
return ZERO_COMPLEXITY;
}
Javancss javancss = new Javancss(source.getInputStream());
if (javancss.getLastErrorMessage() != null)
{
//there is an error while parsing the java file. log it
logger.warn("JavaNCSS got an error while parsing the java " + source.getOriginDesc() + "\n"
+ javancss.getLastErrorMessage());
}
Vector methodMetrics = javancss.getFunctionMetrics();
int classCcn = 0;
for( Enumeration method = methodMetrics.elements(); method.hasMoreElements();)
{
Vector singleMethodMetrics = (Vector)method.nextElement();
classCcn += ((Integer)singleMethodMetrics.elementAt(JavancssConstants.FCT_CCN)).intValue();
}
return new Complexity( classCcn, methodMetrics.size());
}
|
diff --git a/MODSRC/vazkii/tinkerer/common/research/ModResearch.java b/MODSRC/vazkii/tinkerer/common/research/ModResearch.java
index e5eb7e5a..c981819e 100644
--- a/MODSRC/vazkii/tinkerer/common/research/ModResearch.java
+++ b/MODSRC/vazkii/tinkerer/common/research/ModResearch.java
@@ -1,148 +1,148 @@
/**
* This class was created by <Vazkii>. It's distributed as
* part of the ThaumicTinkerer Mod.
*
* ThaumicTinkerer is Open Source and distributed under a
* Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License
* (http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_GB)
*
* ThaumicTinkerer is a Derivative Work on Thaumcraft 4.
* Thaumcraft 4 (c) Azanor 2012
* (http://www.minecraftforum.net/topic/1585216-)
*
* File Created @ [4 Sep 2013, 17:02:29 (GMT)]
*/
package vazkii.tinkerer.common.research;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.util.ResourceLocation;
import thaumcraft.api.aspects.Aspect;
import thaumcraft.api.aspects.AspectList;
import thaumcraft.api.crafting.CrucibleRecipe;
import thaumcraft.api.crafting.IArcaneRecipe;
import thaumcraft.api.crafting.InfusionRecipe;
import thaumcraft.api.research.ResearchCategories;
import thaumcraft.api.research.ResearchItem;
import thaumcraft.api.research.ResearchPage;
import thaumcraft.common.config.ConfigBlocks;
import thaumcraft.common.config.ConfigResearch;
import vazkii.tinkerer.client.lib.LibResources;
import vazkii.tinkerer.common.block.ModBlocks;
import vazkii.tinkerer.common.item.ModItems;
import vazkii.tinkerer.common.lib.LibResearch;
import cpw.mods.fml.common.Loader;
public final class ModResearch {
public static void initResearch() {
registerResearchPages();
ResearchItem research;
research = new TTResearchItem(LibResearch.KEY_DARK_QUARTZ, LibResearch.CATEGORY_ARTIFICE, new AspectList(), -2, -1, 0, new ItemStack(ModItems.darkQuartz)).setStub().setAutoUnlock().setRound().registerResearchItem();
research.setPages(new ResearchPage("0"), recipePage(LibResearch.KEY_DARK_QUARTZ + 0), recipePage(LibResearch.KEY_DARK_QUARTZ + 1), recipePage(LibResearch.KEY_DARK_QUARTZ + 2), recipePage(LibResearch.KEY_DARK_QUARTZ + 3), recipePage(LibResearch.KEY_DARK_QUARTZ + 4), recipePage(LibResearch.KEY_DARK_QUARTZ + 5));
research = new TTResearchItem(LibResearch.KEY_INTERFACE, LibResearch.CATEGORY_ARTIFICE, new AspectList().add(Aspect.ENTROPY, 4).add(Aspect.ORDER, 4), 3, -3, 1, new ItemStack(ModBlocks.interfase)).setParents("ARCANESTONE").registerResearchItem();
research.setPages(new ResearchPage("0"), arcaneRecipePage(LibResearch.KEY_INTERFACE), new ResearchPage("1"), arcaneRecipePage(LibResearch.KEY_CONNECTOR));
research = new TTResearchItem(LibResearch.KEY_GASEOUS_LIGHT, LibResearch.CATEGORY_ALCHEMY, new AspectList().add(Aspect.LIGHT, 2).add(Aspect.AIR, 1), 5, -2, 2, new ItemStack(ModItems.gaseousLight)).setParents("NITOR").registerResearchItem();
research.setPages(new ResearchPage("0"), cruciblePage(LibResearch.KEY_GASEOUS_LIGHT));
research = new TTResearchItem(LibResearch.KEY_GASEOUS_SHADOW, LibResearch.CATEGORY_ALCHEMY, new AspectList().add(Aspect.DARKNESS, 2).add(Aspect.AIR, 1).add(Aspect.MOTION, 4), 5, 0, 2, new ItemStack(ModItems.gaseousShadow)).setParents("ALUMENTUM").setParentsHidden(LibResearch.KEY_GASEOUS_LIGHT).setSiblings(LibResearch.KEY_GAS_REMOVER).registerResearchItem();
research.setPages(new ResearchPage("0"), cruciblePage(LibResearch.KEY_GASEOUS_SHADOW));
research = new TTResearchItem(LibResearch.KEY_GAS_REMOVER, LibResearch.CATEGORY_ALCHEMY, new AspectList(), 6, 0, 0, new ItemStack(ModItems.gasRemover)).setRound().registerResearchItem();
research.setPages(new ResearchPage("0"), arcaneRecipePage(LibResearch.KEY_GAS_REMOVER));
research = new TTResearchItem(LibResearch.KEY_SPELL_CLOTH, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.MAGIC, 2).add(Aspect.CLOTH, 1), 0, 0, 2, new ItemStack(ModItems.spellCloth)).setParentsHidden("ENCHFABRIC").registerResearchItem();
research.setPages(new ResearchPage("0"), cruciblePage(LibResearch.KEY_SPELL_CLOTH));
research = new TTResearchItem(LibResearch.KEY_ANIMATION_TABLET, LibResearch.CATEGORY_GOLEMANCY, new AspectList().add(Aspect.MECHANISM, 2).add(Aspect.METAL, 1).add(Aspect.MOTION, 1).add(Aspect.ENERGY, 1), -3, 1, 4, new ItemStack(ModBlocks.animationTablet)).setParents("COREGATHER").setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"), arcaneRecipePage(LibResearch.KEY_ANIMATION_TABLET));
research = new TTResearchItem(LibResearch.KEY_FOCUS_FLIGHT, LibResearch.CATEGORY_THAUMATURGY, new AspectList().add(Aspect.MOTION, 1).add(Aspect.MAGIC, 1).add(Aspect.AIR, 2), 4, -6, 2, new ItemStack(ModItems.focusFlight)).setParents("FOCUSSHOCK").setParentsHidden("ELEMENTALSWORD").setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), infusionPage(LibResearch.KEY_FOCUS_FLIGHT));
research = new TTResearchItem(LibResearch.KEY_FOCUS_DISLOCATION, LibResearch.CATEGORY_THAUMATURGY, new AspectList().add(Aspect.ELDRITCH, 2).add(Aspect.MAGIC, 1).add(Aspect.EXCHANGE, 1), 6, -2, 2, new ItemStack(ModItems.focusDislocation)).setParents("FOCUSTRADE").setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), new ResearchPage("1"), infusionPage(LibResearch.KEY_FOCUS_DISLOCATION));
research = new TTResearchItem(LibResearch.KEY_CLEANSING_TALISMAN, LibResearch.CATEGORY_ARTIFICE, new AspectList().add(Aspect.HEAL, 2).add(Aspect.ORDER, 1).add(Aspect.POISON, 1), 2, 4, 3, new ItemStack(ModItems.cleansingTalisman)).setParents("ENCHFABRIC").setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"), infusionPage(LibResearch.KEY_CLEANSING_TALISMAN));
research = new TTResearchItem(LibResearch.KEY_BRIGHT_NITOR, LibResearch.CATEGORY_ALCHEMY, new AspectList().add(Aspect.LIGHT, 2).add(Aspect.FIRE, 1).add(Aspect.ENERGY, 1).add(Aspect.AIR, 1), 3, -3, 3, new ItemStack(ModItems.brightNitor)).setParents(LibResearch.KEY_GASEOUS_LIGHT).setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), cruciblePage(LibResearch.KEY_BRIGHT_NITOR));
research = new TTResearchItem(LibResearch.KEY_FOCUS_TELEKINESIS, LibResearch.CATEGORY_THAUMATURGY, new AspectList().add(Aspect.ELDRITCH, 2).add(Aspect.MAGIC, 1).add(Aspect.MOTION, 1), 6, 0, 2, new ItemStack(ModItems.focusTelekinesis)).setParents(LibResearch.KEY_FOCUS_DISLOCATION).setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), infusionPage(LibResearch.KEY_FOCUS_TELEKINESIS));
research = new TTResearchItem(LibResearch.KEY_MAGNETS, LibResearch.CATEGORY_ARTIFICE, new AspectList().add(Aspect.MECHANISM, 2).add(Aspect.MOTION, 1).add(Aspect.SENSES, 1), -5, -3, 3, new ItemStack(ModBlocks.magnet)).setParentsHidden(LibResearch.KEY_FOCUS_TELEKINESIS).setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), new ResearchPage("1"), arcaneRecipePage(LibResearch.KEY_MAGNET), arcaneRecipePage(LibResearch.KEY_MOB_MAGNET), cruciblePage(LibResearch.KEY_MAGNETS));
research = new TTResearchItem(LibResearch.KEY_ENCHANTER, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.MAGIC, 2).add(Aspect.AURA, 1).add(Aspect.ELDRITCH, 1).add(Aspect.DARKNESS, 1).add(Aspect.MIND, 1), 2, -2, 5, new ItemStack(ModBlocks.enchanter)).setParents(LibResearch.KEY_SPELL_CLOTH).setParentsHidden("RESEARCHER2").setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), new ResearchPage("1"), new ResearchPage("2"), infusionPage(LibResearch.KEY_ENCHANTER));
research = new TTResearchItem(LibResearch.KEY_XP_TALISMAN, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.GREED, 1).add(Aspect.MAGIC, 1).add(Aspect.MAN, 1), -2, 2, 2, new ItemStack(ModItems.xpTalisman, 1, 1)).setParents("JARBRAIN").setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), infusionPage(LibResearch.KEY_XP_TALISMAN));
- research = new TTResearchItem(LibResearch.KEY_FUNNEL, LibResearch.CATEGORY_ALCHEMY, new AspectList().add(Aspect.TOOL, 1).add(Aspect.TRAVEL, 2), 8, -2, 1, new ItemStack(ModBlocks.funnel)).setParents("DISTILESSENTIA").setConcealed().registerResearchItem();
+ research = new TTResearchItem(LibResearch.KEY_FUNNEL, LibResearch.CATEGORY_ALCHEMY, new AspectList().add(Aspect.TOOL, 1).add(Aspect.TRAVEL, 2), 7, -2, 1, new ItemStack(ModBlocks.funnel)).setParents("DISTILESSENTIA").setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), arcaneRecipePage(LibResearch.KEY_FUNNEL));
research = new TTResearchItem(LibResearch.KEY_ENCHANT_ASCENT_BOOST, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.AIR, 1).add(Aspect.MOTION, 1).add(Aspect.MAGIC, 2), -2, -3, 2, new ResourceLocation(LibResources.ENCHANT_ASCENT_BOOST)).setParents(LibResearch.KEY_ENCHANTER).setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"));
research = new TTResearchItem(LibResearch.KEY_ENCHANT_SLOW_FALL, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.AIR, 1).add(Aspect.MOTION, 1).add(Aspect.MAGIC, 2), -1, -5, 2, new ResourceLocation(LibResources.ENCHANT_SLOW_FALL)).setParents(LibResearch.KEY_ENCHANTER).setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"));
research = new TTResearchItem(LibResearch.KEY_ENCHANT_AUTO_SMELT, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.FIRE, 1).add(Aspect.ENTROPY, 1).add(Aspect.MAGIC, 2), 1, -6, 2, new ResourceLocation(LibResources.ENCHANT_AUTO_SMELT)).setParents(LibResearch.KEY_ENCHANTER).setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"));
research = new TTResearchItem(LibResearch.KEY_ENCHANT_DESINTEGRATE, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.ENTROPY, 1).add(Aspect.VOID, 1).add(Aspect.MAGIC, 2), 3, -6, 2, new ResourceLocation(LibResources.ENCHANT_DESINTEGRATE)).setParents(LibResearch.KEY_ENCHANTER).setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"));
research = new TTResearchItem(LibResearch.KEY_ENCHANT_QUICK_DRAW, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.SENSES, 1).add(Aspect.WEAPON, 1).add(Aspect.MAGIC, 2), 5, -5, 2, new ResourceLocation(LibResources.ENCHANT_QUICK_DRAW)).setParents(LibResearch.KEY_ENCHANTER).setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"));
research = new TTResearchItem(LibResearch.KEY_ENCHANT_VAMPIRISM, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.HUNGER, 1).add(Aspect.WEAPON, 1).add(Aspect.MAGIC, 2), 6, -3, 2, new ResourceLocation(LibResources.ENCHANT_VAMPIRISM)).setParents(LibResearch.KEY_ENCHANTER).setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"));
research = new TTResearchItem(LibResearch.KEY_FOCUS_SMELT, LibResearch.CATEGORY_THAUMATURGY, new AspectList().add(Aspect.FIRE, 2).add(Aspect.ENERGY, 1).add(Aspect.MAGIC, 1), -1, -5, 2, new ItemStack(ModItems.focusSmelt)).setParents("FOCUSEXCAVATION").setParentsHidden("INFERNALFURNACE").setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), arcaneRecipePage(LibResearch.KEY_FOCUS_SMELT));
// Peripheral documentation research
if(Loader.isModLoaded("ComputerCraft")) {
research = new TTResearchItem(LibResearch.KEY_PERIPHERALS, LibResearch.CATEGORY_BASICS, new AspectList(), 0, 2, 0, new ItemStack(Item.redstone)).setAutoUnlock().setRound().registerResearchItem();
research.setPages(new ResearchPage("0"));
}
// Move the Brain in a jar research
research = ResearchCategories.getResearch("JARBRAIN");
ResearchCategories.researchCategories.get(LibResearch.CATEGORY_ARTIFICE).research.remove("JARBRAIN");
research = new ResearchItem("JARBRAIN", LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.SENSES, 1).add(Aspect.MIND, 2).add(Aspect.UNDEAD, 2), -3, 0, 2, new ItemStack(ConfigBlocks.blockJar, 1, 1)).setParentsHidden("INFUSION").registerResearchItem();
research.setPages(new ResearchPage("tc.research_page.JARBRAIN.1"), infusionPage("JarBrain"));
}
private static void registerResearchPages() {
ResourceLocation background = new ResourceLocation("thaumcraft", "textures/gui/gui_researchback.png");
ResearchCategories.registerCategory(LibResearch.CATEGORY_ENCHANTING, new ResourceLocation(LibResources.MISC_R_ENCHANTING), background);
}
private static ResearchPage recipePage(String name) {
return new ResearchPage((IRecipe) ConfigResearch.recipes.get(name));
}
private static ResearchPage arcaneRecipePage(String name) {
return new ResearchPage((IArcaneRecipe) ConfigResearch.recipes.get(name));
}
private static ResearchPage infusionPage(String name) {
return new ResearchPage((InfusionRecipe) ConfigResearch.recipes.get(name));
}
private static ResearchPage cruciblePage(String name) {
return new ResearchPage((CrucibleRecipe) ConfigResearch.recipes.get(name));
}
}
| true | true | public static void initResearch() {
registerResearchPages();
ResearchItem research;
research = new TTResearchItem(LibResearch.KEY_DARK_QUARTZ, LibResearch.CATEGORY_ARTIFICE, new AspectList(), -2, -1, 0, new ItemStack(ModItems.darkQuartz)).setStub().setAutoUnlock().setRound().registerResearchItem();
research.setPages(new ResearchPage("0"), recipePage(LibResearch.KEY_DARK_QUARTZ + 0), recipePage(LibResearch.KEY_DARK_QUARTZ + 1), recipePage(LibResearch.KEY_DARK_QUARTZ + 2), recipePage(LibResearch.KEY_DARK_QUARTZ + 3), recipePage(LibResearch.KEY_DARK_QUARTZ + 4), recipePage(LibResearch.KEY_DARK_QUARTZ + 5));
research = new TTResearchItem(LibResearch.KEY_INTERFACE, LibResearch.CATEGORY_ARTIFICE, new AspectList().add(Aspect.ENTROPY, 4).add(Aspect.ORDER, 4), 3, -3, 1, new ItemStack(ModBlocks.interfase)).setParents("ARCANESTONE").registerResearchItem();
research.setPages(new ResearchPage("0"), arcaneRecipePage(LibResearch.KEY_INTERFACE), new ResearchPage("1"), arcaneRecipePage(LibResearch.KEY_CONNECTOR));
research = new TTResearchItem(LibResearch.KEY_GASEOUS_LIGHT, LibResearch.CATEGORY_ALCHEMY, new AspectList().add(Aspect.LIGHT, 2).add(Aspect.AIR, 1), 5, -2, 2, new ItemStack(ModItems.gaseousLight)).setParents("NITOR").registerResearchItem();
research.setPages(new ResearchPage("0"), cruciblePage(LibResearch.KEY_GASEOUS_LIGHT));
research = new TTResearchItem(LibResearch.KEY_GASEOUS_SHADOW, LibResearch.CATEGORY_ALCHEMY, new AspectList().add(Aspect.DARKNESS, 2).add(Aspect.AIR, 1).add(Aspect.MOTION, 4), 5, 0, 2, new ItemStack(ModItems.gaseousShadow)).setParents("ALUMENTUM").setParentsHidden(LibResearch.KEY_GASEOUS_LIGHT).setSiblings(LibResearch.KEY_GAS_REMOVER).registerResearchItem();
research.setPages(new ResearchPage("0"), cruciblePage(LibResearch.KEY_GASEOUS_SHADOW));
research = new TTResearchItem(LibResearch.KEY_GAS_REMOVER, LibResearch.CATEGORY_ALCHEMY, new AspectList(), 6, 0, 0, new ItemStack(ModItems.gasRemover)).setRound().registerResearchItem();
research.setPages(new ResearchPage("0"), arcaneRecipePage(LibResearch.KEY_GAS_REMOVER));
research = new TTResearchItem(LibResearch.KEY_SPELL_CLOTH, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.MAGIC, 2).add(Aspect.CLOTH, 1), 0, 0, 2, new ItemStack(ModItems.spellCloth)).setParentsHidden("ENCHFABRIC").registerResearchItem();
research.setPages(new ResearchPage("0"), cruciblePage(LibResearch.KEY_SPELL_CLOTH));
research = new TTResearchItem(LibResearch.KEY_ANIMATION_TABLET, LibResearch.CATEGORY_GOLEMANCY, new AspectList().add(Aspect.MECHANISM, 2).add(Aspect.METAL, 1).add(Aspect.MOTION, 1).add(Aspect.ENERGY, 1), -3, 1, 4, new ItemStack(ModBlocks.animationTablet)).setParents("COREGATHER").setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"), arcaneRecipePage(LibResearch.KEY_ANIMATION_TABLET));
research = new TTResearchItem(LibResearch.KEY_FOCUS_FLIGHT, LibResearch.CATEGORY_THAUMATURGY, new AspectList().add(Aspect.MOTION, 1).add(Aspect.MAGIC, 1).add(Aspect.AIR, 2), 4, -6, 2, new ItemStack(ModItems.focusFlight)).setParents("FOCUSSHOCK").setParentsHidden("ELEMENTALSWORD").setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), infusionPage(LibResearch.KEY_FOCUS_FLIGHT));
research = new TTResearchItem(LibResearch.KEY_FOCUS_DISLOCATION, LibResearch.CATEGORY_THAUMATURGY, new AspectList().add(Aspect.ELDRITCH, 2).add(Aspect.MAGIC, 1).add(Aspect.EXCHANGE, 1), 6, -2, 2, new ItemStack(ModItems.focusDislocation)).setParents("FOCUSTRADE").setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), new ResearchPage("1"), infusionPage(LibResearch.KEY_FOCUS_DISLOCATION));
research = new TTResearchItem(LibResearch.KEY_CLEANSING_TALISMAN, LibResearch.CATEGORY_ARTIFICE, new AspectList().add(Aspect.HEAL, 2).add(Aspect.ORDER, 1).add(Aspect.POISON, 1), 2, 4, 3, new ItemStack(ModItems.cleansingTalisman)).setParents("ENCHFABRIC").setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"), infusionPage(LibResearch.KEY_CLEANSING_TALISMAN));
research = new TTResearchItem(LibResearch.KEY_BRIGHT_NITOR, LibResearch.CATEGORY_ALCHEMY, new AspectList().add(Aspect.LIGHT, 2).add(Aspect.FIRE, 1).add(Aspect.ENERGY, 1).add(Aspect.AIR, 1), 3, -3, 3, new ItemStack(ModItems.brightNitor)).setParents(LibResearch.KEY_GASEOUS_LIGHT).setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), cruciblePage(LibResearch.KEY_BRIGHT_NITOR));
research = new TTResearchItem(LibResearch.KEY_FOCUS_TELEKINESIS, LibResearch.CATEGORY_THAUMATURGY, new AspectList().add(Aspect.ELDRITCH, 2).add(Aspect.MAGIC, 1).add(Aspect.MOTION, 1), 6, 0, 2, new ItemStack(ModItems.focusTelekinesis)).setParents(LibResearch.KEY_FOCUS_DISLOCATION).setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), infusionPage(LibResearch.KEY_FOCUS_TELEKINESIS));
research = new TTResearchItem(LibResearch.KEY_MAGNETS, LibResearch.CATEGORY_ARTIFICE, new AspectList().add(Aspect.MECHANISM, 2).add(Aspect.MOTION, 1).add(Aspect.SENSES, 1), -5, -3, 3, new ItemStack(ModBlocks.magnet)).setParentsHidden(LibResearch.KEY_FOCUS_TELEKINESIS).setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), new ResearchPage("1"), arcaneRecipePage(LibResearch.KEY_MAGNET), arcaneRecipePage(LibResearch.KEY_MOB_MAGNET), cruciblePage(LibResearch.KEY_MAGNETS));
research = new TTResearchItem(LibResearch.KEY_ENCHANTER, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.MAGIC, 2).add(Aspect.AURA, 1).add(Aspect.ELDRITCH, 1).add(Aspect.DARKNESS, 1).add(Aspect.MIND, 1), 2, -2, 5, new ItemStack(ModBlocks.enchanter)).setParents(LibResearch.KEY_SPELL_CLOTH).setParentsHidden("RESEARCHER2").setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), new ResearchPage("1"), new ResearchPage("2"), infusionPage(LibResearch.KEY_ENCHANTER));
research = new TTResearchItem(LibResearch.KEY_XP_TALISMAN, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.GREED, 1).add(Aspect.MAGIC, 1).add(Aspect.MAN, 1), -2, 2, 2, new ItemStack(ModItems.xpTalisman, 1, 1)).setParents("JARBRAIN").setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), infusionPage(LibResearch.KEY_XP_TALISMAN));
research = new TTResearchItem(LibResearch.KEY_FUNNEL, LibResearch.CATEGORY_ALCHEMY, new AspectList().add(Aspect.TOOL, 1).add(Aspect.TRAVEL, 2), 8, -2, 1, new ItemStack(ModBlocks.funnel)).setParents("DISTILESSENTIA").setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), arcaneRecipePage(LibResearch.KEY_FUNNEL));
research = new TTResearchItem(LibResearch.KEY_ENCHANT_ASCENT_BOOST, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.AIR, 1).add(Aspect.MOTION, 1).add(Aspect.MAGIC, 2), -2, -3, 2, new ResourceLocation(LibResources.ENCHANT_ASCENT_BOOST)).setParents(LibResearch.KEY_ENCHANTER).setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"));
research = new TTResearchItem(LibResearch.KEY_ENCHANT_SLOW_FALL, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.AIR, 1).add(Aspect.MOTION, 1).add(Aspect.MAGIC, 2), -1, -5, 2, new ResourceLocation(LibResources.ENCHANT_SLOW_FALL)).setParents(LibResearch.KEY_ENCHANTER).setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"));
research = new TTResearchItem(LibResearch.KEY_ENCHANT_AUTO_SMELT, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.FIRE, 1).add(Aspect.ENTROPY, 1).add(Aspect.MAGIC, 2), 1, -6, 2, new ResourceLocation(LibResources.ENCHANT_AUTO_SMELT)).setParents(LibResearch.KEY_ENCHANTER).setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"));
research = new TTResearchItem(LibResearch.KEY_ENCHANT_DESINTEGRATE, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.ENTROPY, 1).add(Aspect.VOID, 1).add(Aspect.MAGIC, 2), 3, -6, 2, new ResourceLocation(LibResources.ENCHANT_DESINTEGRATE)).setParents(LibResearch.KEY_ENCHANTER).setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"));
research = new TTResearchItem(LibResearch.KEY_ENCHANT_QUICK_DRAW, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.SENSES, 1).add(Aspect.WEAPON, 1).add(Aspect.MAGIC, 2), 5, -5, 2, new ResourceLocation(LibResources.ENCHANT_QUICK_DRAW)).setParents(LibResearch.KEY_ENCHANTER).setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"));
research = new TTResearchItem(LibResearch.KEY_ENCHANT_VAMPIRISM, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.HUNGER, 1).add(Aspect.WEAPON, 1).add(Aspect.MAGIC, 2), 6, -3, 2, new ResourceLocation(LibResources.ENCHANT_VAMPIRISM)).setParents(LibResearch.KEY_ENCHANTER).setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"));
research = new TTResearchItem(LibResearch.KEY_FOCUS_SMELT, LibResearch.CATEGORY_THAUMATURGY, new AspectList().add(Aspect.FIRE, 2).add(Aspect.ENERGY, 1).add(Aspect.MAGIC, 1), -1, -5, 2, new ItemStack(ModItems.focusSmelt)).setParents("FOCUSEXCAVATION").setParentsHidden("INFERNALFURNACE").setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), arcaneRecipePage(LibResearch.KEY_FOCUS_SMELT));
// Peripheral documentation research
if(Loader.isModLoaded("ComputerCraft")) {
research = new TTResearchItem(LibResearch.KEY_PERIPHERALS, LibResearch.CATEGORY_BASICS, new AspectList(), 0, 2, 0, new ItemStack(Item.redstone)).setAutoUnlock().setRound().registerResearchItem();
research.setPages(new ResearchPage("0"));
}
// Move the Brain in a jar research
research = ResearchCategories.getResearch("JARBRAIN");
ResearchCategories.researchCategories.get(LibResearch.CATEGORY_ARTIFICE).research.remove("JARBRAIN");
research = new ResearchItem("JARBRAIN", LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.SENSES, 1).add(Aspect.MIND, 2).add(Aspect.UNDEAD, 2), -3, 0, 2, new ItemStack(ConfigBlocks.blockJar, 1, 1)).setParentsHidden("INFUSION").registerResearchItem();
research.setPages(new ResearchPage("tc.research_page.JARBRAIN.1"), infusionPage("JarBrain"));
}
| public static void initResearch() {
registerResearchPages();
ResearchItem research;
research = new TTResearchItem(LibResearch.KEY_DARK_QUARTZ, LibResearch.CATEGORY_ARTIFICE, new AspectList(), -2, -1, 0, new ItemStack(ModItems.darkQuartz)).setStub().setAutoUnlock().setRound().registerResearchItem();
research.setPages(new ResearchPage("0"), recipePage(LibResearch.KEY_DARK_QUARTZ + 0), recipePage(LibResearch.KEY_DARK_QUARTZ + 1), recipePage(LibResearch.KEY_DARK_QUARTZ + 2), recipePage(LibResearch.KEY_DARK_QUARTZ + 3), recipePage(LibResearch.KEY_DARK_QUARTZ + 4), recipePage(LibResearch.KEY_DARK_QUARTZ + 5));
research = new TTResearchItem(LibResearch.KEY_INTERFACE, LibResearch.CATEGORY_ARTIFICE, new AspectList().add(Aspect.ENTROPY, 4).add(Aspect.ORDER, 4), 3, -3, 1, new ItemStack(ModBlocks.interfase)).setParents("ARCANESTONE").registerResearchItem();
research.setPages(new ResearchPage("0"), arcaneRecipePage(LibResearch.KEY_INTERFACE), new ResearchPage("1"), arcaneRecipePage(LibResearch.KEY_CONNECTOR));
research = new TTResearchItem(LibResearch.KEY_GASEOUS_LIGHT, LibResearch.CATEGORY_ALCHEMY, new AspectList().add(Aspect.LIGHT, 2).add(Aspect.AIR, 1), 5, -2, 2, new ItemStack(ModItems.gaseousLight)).setParents("NITOR").registerResearchItem();
research.setPages(new ResearchPage("0"), cruciblePage(LibResearch.KEY_GASEOUS_LIGHT));
research = new TTResearchItem(LibResearch.KEY_GASEOUS_SHADOW, LibResearch.CATEGORY_ALCHEMY, new AspectList().add(Aspect.DARKNESS, 2).add(Aspect.AIR, 1).add(Aspect.MOTION, 4), 5, 0, 2, new ItemStack(ModItems.gaseousShadow)).setParents("ALUMENTUM").setParentsHidden(LibResearch.KEY_GASEOUS_LIGHT).setSiblings(LibResearch.KEY_GAS_REMOVER).registerResearchItem();
research.setPages(new ResearchPage("0"), cruciblePage(LibResearch.KEY_GASEOUS_SHADOW));
research = new TTResearchItem(LibResearch.KEY_GAS_REMOVER, LibResearch.CATEGORY_ALCHEMY, new AspectList(), 6, 0, 0, new ItemStack(ModItems.gasRemover)).setRound().registerResearchItem();
research.setPages(new ResearchPage("0"), arcaneRecipePage(LibResearch.KEY_GAS_REMOVER));
research = new TTResearchItem(LibResearch.KEY_SPELL_CLOTH, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.MAGIC, 2).add(Aspect.CLOTH, 1), 0, 0, 2, new ItemStack(ModItems.spellCloth)).setParentsHidden("ENCHFABRIC").registerResearchItem();
research.setPages(new ResearchPage("0"), cruciblePage(LibResearch.KEY_SPELL_CLOTH));
research = new TTResearchItem(LibResearch.KEY_ANIMATION_TABLET, LibResearch.CATEGORY_GOLEMANCY, new AspectList().add(Aspect.MECHANISM, 2).add(Aspect.METAL, 1).add(Aspect.MOTION, 1).add(Aspect.ENERGY, 1), -3, 1, 4, new ItemStack(ModBlocks.animationTablet)).setParents("COREGATHER").setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"), arcaneRecipePage(LibResearch.KEY_ANIMATION_TABLET));
research = new TTResearchItem(LibResearch.KEY_FOCUS_FLIGHT, LibResearch.CATEGORY_THAUMATURGY, new AspectList().add(Aspect.MOTION, 1).add(Aspect.MAGIC, 1).add(Aspect.AIR, 2), 4, -6, 2, new ItemStack(ModItems.focusFlight)).setParents("FOCUSSHOCK").setParentsHidden("ELEMENTALSWORD").setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), infusionPage(LibResearch.KEY_FOCUS_FLIGHT));
research = new TTResearchItem(LibResearch.KEY_FOCUS_DISLOCATION, LibResearch.CATEGORY_THAUMATURGY, new AspectList().add(Aspect.ELDRITCH, 2).add(Aspect.MAGIC, 1).add(Aspect.EXCHANGE, 1), 6, -2, 2, new ItemStack(ModItems.focusDislocation)).setParents("FOCUSTRADE").setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), new ResearchPage("1"), infusionPage(LibResearch.KEY_FOCUS_DISLOCATION));
research = new TTResearchItem(LibResearch.KEY_CLEANSING_TALISMAN, LibResearch.CATEGORY_ARTIFICE, new AspectList().add(Aspect.HEAL, 2).add(Aspect.ORDER, 1).add(Aspect.POISON, 1), 2, 4, 3, new ItemStack(ModItems.cleansingTalisman)).setParents("ENCHFABRIC").setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"), infusionPage(LibResearch.KEY_CLEANSING_TALISMAN));
research = new TTResearchItem(LibResearch.KEY_BRIGHT_NITOR, LibResearch.CATEGORY_ALCHEMY, new AspectList().add(Aspect.LIGHT, 2).add(Aspect.FIRE, 1).add(Aspect.ENERGY, 1).add(Aspect.AIR, 1), 3, -3, 3, new ItemStack(ModItems.brightNitor)).setParents(LibResearch.KEY_GASEOUS_LIGHT).setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), cruciblePage(LibResearch.KEY_BRIGHT_NITOR));
research = new TTResearchItem(LibResearch.KEY_FOCUS_TELEKINESIS, LibResearch.CATEGORY_THAUMATURGY, new AspectList().add(Aspect.ELDRITCH, 2).add(Aspect.MAGIC, 1).add(Aspect.MOTION, 1), 6, 0, 2, new ItemStack(ModItems.focusTelekinesis)).setParents(LibResearch.KEY_FOCUS_DISLOCATION).setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), infusionPage(LibResearch.KEY_FOCUS_TELEKINESIS));
research = new TTResearchItem(LibResearch.KEY_MAGNETS, LibResearch.CATEGORY_ARTIFICE, new AspectList().add(Aspect.MECHANISM, 2).add(Aspect.MOTION, 1).add(Aspect.SENSES, 1), -5, -3, 3, new ItemStack(ModBlocks.magnet)).setParentsHidden(LibResearch.KEY_FOCUS_TELEKINESIS).setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), new ResearchPage("1"), arcaneRecipePage(LibResearch.KEY_MAGNET), arcaneRecipePage(LibResearch.KEY_MOB_MAGNET), cruciblePage(LibResearch.KEY_MAGNETS));
research = new TTResearchItem(LibResearch.KEY_ENCHANTER, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.MAGIC, 2).add(Aspect.AURA, 1).add(Aspect.ELDRITCH, 1).add(Aspect.DARKNESS, 1).add(Aspect.MIND, 1), 2, -2, 5, new ItemStack(ModBlocks.enchanter)).setParents(LibResearch.KEY_SPELL_CLOTH).setParentsHidden("RESEARCHER2").setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), new ResearchPage("1"), new ResearchPage("2"), infusionPage(LibResearch.KEY_ENCHANTER));
research = new TTResearchItem(LibResearch.KEY_XP_TALISMAN, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.GREED, 1).add(Aspect.MAGIC, 1).add(Aspect.MAN, 1), -2, 2, 2, new ItemStack(ModItems.xpTalisman, 1, 1)).setParents("JARBRAIN").setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), infusionPage(LibResearch.KEY_XP_TALISMAN));
research = new TTResearchItem(LibResearch.KEY_FUNNEL, LibResearch.CATEGORY_ALCHEMY, new AspectList().add(Aspect.TOOL, 1).add(Aspect.TRAVEL, 2), 7, -2, 1, new ItemStack(ModBlocks.funnel)).setParents("DISTILESSENTIA").setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), arcaneRecipePage(LibResearch.KEY_FUNNEL));
research = new TTResearchItem(LibResearch.KEY_ENCHANT_ASCENT_BOOST, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.AIR, 1).add(Aspect.MOTION, 1).add(Aspect.MAGIC, 2), -2, -3, 2, new ResourceLocation(LibResources.ENCHANT_ASCENT_BOOST)).setParents(LibResearch.KEY_ENCHANTER).setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"));
research = new TTResearchItem(LibResearch.KEY_ENCHANT_SLOW_FALL, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.AIR, 1).add(Aspect.MOTION, 1).add(Aspect.MAGIC, 2), -1, -5, 2, new ResourceLocation(LibResources.ENCHANT_SLOW_FALL)).setParents(LibResearch.KEY_ENCHANTER).setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"));
research = new TTResearchItem(LibResearch.KEY_ENCHANT_AUTO_SMELT, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.FIRE, 1).add(Aspect.ENTROPY, 1).add(Aspect.MAGIC, 2), 1, -6, 2, new ResourceLocation(LibResources.ENCHANT_AUTO_SMELT)).setParents(LibResearch.KEY_ENCHANTER).setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"));
research = new TTResearchItem(LibResearch.KEY_ENCHANT_DESINTEGRATE, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.ENTROPY, 1).add(Aspect.VOID, 1).add(Aspect.MAGIC, 2), 3, -6, 2, new ResourceLocation(LibResources.ENCHANT_DESINTEGRATE)).setParents(LibResearch.KEY_ENCHANTER).setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"));
research = new TTResearchItem(LibResearch.KEY_ENCHANT_QUICK_DRAW, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.SENSES, 1).add(Aspect.WEAPON, 1).add(Aspect.MAGIC, 2), 5, -5, 2, new ResourceLocation(LibResources.ENCHANT_QUICK_DRAW)).setParents(LibResearch.KEY_ENCHANTER).setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"));
research = new TTResearchItem(LibResearch.KEY_ENCHANT_VAMPIRISM, LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.HUNGER, 1).add(Aspect.WEAPON, 1).add(Aspect.MAGIC, 2), 6, -3, 2, new ResourceLocation(LibResources.ENCHANT_VAMPIRISM)).setParents(LibResearch.KEY_ENCHANTER).setHidden().registerResearchItem();
research.setPages(new ResearchPage("0"));
research = new TTResearchItem(LibResearch.KEY_FOCUS_SMELT, LibResearch.CATEGORY_THAUMATURGY, new AspectList().add(Aspect.FIRE, 2).add(Aspect.ENERGY, 1).add(Aspect.MAGIC, 1), -1, -5, 2, new ItemStack(ModItems.focusSmelt)).setParents("FOCUSEXCAVATION").setParentsHidden("INFERNALFURNACE").setConcealed().registerResearchItem();
research.setPages(new ResearchPage("0"), arcaneRecipePage(LibResearch.KEY_FOCUS_SMELT));
// Peripheral documentation research
if(Loader.isModLoaded("ComputerCraft")) {
research = new TTResearchItem(LibResearch.KEY_PERIPHERALS, LibResearch.CATEGORY_BASICS, new AspectList(), 0, 2, 0, new ItemStack(Item.redstone)).setAutoUnlock().setRound().registerResearchItem();
research.setPages(new ResearchPage("0"));
}
// Move the Brain in a jar research
research = ResearchCategories.getResearch("JARBRAIN");
ResearchCategories.researchCategories.get(LibResearch.CATEGORY_ARTIFICE).research.remove("JARBRAIN");
research = new ResearchItem("JARBRAIN", LibResearch.CATEGORY_ENCHANTING, new AspectList().add(Aspect.SENSES, 1).add(Aspect.MIND, 2).add(Aspect.UNDEAD, 2), -3, 0, 2, new ItemStack(ConfigBlocks.blockJar, 1, 1)).setParentsHidden("INFUSION").registerResearchItem();
research.setPages(new ResearchPage("tc.research_page.JARBRAIN.1"), infusionPage("JarBrain"));
}
|
diff --git a/platform/android/src/com/artifex/mupdfdemo/MuPDFPageAdapter.java b/platform/android/src/com/artifex/mupdfdemo/MuPDFPageAdapter.java
index 6ed10fe4..36c17a97 100644
--- a/platform/android/src/com/artifex/mupdfdemo/MuPDFPageAdapter.java
+++ b/platform/android/src/com/artifex/mupdfdemo/MuPDFPageAdapter.java
@@ -1,79 +1,79 @@
package com.artifex.mupdfdemo;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.PointF;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class MuPDFPageAdapter extends BaseAdapter {
private final Context mContext;
private final FilePicker.FilePickerSupport mFilePickerSupport;
private final MuPDFCore mCore;
private final SparseArray<PointF> mPageSizes = new SparseArray<PointF>();
private Bitmap mSharedHqBm;
public MuPDFPageAdapter(Context c, FilePicker.FilePickerSupport filePickerSupport, MuPDFCore core) {
mContext = c;
mFilePickerSupport = filePickerSupport;
mCore = core;
}
public int getCount() {
return mCore.countPages();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final MuPDFPageView pageView;
if (convertView == null) {
- if (mSharedHqBm == null || mSharedHqBm.getWidth() != parent.getWidth() || mSharedHqBm.getWidth() != parent.getWidth())
+ if (mSharedHqBm == null || mSharedHqBm.getWidth() != parent.getWidth() || mSharedHqBm.getHeight() != parent.getHeight())
mSharedHqBm = Bitmap.createBitmap(parent.getWidth(), parent.getHeight(), Bitmap.Config.ARGB_8888);
pageView = new MuPDFPageView(mContext, mFilePickerSupport, mCore, new Point(parent.getWidth(), parent.getHeight()), mSharedHqBm);
} else {
pageView = (MuPDFPageView) convertView;
}
PointF pageSize = mPageSizes.get(position);
if (pageSize != null) {
// We already know the page size. Set it up
// immediately
pageView.setPage(position, pageSize);
} else {
// Page size as yet unknown. Blank it for now, and
// start a background task to find the size
pageView.blank(position);
AsyncTask<Void,Void,PointF> sizingTask = new AsyncTask<Void,Void,PointF>() {
@Override
protected PointF doInBackground(Void... arg0) {
return mCore.getPageSize(position);
}
@Override
protected void onPostExecute(PointF result) {
super.onPostExecute(result);
// We now know the page size
mPageSizes.put(position, result);
// Check that this view hasn't been reused for
// another page since we started
if (pageView.getPage() == position)
pageView.setPage(position, result);
}
};
sizingTask.execute((Void)null);
}
return pageView;
}
}
| true | true | public View getView(final int position, View convertView, ViewGroup parent) {
final MuPDFPageView pageView;
if (convertView == null) {
if (mSharedHqBm == null || mSharedHqBm.getWidth() != parent.getWidth() || mSharedHqBm.getWidth() != parent.getWidth())
mSharedHqBm = Bitmap.createBitmap(parent.getWidth(), parent.getHeight(), Bitmap.Config.ARGB_8888);
pageView = new MuPDFPageView(mContext, mFilePickerSupport, mCore, new Point(parent.getWidth(), parent.getHeight()), mSharedHqBm);
} else {
pageView = (MuPDFPageView) convertView;
}
PointF pageSize = mPageSizes.get(position);
if (pageSize != null) {
// We already know the page size. Set it up
// immediately
pageView.setPage(position, pageSize);
} else {
// Page size as yet unknown. Blank it for now, and
// start a background task to find the size
pageView.blank(position);
AsyncTask<Void,Void,PointF> sizingTask = new AsyncTask<Void,Void,PointF>() {
@Override
protected PointF doInBackground(Void... arg0) {
return mCore.getPageSize(position);
}
@Override
protected void onPostExecute(PointF result) {
super.onPostExecute(result);
// We now know the page size
mPageSizes.put(position, result);
// Check that this view hasn't been reused for
// another page since we started
if (pageView.getPage() == position)
pageView.setPage(position, result);
}
};
sizingTask.execute((Void)null);
}
return pageView;
}
| public View getView(final int position, View convertView, ViewGroup parent) {
final MuPDFPageView pageView;
if (convertView == null) {
if (mSharedHqBm == null || mSharedHqBm.getWidth() != parent.getWidth() || mSharedHqBm.getHeight() != parent.getHeight())
mSharedHqBm = Bitmap.createBitmap(parent.getWidth(), parent.getHeight(), Bitmap.Config.ARGB_8888);
pageView = new MuPDFPageView(mContext, mFilePickerSupport, mCore, new Point(parent.getWidth(), parent.getHeight()), mSharedHqBm);
} else {
pageView = (MuPDFPageView) convertView;
}
PointF pageSize = mPageSizes.get(position);
if (pageSize != null) {
// We already know the page size. Set it up
// immediately
pageView.setPage(position, pageSize);
} else {
// Page size as yet unknown. Blank it for now, and
// start a background task to find the size
pageView.blank(position);
AsyncTask<Void,Void,PointF> sizingTask = new AsyncTask<Void,Void,PointF>() {
@Override
protected PointF doInBackground(Void... arg0) {
return mCore.getPageSize(position);
}
@Override
protected void onPostExecute(PointF result) {
super.onPostExecute(result);
// We now know the page size
mPageSizes.put(position, result);
// Check that this view hasn't been reused for
// another page since we started
if (pageView.getPage() == position)
pageView.setPage(position, result);
}
};
sizingTask.execute((Void)null);
}
return pageView;
}
|
diff --git a/src/org/ballproject/knime/base/node/GenericKnimeNodeDialog.java b/src/org/ballproject/knime/base/node/GenericKnimeNodeDialog.java
index c9a0df4..9c38584 100644
--- a/src/org/ballproject/knime/base/node/GenericKnimeNodeDialog.java
+++ b/src/org/ballproject/knime/base/node/GenericKnimeNodeDialog.java
@@ -1,119 +1,121 @@
/*
* Copyright (c) 2011, Marc Röttig.
*
* This file is part of GenericKnimeNodes.
*
* GenericKnimeNodes 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ballproject.knime.base.node;
import java.io.FileNotFoundException;
import org.ballproject.knime.base.config.NodeConfiguration;
import org.ballproject.knime.base.parameter.InvalidParameterValueException;
import org.ballproject.knime.base.parameter.Parameter;
import org.ballproject.knime.base.treetabledialog.MimeTypeChooserDialog;
import org.ballproject.knime.base.treetabledialog.ParameterDialog;
import org.knime.core.data.DataTableSpec;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.NodeDialogPane;
import org.knime.core.node.NodeSettingsRO;
import org.knime.core.node.NodeSettingsWO;
import org.knime.core.node.NotConfigurableException;
public class GenericKnimeNodeDialog extends NodeDialogPane
{
private NodeConfiguration config;
private ParameterDialog dialog;
private MimeTypeChooserDialog mtc;
public GenericKnimeNodeDialog(NodeConfiguration config)
{
this.config = config;
try
{
dialog = new ParameterDialog(config);
this.addTab("Parameters", dialog);
mtc = new MimeTypeChooserDialog(config);
this.addTab("OutputTypes", mtc);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
protected void saveSettingsTo(NodeSettingsWO settings) throws InvalidSettingsException
{
for(Parameter<?> param: config.getParameters())
{
settings.addString(param.getKey(), param.getStringRep());
}
int[] sel_ports = mtc.getSelectedTypes();
for(int i=0;i<this.config.getNumberOfOutputPorts();i++)
{
settings.addInt("GENERIC_KNIME_NODES_outtype#"+i, sel_ports[i]);
}
}
@Override
protected void loadSettingsFrom(NodeSettingsRO settings, DataTableSpec[] specs) throws NotConfigurableException
{
for(Parameter<?> param: config.getParameters())
{
String value = null;
try
{
value = settings.getString(param.getKey());
}
catch (InvalidSettingsException e)
{
e.printStackTrace();
}
try
{
param.fillFromString(value);
}
catch (InvalidParameterValueException e)
{
+ e.printStackTrace();
throw new NotConfigurableException(e.getMessage());
}
}
int nP = this.config.getNumberOfOutputPorts();
int[] sel_ports = new int[nP];
for(int i=0;i<nP;i++)
{
try
{
int idx = settings.getInt("GENERIC_KNIME_NODES_outtype#"+i);
sel_ports[i] = idx;
}
catch (InvalidSettingsException e)
{
+ e.printStackTrace();
throw new NotConfigurableException(e.getMessage());
}
}
mtc.setSelectedTypes(sel_ports);
}
}
| false | true | protected void loadSettingsFrom(NodeSettingsRO settings, DataTableSpec[] specs) throws NotConfigurableException
{
for(Parameter<?> param: config.getParameters())
{
String value = null;
try
{
value = settings.getString(param.getKey());
}
catch (InvalidSettingsException e)
{
e.printStackTrace();
}
try
{
param.fillFromString(value);
}
catch (InvalidParameterValueException e)
{
throw new NotConfigurableException(e.getMessage());
}
}
int nP = this.config.getNumberOfOutputPorts();
int[] sel_ports = new int[nP];
for(int i=0;i<nP;i++)
{
try
{
int idx = settings.getInt("GENERIC_KNIME_NODES_outtype#"+i);
sel_ports[i] = idx;
}
catch (InvalidSettingsException e)
{
throw new NotConfigurableException(e.getMessage());
}
}
mtc.setSelectedTypes(sel_ports);
}
| protected void loadSettingsFrom(NodeSettingsRO settings, DataTableSpec[] specs) throws NotConfigurableException
{
for(Parameter<?> param: config.getParameters())
{
String value = null;
try
{
value = settings.getString(param.getKey());
}
catch (InvalidSettingsException e)
{
e.printStackTrace();
}
try
{
param.fillFromString(value);
}
catch (InvalidParameterValueException e)
{
e.printStackTrace();
throw new NotConfigurableException(e.getMessage());
}
}
int nP = this.config.getNumberOfOutputPorts();
int[] sel_ports = new int[nP];
for(int i=0;i<nP;i++)
{
try
{
int idx = settings.getInt("GENERIC_KNIME_NODES_outtype#"+i);
sel_ports[i] = idx;
}
catch (InvalidSettingsException e)
{
e.printStackTrace();
throw new NotConfigurableException(e.getMessage());
}
}
mtc.setSelectedTypes(sel_ports);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.