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/spock-core/src/main/java/org/spockframework/mock/PositionalArgumentListConstraint.java b/spock-core/src/main/java/org/spockframework/mock/PositionalArgumentListConstraint.java index fbc62fa5..1a1f932c 100755 --- a/spock-core/src/main/java/org/spockframework/mock/PositionalArgumentListConstraint.java +++ b/spock-core/src/main/java/org/spockframework/mock/PositionalArgumentListConstraint.java @@ -1,73 +1,73 @@ /* * Copyright 2009 the original author or authors. * * 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.spockframework.mock; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.spockframework.util.*; /** * * @author Peter Niederwieser */ public class PositionalArgumentListConstraint implements IInvocationConstraint { private final List<IArgumentConstraint> argConstraints; public PositionalArgumentListConstraint(List<IArgumentConstraint> argConstraints) { this.argConstraints = argConstraints; } public boolean isSatisfiedBy(IMockInvocation invocation) { List<Object> args = invocation.getArguments(); if (areConstraintsSatisfiedBy(args)) return true; if (!canBeCalledWithVarArgSyntax(invocation.getMethod())) return false; return areConstraintsSatisfiedBy(expandVarArgs(args)); } /** * Tells if the given method can be called with vararg syntax from Groovy(!). * If yes, we also support vararg syntax in the interaction definition. */ private boolean canBeCalledWithVarArgSyntax(Method method) { Class<?>[] paramTypes = method.getParameterTypes(); return paramTypes.length > 0 && paramTypes[paramTypes.length - 1].isArray(); } private List<Object> expandVarArgs(List<Object> args) { List<Object> expanded = new ArrayList<Object>(); expanded.addAll(args.subList(0, args.size() - 1)); expanded.addAll(Arrays.asList((Object[]) CollectionUtil.getLastElement(args))); return expanded; } private boolean areConstraintsSatisfiedBy(List<Object> args) { - if (argConstraints.isEmpty() && args.isEmpty()) return true; + if (argConstraints.isEmpty()) return args.isEmpty(); if (argConstraints.size() - args.size() > 1) return false; for (int i = 0; i < argConstraints.size() - 1; i++) { if (!argConstraints.get(i).isSatisfiedBy(args.get(i))) return false; } IArgumentConstraint lastConstraint = CollectionUtil.getLastElement(argConstraints); if (lastConstraint instanceof SpreadWildcardArgumentConstraint) return true; return argConstraints.size() == args.size() && lastConstraint.isSatisfiedBy(CollectionUtil.getLastElement(args)); } }
true
true
private boolean areConstraintsSatisfiedBy(List<Object> args) { if (argConstraints.isEmpty() && args.isEmpty()) return true; if (argConstraints.size() - args.size() > 1) return false; for (int i = 0; i < argConstraints.size() - 1; i++) { if (!argConstraints.get(i).isSatisfiedBy(args.get(i))) return false; } IArgumentConstraint lastConstraint = CollectionUtil.getLastElement(argConstraints); if (lastConstraint instanceof SpreadWildcardArgumentConstraint) return true; return argConstraints.size() == args.size() && lastConstraint.isSatisfiedBy(CollectionUtil.getLastElement(args)); }
private boolean areConstraintsSatisfiedBy(List<Object> args) { if (argConstraints.isEmpty()) return args.isEmpty(); if (argConstraints.size() - args.size() > 1) return false; for (int i = 0; i < argConstraints.size() - 1; i++) { if (!argConstraints.get(i).isSatisfiedBy(args.get(i))) return false; } IArgumentConstraint lastConstraint = CollectionUtil.getLastElement(argConstraints); if (lastConstraint instanceof SpreadWildcardArgumentConstraint) return true; return argConstraints.size() == args.size() && lastConstraint.isSatisfiedBy(CollectionUtil.getLastElement(args)); }
diff --git a/src/main/java/com/forgenz/mobmanager/common/util/RandomLocationGen.java b/src/main/java/com/forgenz/mobmanager/common/util/RandomLocationGen.java index ba7a53f..bee9f52 100644 --- a/src/main/java/com/forgenz/mobmanager/common/util/RandomLocationGen.java +++ b/src/main/java/com/forgenz/mobmanager/common/util/RandomLocationGen.java @@ -1,358 +1,357 @@ /* * Copyright 2013 Michael McKnight. 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. * * 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 OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those of the * authors and contributors and should not be interpreted as representing official policies, * either expressed or implied, of anybody else. */ package com.forgenz.mobmanager.common.util; import java.util.ArrayList; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.ChunkSnapshot; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import com.forgenz.mobmanager.P; public class RandomLocationGen { private static List<Integer> cacheList; /** * Stop instances of the class from being created */ private RandomLocationGen() {} /** * Generates a random location around the center location */ public static Location getLocation(boolean circle, Location center, int range, int minRange, int heightRange) { return getLocation(circle, center, range, minRange, heightRange, LocationCache.getCachedLocation()); } /** * Generates a random location around the center location */ public static Location getLocation(boolean circle, Location center, int range, int minRange, int heightRange, Location cacheLoc) { return getLocation(circle, false, center, range, minRange, heightRange, cacheLoc); } /** * Generates a random location around the center location */ public static Location getLocation(boolean circle, boolean checkPlayers, Location center, int range, int minRange, int heightRange, Location cacheLoc) { return getLocation(circle, false, 5, center, range, minRange, heightRange, cacheLoc); } /** * Generates a random location around the center location */ public static Location getLocation(boolean circle, boolean checkPlayers, int spawnAttempts, Location center, int range, int minRange, int heightRange, Location cacheLoc) { // Make sure the centers world is valid if (center.getWorld() == null) { P.p().getLogger().warning("Null world passed to location generator"); return center; } // Make sure range is larger than minRange if (range < minRange) { range = range ^ minRange; minRange = range ^ minRange; range = range ^ minRange; } // Height range must be at least 1 if (heightRange < 0) heightRange = 1; // Make sure range is bigger than minRange if (range == minRange) ++range; // Calculate the total (up/down) range of heightRange int heightRange2 = heightRange << 1; // Copy the world cacheLoc.setWorld(center.getWorld()); // Make X attempts to find a safe spawning location for (int i = 0; i < spawnAttempts; ++i) { // Generate the appropriate type of location if (circle) { getCircularLocation(center, range, minRange, cacheLoc); } else { getSquareLocation(center, range, minRange, cacheLoc); } // Generate coordinates for Y cacheLoc.setY(RandomUtil.i.nextInt(heightRange2) - heightRange + center.getBlockY() + 0.5); // If the location is safe we can return the location if ((!checkPlayers || !PlayerFinder.playerNear(cacheLoc, minRange, heightRange)) && findSafeY(cacheLoc, center.getBlockY(), heightRange)) { // Generate a random Yaw/Pitch cacheLoc.setYaw(RandomUtil.i.nextFloat() * 360.0F); -// cacheLoc.setPitch(-10.0F + RandomUtil.i.nextFloat() * 20.0F); - cacheLoc.setPitch(90.0F); + cacheLoc.setPitch(0.0F); return cacheLoc; } } // If no safe location was found in a reasonable time frame just return the center return center; } /** * Finds a safe Y location at the given x/z location * @return true if a safe location was found */ public static boolean findSafeY(Location location, int centerY, int heightRange) { List<Integer> list = Bukkit.isPrimaryThread() ? cacheList : new ArrayList<Integer>(); if (list == null) cacheList = list = new ArrayList<Integer>(); return findSafeY(location, centerY, heightRange, list); } /** * Finds a safe Y location at the given x/z location * @return true if a safe location was found */ public static boolean findSafeY(Location location, int centerY, int heightRange, List<Integer> cacheList) { int foundAir = 0; // Fetch max and min Y locations int startY = centerY + heightRange; int endY = centerY - heightRange; // Validate max and min Y locations if (startY > 256) startY = 256; if (endY < 0) endY = 0; World world = location.getWorld(); if (!world.isChunkLoaded(location.getBlockX() >> 4, location.getBlockZ() >> 4)) return false; // Find sets of Y's which are safe for (; startY > endY; --startY) { Block b = world.getBlockAt(location.getBlockX(), startY, location.getBlockZ()); if (isSafeMaterial(b.getType())) { ++foundAir; } else { if (foundAir >= 2) cacheList.add(startY + 1); foundAir = 0; } } // If there are no safe locations we return false :( if (cacheList.isEmpty()) return false; // Fetch a random location location.setY(cacheList.get(RandomUtil.i.nextInt(cacheList.size()))); cacheList.clear(); return true; } /** * Finds a safe Y location at the given x/z location * Uses a chunk snapshot for speed * @return true if a safe location was found */ @SuppressWarnings("deprecation") public static boolean findSafeY(ChunkSnapshot chunk, Location location, int centerY, int heightRange, List<Integer> cacheList) { int foundAir = 0; // Fetch max and min Y locations int startY = centerY + heightRange; int endY = centerY - heightRange; // Validate max and min Y locations if (startY > 256) startY = 256; if (endY < 0) endY = 0; int x = location.getBlockX() % 16, z = location.getBlockZ() % 16; if (x < 0) x += 16; if (z < 0) z += 16; // Find sets of Y's which are safe for (; startY > endY; --startY) { if (isSafeMaterial(Material.getMaterial(chunk.getBlockTypeId(x, startY, z)))) { ++foundAir; } else { if (foundAir >= 2) cacheList.add(startY + 1); foundAir = 0; } } // If there are no safe locations we return false :( if (cacheList.isEmpty()) return false; // Fetch a random location location.setY(cacheList.get(RandomUtil.i.nextInt(cacheList.size()))); cacheList.clear(); return true; } /** * Generates a random location which is circular around the center */ public static Location getCircularLocation(Location center, int range, int minRange, Location cacheLoc) { return getCircularLocation(center.getBlockX(), center.getBlockZ(), range, minRange, cacheLoc); } public static Location getCircularLocation(int centerX, int centerZ, double range, double minRange, Location cacheLoc) { // Calculate the difference between the max and min range double rangeDiff = range - minRange; // Calculate a random direction for the X/Z values double theta = 2 * Math.PI * RandomUtil.i.nextDouble(); // Generate a random radius double radius = RandomUtil.i.nextDouble() * rangeDiff + minRange; // Set the X/Z coordinates double trig = Math.cos(theta); cacheLoc.setX(Location.locToBlock(radius * trig) + centerX + 0.5); trig = Math.sin(theta); cacheLoc.setZ(Location.locToBlock(radius * trig) + centerZ + 0.5); return cacheLoc; } /** * Generates a random location which is square around the center */ public static Location getSquareLocation(Location center, int range, int minRange, Location cacheLoc) { return getSquareLocation(center.getBlockX(), center.getBlockZ(), range, minRange, cacheLoc); } public static Location getSquareLocation(int centerX, int centerZ, int range, int minRange, Location cacheLoc) { // Calculate the sum of all the block deviations from the center between minRange and range int totalBlockCount = (range * (++range) - minRange * (minRange + 1)) >> 1; // Fetch a random number of blocks int blockCount = totalBlockCount - RandomUtil.i.nextInt(totalBlockCount); // While the block deviation from the center for the given range is // less than the number of blocks left we remove a layer of blocks while (range < blockCount) blockCount -= --range; // Pick a random location on the range line int lineLoc = RandomUtil.i.nextInt(range << 1); // Choose a line (North/East/West/South lines) // Then set the X/Z coordinates switch (RandomUtil.i.nextInt(4)) { // East Line going North case 0: cacheLoc.setX(centerX + range + 0.5D); cacheLoc.setZ(centerZ + range - lineLoc + 0.5D); break; // South Line going East case 1: cacheLoc.setX(centerX - range + lineLoc + 0.5D); cacheLoc.setZ(centerZ + range + 0.5D); break; // West Line going South case 2: cacheLoc.setX(centerX - range + 0.5D); cacheLoc.setZ(centerZ - range + lineLoc + 0.5D); break; // North Line going west case 3: default: cacheLoc.setX(centerX + range - lineLoc + 0.5D); cacheLoc.setZ(centerZ - range + 0.5D); } return cacheLoc; } /** * Checks if the block is of a type which is safe for spawning inside of * @return true if the block type is safe */ public static boolean isSafeBlock(Block block) { return isSafeMaterial(block.getType()); } public static boolean isSafeMaterial(Material mat) { switch (mat) { case AIR: case WEB: case VINE: case SNOW: case LONG_GRASS: case DEAD_BUSH: case SAPLING: return true; default: return false; } } }
true
true
public static Location getLocation(boolean circle, boolean checkPlayers, int spawnAttempts, Location center, int range, int minRange, int heightRange, Location cacheLoc) { // Make sure the centers world is valid if (center.getWorld() == null) { P.p().getLogger().warning("Null world passed to location generator"); return center; } // Make sure range is larger than minRange if (range < minRange) { range = range ^ minRange; minRange = range ^ minRange; range = range ^ minRange; } // Height range must be at least 1 if (heightRange < 0) heightRange = 1; // Make sure range is bigger than minRange if (range == minRange) ++range; // Calculate the total (up/down) range of heightRange int heightRange2 = heightRange << 1; // Copy the world cacheLoc.setWorld(center.getWorld()); // Make X attempts to find a safe spawning location for (int i = 0; i < spawnAttempts; ++i) { // Generate the appropriate type of location if (circle) { getCircularLocation(center, range, minRange, cacheLoc); } else { getSquareLocation(center, range, minRange, cacheLoc); } // Generate coordinates for Y cacheLoc.setY(RandomUtil.i.nextInt(heightRange2) - heightRange + center.getBlockY() + 0.5); // If the location is safe we can return the location if ((!checkPlayers || !PlayerFinder.playerNear(cacheLoc, minRange, heightRange)) && findSafeY(cacheLoc, center.getBlockY(), heightRange)) { // Generate a random Yaw/Pitch cacheLoc.setYaw(RandomUtil.i.nextFloat() * 360.0F); // cacheLoc.setPitch(-10.0F + RandomUtil.i.nextFloat() * 20.0F); cacheLoc.setPitch(90.0F); return cacheLoc; } } // If no safe location was found in a reasonable time frame just return the center return center; }
public static Location getLocation(boolean circle, boolean checkPlayers, int spawnAttempts, Location center, int range, int minRange, int heightRange, Location cacheLoc) { // Make sure the centers world is valid if (center.getWorld() == null) { P.p().getLogger().warning("Null world passed to location generator"); return center; } // Make sure range is larger than minRange if (range < minRange) { range = range ^ minRange; minRange = range ^ minRange; range = range ^ minRange; } // Height range must be at least 1 if (heightRange < 0) heightRange = 1; // Make sure range is bigger than minRange if (range == minRange) ++range; // Calculate the total (up/down) range of heightRange int heightRange2 = heightRange << 1; // Copy the world cacheLoc.setWorld(center.getWorld()); // Make X attempts to find a safe spawning location for (int i = 0; i < spawnAttempts; ++i) { // Generate the appropriate type of location if (circle) { getCircularLocation(center, range, minRange, cacheLoc); } else { getSquareLocation(center, range, minRange, cacheLoc); } // Generate coordinates for Y cacheLoc.setY(RandomUtil.i.nextInt(heightRange2) - heightRange + center.getBlockY() + 0.5); // If the location is safe we can return the location if ((!checkPlayers || !PlayerFinder.playerNear(cacheLoc, minRange, heightRange)) && findSafeY(cacheLoc, center.getBlockY(), heightRange)) { // Generate a random Yaw/Pitch cacheLoc.setYaw(RandomUtil.i.nextFloat() * 360.0F); cacheLoc.setPitch(0.0F); return cacheLoc; } } // If no safe location was found in a reasonable time frame just return the center return center; }
diff --git a/src/com/android/mms/ui/RecipientsAdapter.java b/src/com/android/mms/ui/RecipientsAdapter.java index 2719ac8..ca7ca16 100644 --- a/src/com/android/mms/ui/RecipientsAdapter.java +++ b/src/com/android/mms/ui/RecipientsAdapter.java @@ -1,208 +1,212 @@ /* * Copyright (C) 2008 Esmertec AG. * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.ui; import com.android.internal.database.ArrayListCursor; import com.android.mms.R; import com.android.mms.data.Contact; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.database.MergeCursor; import android.net.Uri; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.telephony.PhoneNumberUtils; import android.text.Annotation; import android.text.Spannable; import android.text.SpannableString; import android.text.TextUtils; import android.view.View; import android.widget.ResourceCursorAdapter; import android.widget.TextView; import java.util.ArrayList; /** * This adapter is used to filter contacts on both name and number. */ public class RecipientsAdapter extends ResourceCursorAdapter { public static final int CONTACT_ID_INDEX = 1; public static final int TYPE_INDEX = 2; public static final int NUMBER_INDEX = 3; public static final int LABEL_INDEX = 4; public static final int NAME_INDEX = 5; private static final String[] PROJECTION_PHONE = { Data._ID, // 0 RawContacts.CONTACT_ID, // 1 Phone.TYPE, // 2 Phone.NUMBER, // 3 Phone.LABEL, // 4 Contacts.DISPLAY_NAME, // 5 }; private static final String SORT_ORDER = Contacts.TIMES_CONTACTED + " DESC," + Contacts.DISPLAY_NAME + "," + Phone.TYPE; private final Context mContext; private final ContentResolver mContentResolver; public RecipientsAdapter(Context context) { super(context, R.layout.recipient_filter_item, null); mContext = context; mContentResolver = context.getContentResolver(); } @Override public final CharSequence convertToString(Cursor cursor) { String name = cursor.getString(RecipientsAdapter.NAME_INDEX); int type = cursor.getInt(RecipientsAdapter.TYPE_INDEX); String number = cursor.getString(RecipientsAdapter.NUMBER_INDEX).trim(); String label = cursor.getString(RecipientsAdapter.LABEL_INDEX); CharSequence displayLabel = Phone.getDisplayLabel(mContext, type, label); if (number.length() == 0) { return number; } if (name == null) { name = ""; } String nameAndNumber = Contact.formatNameAndNumber(name, number); SpannableString out = new SpannableString(nameAndNumber); int len = out.length(); if (!TextUtils.isEmpty(name)) { out.setSpan(new Annotation("name", name), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } else { out.setSpan(new Annotation("name", number), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } String person_id = cursor.getString(RecipientsAdapter.CONTACT_ID_INDEX); out.setSpan(new Annotation("person_id", person_id), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); out.setSpan(new Annotation("label", displayLabel.toString()), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); out.setSpan(new Annotation("number", number), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return out; } @Override public final void bindView(View view, Context context, Cursor cursor) { TextView name = (TextView) view.findViewById(R.id.name); name.setText(cursor.getString(NAME_INDEX)); TextView label = (TextView) view.findViewById(R.id.label); int type = cursor.getInt(TYPE_INDEX); label.setText(Phone.getDisplayLabel(mContext, type, cursor.getString(LABEL_INDEX))); TextView number = (TextView) view.findViewById(R.id.number); number.setText("(" + cursor.getString(NUMBER_INDEX) + ")"); } @Override public Cursor runQueryOnBackgroundThread(CharSequence constraint) { String phone = ""; String cons = null; if (constraint != null) { cons = constraint.toString(); if (usefulAsDigits(cons)) { phone = PhoneNumberUtils.convertKeypadLettersToDigits(cons); if (phone.equals(cons)) { phone = ""; } else { phone = phone.trim(); } } } Uri uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(cons)); Cursor phoneCursor = - mContentResolver.query(uri, PROJECTION_PHONE, Phone.TYPE + "=" + Phone.TYPE_MOBILE, - null, SORT_ORDER); + mContentResolver.query(uri, + PROJECTION_PHONE, + Phone.TYPE + '=' + Phone.TYPE_MOBILE + " OR " + + Phone.TYPE + '=' + Phone.TYPE_WORK_MOBILE, + null, + SORT_ORDER); if (phone.length() > 0) { ArrayList result = new ArrayList(); result.add(Integer.valueOf(-1)); // ID result.add(Long.valueOf(-1)); // PERSON_ID result.add(Integer.valueOf(Phone.TYPE_CUSTOM)); // TYPE result.add(phone); // NUMBER /* * The "\u00A0" keeps Phone.getDisplayLabel() from deciding * to display the default label ("Home") next to the transformation * of the letters into numbers. */ result.add("\u00A0"); // LABEL result.add(cons); // NAME ArrayList<ArrayList> wrap = new ArrayList<ArrayList>(); wrap.add(result); ArrayListCursor translated = new ArrayListCursor(PROJECTION_PHONE, wrap); return new MergeCursor(new Cursor[] { translated, phoneCursor }); } else { return phoneCursor; } } /** * Returns true if all the characters are meaningful as digits * in a phone number -- letters, digits, and a few punctuation marks. */ private boolean usefulAsDigits(CharSequence cons) { int len = cons.length(); for (int i = 0; i < len; i++) { char c = cons.charAt(i); if ((c >= '0') && (c <= '9')) { continue; } if ((c == ' ') || (c == '-') || (c == '(') || (c == ')') || (c == '.') || (c == '+') || (c == '#') || (c == '*')) { continue; } if ((c >= 'A') && (c <= 'Z')) { continue; } if ((c >= 'a') && (c <= 'z')) { continue; } return false; } return true; } }
true
true
public Cursor runQueryOnBackgroundThread(CharSequence constraint) { String phone = ""; String cons = null; if (constraint != null) { cons = constraint.toString(); if (usefulAsDigits(cons)) { phone = PhoneNumberUtils.convertKeypadLettersToDigits(cons); if (phone.equals(cons)) { phone = ""; } else { phone = phone.trim(); } } } Uri uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(cons)); Cursor phoneCursor = mContentResolver.query(uri, PROJECTION_PHONE, Phone.TYPE + "=" + Phone.TYPE_MOBILE, null, SORT_ORDER); if (phone.length() > 0) { ArrayList result = new ArrayList(); result.add(Integer.valueOf(-1)); // ID result.add(Long.valueOf(-1)); // PERSON_ID result.add(Integer.valueOf(Phone.TYPE_CUSTOM)); // TYPE result.add(phone); // NUMBER /* * The "\u00A0" keeps Phone.getDisplayLabel() from deciding * to display the default label ("Home") next to the transformation * of the letters into numbers. */ result.add("\u00A0"); // LABEL result.add(cons); // NAME ArrayList<ArrayList> wrap = new ArrayList<ArrayList>(); wrap.add(result); ArrayListCursor translated = new ArrayListCursor(PROJECTION_PHONE, wrap); return new MergeCursor(new Cursor[] { translated, phoneCursor }); } else { return phoneCursor; } }
public Cursor runQueryOnBackgroundThread(CharSequence constraint) { String phone = ""; String cons = null; if (constraint != null) { cons = constraint.toString(); if (usefulAsDigits(cons)) { phone = PhoneNumberUtils.convertKeypadLettersToDigits(cons); if (phone.equals(cons)) { phone = ""; } else { phone = phone.trim(); } } } Uri uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(cons)); Cursor phoneCursor = mContentResolver.query(uri, PROJECTION_PHONE, Phone.TYPE + '=' + Phone.TYPE_MOBILE + " OR " + Phone.TYPE + '=' + Phone.TYPE_WORK_MOBILE, null, SORT_ORDER); if (phone.length() > 0) { ArrayList result = new ArrayList(); result.add(Integer.valueOf(-1)); // ID result.add(Long.valueOf(-1)); // PERSON_ID result.add(Integer.valueOf(Phone.TYPE_CUSTOM)); // TYPE result.add(phone); // NUMBER /* * The "\u00A0" keeps Phone.getDisplayLabel() from deciding * to display the default label ("Home") next to the transformation * of the letters into numbers. */ result.add("\u00A0"); // LABEL result.add(cons); // NAME ArrayList<ArrayList> wrap = new ArrayList<ArrayList>(); wrap.add(result); ArrayListCursor translated = new ArrayListCursor(PROJECTION_PHONE, wrap); return new MergeCursor(new Cursor[] { translated, phoneCursor }); } else { return phoneCursor; } }
diff --git a/atlas-web/src/test/java/uk/ac/ebi/gxa/requesthandlers/experimentpage/SimilarGeneListTest.java b/atlas-web/src/test/java/uk/ac/ebi/gxa/requesthandlers/experimentpage/SimilarGeneListTest.java index 7509e9432..9140227db 100644 --- a/atlas-web/src/test/java/uk/ac/ebi/gxa/requesthandlers/experimentpage/SimilarGeneListTest.java +++ b/atlas-web/src/test/java/uk/ac/ebi/gxa/requesthandlers/experimentpage/SimilarGeneListTest.java @@ -1,125 +1,126 @@ /* * Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute * * 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. * * * For further details of the Gene Expression Atlas project, including source code, * downloads and documentation, please see: * * http://gxa.github.com/gxa */ package uk.ac.ebi.gxa.requesthandlers.experimentpage; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import uk.ac.ebi.gxa.R.AtlasRFactory; import uk.ac.ebi.gxa.R.AtlasRFactoryBuilder; import uk.ac.ebi.gxa.analytics.compute.AtlasComputeService; import uk.ac.ebi.gxa.analytics.compute.ComputeException; import uk.ac.ebi.gxa.analytics.compute.ComputeTask; import uk.ac.ebi.gxa.requesthandlers.experimentpage.result.SimilarityResultSet; import uk.ac.ebi.rcloud.server.RServices; import uk.ac.ebi.rcloud.server.RType.RDataFrame; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.rmi.RemoteException; import java.util.ArrayList; /** * Javadocs go here! * * @author Tony Burdett * @date 17-Nov-2009 */ public class SimilarGeneListTest extends TestCase { private AtlasComputeService svc; @Before public void setUp() { try { // build default rFactory - reads R.properties from classpath AtlasRFactory rFactory = AtlasRFactoryBuilder.getAtlasRFactoryBuilder().buildAtlasRFactory(); // build service svc = new AtlasComputeService(); svc.setAtlasRFactory(rFactory); } catch (Exception e) { e.printStackTrace(); fail("Caught exception whilst setting up"); } } @After public void tearDown() { svc.shutdown(); } @Test public void testComputeSimilarityTask() { // do a similarity over E-AFMX-5 for an arbitrary design element/array design - final SimilarityResultSet simRS = new SimilarityResultSet("226010852", "153094131", "153069949"); + // TODO: fix similarity result test! + final SimilarityResultSet simRS = new SimilarityResultSet("226010852", "153094131", "153069949", ""); final String callSim = "sim.nc(" + simRS.getTargetDesignElementId() + ",'" + simRS.getSourceNetCDF() + "')"; RDataFrame sim = null; try { sim = svc.computeTask(new ComputeTask<RDataFrame>() { public RDataFrame compute(RServices R) throws RemoteException { try { R.sourceFromBuffer(getRCodeFromResource("sim.R")); } catch (IOException e) { fail("Couldn't read sim.R"); } return (RDataFrame) R.getObject(callSim); } }); } catch (ComputeException e) { fail("Failed calling: " + callSim + "\n" + e.getMessage()); e.printStackTrace(); } if (null != sim) { simRS.loadResult(sim); ArrayList<String> simGeneIds = simRS.getSimGeneIDs(); assertEquals(simGeneIds.get(0), "153069988"); } else { fail("Similarity search returned null"); } } private String getRCodeFromResource(String resourcePath) throws IOException { // open a stream to the resource InputStream in = getClass().getClassLoader().getResourceAsStream(resourcePath); // create a reader to read in code BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } in.close(); return sb.toString(); } }
true
true
public void testComputeSimilarityTask() { // do a similarity over E-AFMX-5 for an arbitrary design element/array design final SimilarityResultSet simRS = new SimilarityResultSet("226010852", "153094131", "153069949"); final String callSim = "sim.nc(" + simRS.getTargetDesignElementId() + ",'" + simRS.getSourceNetCDF() + "')"; RDataFrame sim = null; try { sim = svc.computeTask(new ComputeTask<RDataFrame>() { public RDataFrame compute(RServices R) throws RemoteException { try { R.sourceFromBuffer(getRCodeFromResource("sim.R")); } catch (IOException e) { fail("Couldn't read sim.R"); } return (RDataFrame) R.getObject(callSim); } }); } catch (ComputeException e) { fail("Failed calling: " + callSim + "\n" + e.getMessage()); e.printStackTrace(); } if (null != sim) { simRS.loadResult(sim); ArrayList<String> simGeneIds = simRS.getSimGeneIDs(); assertEquals(simGeneIds.get(0), "153069988"); } else { fail("Similarity search returned null"); } }
public void testComputeSimilarityTask() { // do a similarity over E-AFMX-5 for an arbitrary design element/array design // TODO: fix similarity result test! final SimilarityResultSet simRS = new SimilarityResultSet("226010852", "153094131", "153069949", ""); final String callSim = "sim.nc(" + simRS.getTargetDesignElementId() + ",'" + simRS.getSourceNetCDF() + "')"; RDataFrame sim = null; try { sim = svc.computeTask(new ComputeTask<RDataFrame>() { public RDataFrame compute(RServices R) throws RemoteException { try { R.sourceFromBuffer(getRCodeFromResource("sim.R")); } catch (IOException e) { fail("Couldn't read sim.R"); } return (RDataFrame) R.getObject(callSim); } }); } catch (ComputeException e) { fail("Failed calling: " + callSim + "\n" + e.getMessage()); e.printStackTrace(); } if (null != sim) { simRS.loadResult(sim); ArrayList<String> simGeneIds = simRS.getSimGeneIDs(); assertEquals(simGeneIds.get(0), "153069988"); } else { fail("Similarity search returned null"); } }
diff --git a/Basics/src/coolawesomeme/basics_plugin/commands/TPRCommand.java b/Basics/src/coolawesomeme/basics_plugin/commands/TPRCommand.java index 77777f9..677e90d 100644 --- a/Basics/src/coolawesomeme/basics_plugin/commands/TPRCommand.java +++ b/Basics/src/coolawesomeme/basics_plugin/commands/TPRCommand.java @@ -1,140 +1,140 @@ package coolawesomeme.basics_plugin.commands; import java.util.HashMap; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import coolawesomeme.basics_plugin.Basics; import coolawesomeme.basics_plugin.MinecraftColors; public class TPRCommand implements CommandExecutor{ private Basics basics; private HashMap<Player, Player> pendingTeleports = new HashMap<Player, Player>(); private boolean requests = Basics.teleportRequests; public TPRCommand(Basics instance){ basics = instance; } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(!(sender instanceof Player)){ if(args.length == 2){ if(Bukkit.getPlayer(args[0]) == null || Bukkit.getPlayer(args[0]).equals(null)){ sender.sendMessage(MinecraftColors.red + "Player" + args[0] + " not found!"); }else{ if((Bukkit.getPlayer(args[1]) == null || Bukkit.getPlayer(args[1]).equals(null))){ sender.sendMessage(MinecraftColors.red + "Player " + args[1] + " not found!"); }else{ Bukkit.getPlayer(args[0]).teleport(Bukkit.getPlayer(args[1])); } } return true; }else if(args.length > 2){ sender.sendMessage("Invalid command syntax!"); return false; }else if(args.length < 2){ sender.sendMessage("You must be a player to do that!"); return false; } }else{ if(args.length == 1){ if(args[0].equalsIgnoreCase("a") || args[0].equalsIgnoreCase("accept")){ Player target = Bukkit.getPlayer(sender.getName()); if(pendingTeleports.containsKey(target)){ Player originalSender = pendingTeleports.get(target); if(originalSender == null || originalSender.equals(null)){ target.sendMessage(target.getName() + MinecraftColors.red + " is not currently online!"); target.sendMessage(MinecraftColors.red + "Request failed!"); }else{ originalSender.sendMessage(MinecraftColors.green + "Teleport request accepted!"); originalSender.sendMessage(MinecraftColors.green + "Teleporting..."); originalSender.teleport(target); } pendingTeleports.remove(target); }else{ sender.sendMessage(MinecraftColors.red + "You have no pending teleports!"); } return true; }else if(args[0].equalsIgnoreCase("d") || args[0].equalsIgnoreCase("decline")){ Player target = Bukkit.getPlayer(sender.getName()); if(pendingTeleports.containsKey(target)){ Player originalSender = pendingTeleports.get(target); if(originalSender == null || originalSender.equals(null)){ }else{ originalSender.sendMessage(MinecraftColors.red + "Your teleport request has been denied."); } pendingTeleports.remove(target); }else{ sender.sendMessage(MinecraftColors.red + "You have no pending teleports!"); } return true; }else if(args[0].equalsIgnoreCase("setrequest")){ if(sender.isOp() || sender.hasPermission("basics.tpr.setrequest")){ basics.getConfig().set("teleport-requests", Boolean.parseBoolean(args[1])); }else{ sender.sendMessage("You must be OP/ Admin to do that!"); } return true; }else{ Player target = Bukkit.getPlayer(args[0]); if(target == null || target.equals(null)){ sender.sendMessage(MinecraftColors.red + "Player " + args[0] + " not found!"); }else{ if(this.requests){ if(pendingTeleports.containsKey(target)){ pendingTeleports.remove(target); } pendingTeleports.put(target, Bukkit.getPlayer(sender.getName())); - sender.sendMessage("Teleport request send to " + target.getName()); + sender.sendMessage("Teleport request sent to " + target.getName()); target.sendMessage(MinecraftColors.red + sender.getName() + " would like to teleport to you."); target.sendMessage(MinecraftColors.red + "Type /tpr a or /tpr d, to accept or decline, respectfully."); }else{ sender.sendMessage("Teleporting..."); Bukkit.getPlayer(sender.getName()).teleport(target); } } return true; } }else if(args.length == 2){ if(Bukkit.getPlayer(args[0]) == null || Bukkit.getPlayer(args[0]).equals(null)){ sender.sendMessage(MinecraftColors.red + "Player" + args[0] + " not found!"); }else{ if((Bukkit.getPlayer(args[1]) == null || Bukkit.getPlayer(args[1]).equals(null))){ sender.sendMessage(MinecraftColors.red + "Player " + args[1] + " not found!"); }else{ Player target = Bukkit.getPlayer(args[1]); Player teleportee = Bukkit.getPlayer(args[0]); if(this.requests){ if(pendingTeleports.containsKey(target)){ pendingTeleports.remove(target); } pendingTeleports.put(target, teleportee); sender.sendMessage("Teleport request send to " + target.getName() + " for " + args[0]); teleportee.sendMessage("Teleport request send to " + target.getName() + " for you by " + sender.getName()); target.sendMessage(MinecraftColors.red + sender.getName() + " would like to teleport to you."); target.sendMessage(MinecraftColors.red + "Type /tpr a or /tpr d, to accept or decline, respectfully."); }else{ sender.sendMessage("Teleporting " + args[0] + "..."); teleportee.sendMessage("Teleporting to " + args[1] + " for " + sender.getName() + "..."); Bukkit.getPlayer(sender.getName()).teleport(target); } } } return true; }else if(args.length < 1){ sender.sendMessage("Invalid command syntax!"); return false; }else if(args.length > 2){ sender.sendMessage("Invalid command syntax!"); return false; } } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(!(sender instanceof Player)){ if(args.length == 2){ if(Bukkit.getPlayer(args[0]) == null || Bukkit.getPlayer(args[0]).equals(null)){ sender.sendMessage(MinecraftColors.red + "Player" + args[0] + " not found!"); }else{ if((Bukkit.getPlayer(args[1]) == null || Bukkit.getPlayer(args[1]).equals(null))){ sender.sendMessage(MinecraftColors.red + "Player " + args[1] + " not found!"); }else{ Bukkit.getPlayer(args[0]).teleport(Bukkit.getPlayer(args[1])); } } return true; }else if(args.length > 2){ sender.sendMessage("Invalid command syntax!"); return false; }else if(args.length < 2){ sender.sendMessage("You must be a player to do that!"); return false; } }else{ if(args.length == 1){ if(args[0].equalsIgnoreCase("a") || args[0].equalsIgnoreCase("accept")){ Player target = Bukkit.getPlayer(sender.getName()); if(pendingTeleports.containsKey(target)){ Player originalSender = pendingTeleports.get(target); if(originalSender == null || originalSender.equals(null)){ target.sendMessage(target.getName() + MinecraftColors.red + " is not currently online!"); target.sendMessage(MinecraftColors.red + "Request failed!"); }else{ originalSender.sendMessage(MinecraftColors.green + "Teleport request accepted!"); originalSender.sendMessage(MinecraftColors.green + "Teleporting..."); originalSender.teleport(target); } pendingTeleports.remove(target); }else{ sender.sendMessage(MinecraftColors.red + "You have no pending teleports!"); } return true; }else if(args[0].equalsIgnoreCase("d") || args[0].equalsIgnoreCase("decline")){ Player target = Bukkit.getPlayer(sender.getName()); if(pendingTeleports.containsKey(target)){ Player originalSender = pendingTeleports.get(target); if(originalSender == null || originalSender.equals(null)){ }else{ originalSender.sendMessage(MinecraftColors.red + "Your teleport request has been denied."); } pendingTeleports.remove(target); }else{ sender.sendMessage(MinecraftColors.red + "You have no pending teleports!"); } return true; }else if(args[0].equalsIgnoreCase("setrequest")){ if(sender.isOp() || sender.hasPermission("basics.tpr.setrequest")){ basics.getConfig().set("teleport-requests", Boolean.parseBoolean(args[1])); }else{ sender.sendMessage("You must be OP/ Admin to do that!"); } return true; }else{ Player target = Bukkit.getPlayer(args[0]); if(target == null || target.equals(null)){ sender.sendMessage(MinecraftColors.red + "Player " + args[0] + " not found!"); }else{ if(this.requests){ if(pendingTeleports.containsKey(target)){ pendingTeleports.remove(target); } pendingTeleports.put(target, Bukkit.getPlayer(sender.getName())); sender.sendMessage("Teleport request send to " + target.getName()); target.sendMessage(MinecraftColors.red + sender.getName() + " would like to teleport to you."); target.sendMessage(MinecraftColors.red + "Type /tpr a or /tpr d, to accept or decline, respectfully."); }else{ sender.sendMessage("Teleporting..."); Bukkit.getPlayer(sender.getName()).teleport(target); } } return true; } }else if(args.length == 2){ if(Bukkit.getPlayer(args[0]) == null || Bukkit.getPlayer(args[0]).equals(null)){ sender.sendMessage(MinecraftColors.red + "Player" + args[0] + " not found!"); }else{ if((Bukkit.getPlayer(args[1]) == null || Bukkit.getPlayer(args[1]).equals(null))){ sender.sendMessage(MinecraftColors.red + "Player " + args[1] + " not found!"); }else{ Player target = Bukkit.getPlayer(args[1]); Player teleportee = Bukkit.getPlayer(args[0]); if(this.requests){ if(pendingTeleports.containsKey(target)){ pendingTeleports.remove(target); } pendingTeleports.put(target, teleportee); sender.sendMessage("Teleport request send to " + target.getName() + " for " + args[0]); teleportee.sendMessage("Teleport request send to " + target.getName() + " for you by " + sender.getName()); target.sendMessage(MinecraftColors.red + sender.getName() + " would like to teleport to you."); target.sendMessage(MinecraftColors.red + "Type /tpr a or /tpr d, to accept or decline, respectfully."); }else{ sender.sendMessage("Teleporting " + args[0] + "..."); teleportee.sendMessage("Teleporting to " + args[1] + " for " + sender.getName() + "..."); Bukkit.getPlayer(sender.getName()).teleport(target); } } } return true; }else if(args.length < 1){ sender.sendMessage("Invalid command syntax!"); return false; }else if(args.length > 2){ sender.sendMessage("Invalid command syntax!"); return false; } } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(!(sender instanceof Player)){ if(args.length == 2){ if(Bukkit.getPlayer(args[0]) == null || Bukkit.getPlayer(args[0]).equals(null)){ sender.sendMessage(MinecraftColors.red + "Player" + args[0] + " not found!"); }else{ if((Bukkit.getPlayer(args[1]) == null || Bukkit.getPlayer(args[1]).equals(null))){ sender.sendMessage(MinecraftColors.red + "Player " + args[1] + " not found!"); }else{ Bukkit.getPlayer(args[0]).teleport(Bukkit.getPlayer(args[1])); } } return true; }else if(args.length > 2){ sender.sendMessage("Invalid command syntax!"); return false; }else if(args.length < 2){ sender.sendMessage("You must be a player to do that!"); return false; } }else{ if(args.length == 1){ if(args[0].equalsIgnoreCase("a") || args[0].equalsIgnoreCase("accept")){ Player target = Bukkit.getPlayer(sender.getName()); if(pendingTeleports.containsKey(target)){ Player originalSender = pendingTeleports.get(target); if(originalSender == null || originalSender.equals(null)){ target.sendMessage(target.getName() + MinecraftColors.red + " is not currently online!"); target.sendMessage(MinecraftColors.red + "Request failed!"); }else{ originalSender.sendMessage(MinecraftColors.green + "Teleport request accepted!"); originalSender.sendMessage(MinecraftColors.green + "Teleporting..."); originalSender.teleport(target); } pendingTeleports.remove(target); }else{ sender.sendMessage(MinecraftColors.red + "You have no pending teleports!"); } return true; }else if(args[0].equalsIgnoreCase("d") || args[0].equalsIgnoreCase("decline")){ Player target = Bukkit.getPlayer(sender.getName()); if(pendingTeleports.containsKey(target)){ Player originalSender = pendingTeleports.get(target); if(originalSender == null || originalSender.equals(null)){ }else{ originalSender.sendMessage(MinecraftColors.red + "Your teleport request has been denied."); } pendingTeleports.remove(target); }else{ sender.sendMessage(MinecraftColors.red + "You have no pending teleports!"); } return true; }else if(args[0].equalsIgnoreCase("setrequest")){ if(sender.isOp() || sender.hasPermission("basics.tpr.setrequest")){ basics.getConfig().set("teleport-requests", Boolean.parseBoolean(args[1])); }else{ sender.sendMessage("You must be OP/ Admin to do that!"); } return true; }else{ Player target = Bukkit.getPlayer(args[0]); if(target == null || target.equals(null)){ sender.sendMessage(MinecraftColors.red + "Player " + args[0] + " not found!"); }else{ if(this.requests){ if(pendingTeleports.containsKey(target)){ pendingTeleports.remove(target); } pendingTeleports.put(target, Bukkit.getPlayer(sender.getName())); sender.sendMessage("Teleport request sent to " + target.getName()); target.sendMessage(MinecraftColors.red + sender.getName() + " would like to teleport to you."); target.sendMessage(MinecraftColors.red + "Type /tpr a or /tpr d, to accept or decline, respectfully."); }else{ sender.sendMessage("Teleporting..."); Bukkit.getPlayer(sender.getName()).teleport(target); } } return true; } }else if(args.length == 2){ if(Bukkit.getPlayer(args[0]) == null || Bukkit.getPlayer(args[0]).equals(null)){ sender.sendMessage(MinecraftColors.red + "Player" + args[0] + " not found!"); }else{ if((Bukkit.getPlayer(args[1]) == null || Bukkit.getPlayer(args[1]).equals(null))){ sender.sendMessage(MinecraftColors.red + "Player " + args[1] + " not found!"); }else{ Player target = Bukkit.getPlayer(args[1]); Player teleportee = Bukkit.getPlayer(args[0]); if(this.requests){ if(pendingTeleports.containsKey(target)){ pendingTeleports.remove(target); } pendingTeleports.put(target, teleportee); sender.sendMessage("Teleport request send to " + target.getName() + " for " + args[0]); teleportee.sendMessage("Teleport request send to " + target.getName() + " for you by " + sender.getName()); target.sendMessage(MinecraftColors.red + sender.getName() + " would like to teleport to you."); target.sendMessage(MinecraftColors.red + "Type /tpr a or /tpr d, to accept or decline, respectfully."); }else{ sender.sendMessage("Teleporting " + args[0] + "..."); teleportee.sendMessage("Teleporting to " + args[1] + " for " + sender.getName() + "..."); Bukkit.getPlayer(sender.getName()).teleport(target); } } } return true; }else if(args.length < 1){ sender.sendMessage("Invalid command syntax!"); return false; }else if(args.length > 2){ sender.sendMessage("Invalid command syntax!"); return false; } } return false; }
diff --git a/hot-deploy/warehouse/src/org/opentaps/warehouse/facility/UtilWarehouse.java b/hot-deploy/warehouse/src/org/opentaps/warehouse/facility/UtilWarehouse.java index 8d1f162c0..23294f2fd 100644 --- a/hot-deploy/warehouse/src/org/opentaps/warehouse/facility/UtilWarehouse.java +++ b/hot-deploy/warehouse/src/org/opentaps/warehouse/facility/UtilWarehouse.java @@ -1,119 +1,131 @@ /* * Copyright (c) 2006 - 2009 Open Source Strategies, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the Honest Public License. * * 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 * Honest Public License for more details. * * You should have received a copy of the Honest Public License * along with this program; if not, write to Funambol, * 643 Bair Island Road, Suite 305 - Redwood City, CA 94063, USA */ package org.opentaps.warehouse.facility; import java.util.List; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.condition.EntityCondition; import org.ofbiz.entity.condition.EntityOperator; /** * UtilWarehouse. */ public final class UtilWarehouse { private UtilWarehouse() { } private static String MODULE = UtilWarehouse.class.getName(); /** * Copy of the bsh located at * component://product/webapp/facility/WEB-INF/actions/facility/FindFacilityTransfers.bsh. * * @param facilityId The Id of the warehouse to look on * @param activeOnly If true, get all the transfers which are not completed and not canceled, else get all the transfers * @param completeRequested If true, get all the requested transfers * @param toTransfer If true, get the toTransfer list else get the fromTransfer list * @param delegator The delegator object to look up on * @return The list of the transfers elements */ public static List<GenericValue> findFacilityTransfer(String facilityId, boolean activeOnly, boolean completeRequested, boolean toTransfer, GenericDelegator delegator) throws GenericEntityException { if (facilityId == null) { return null; } GenericValue facility = delegator.findByPrimaryKey("Facility", UtilMisc.toMap("facilityId", facilityId)); if (facility == null) { return null; } if (toTransfer) { // get the 'to' this facility transfers EntityCondition exprsTo = null; if (activeOnly) { - exprsTo = EntityCondition.makeCondition(EntityCondition.makeCondition("facilityIdTo", EntityOperator.EQUALS, facilityId), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "IXF_COMPLETE"), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "IXF_CANCELLED")); + exprsTo = EntityCondition.makeCondition(EntityOperator.AND, + EntityCondition.makeCondition("facilityIdTo", EntityOperator.EQUALS, facilityId), + EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "IXF_COMPLETE"), + EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "IXF_CANCELLED")); } else { - exprsTo = EntityCondition.makeCondition(EntityCondition.makeCondition("facilityIdTo", EntityOperator.EQUALS, facilityId)); + exprsTo = EntityCondition.makeCondition(EntityOperator.AND, + EntityCondition.makeCondition("facilityIdTo", EntityOperator.EQUALS, facilityId)); } if (completeRequested) { - exprsTo = EntityCondition.makeCondition(EntityCondition.makeCondition("facilityIdTo", EntityOperator.EQUALS, facilityId), EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "IXF_REQUESTED")); + exprsTo = EntityCondition.makeCondition(EntityOperator.AND, + EntityCondition.makeCondition("facilityIdTo", EntityOperator.EQUALS, facilityId), + EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "IXF_REQUESTED")); } return delegator.findByAnd("InventoryTransfer", exprsTo, UtilMisc.toList("sendDate")); } else { // get the 'from' this facility transfers EntityCondition exprsFrom = null; if (activeOnly) { - exprsFrom = EntityCondition.makeCondition(EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "IXF_COMPLETE"), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "IXF_CANCELLED")); + exprsFrom = EntityCondition.makeCondition(EntityOperator.AND, + EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId), + EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "IXF_COMPLETE"), + EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "IXF_CANCELLED")); } else { - exprsFrom = EntityCondition.makeCondition(EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId)); + exprsFrom = EntityCondition.makeCondition(EntityOperator.AND, + EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId)); } if (completeRequested) { - exprsFrom = EntityCondition.makeCondition(EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId), EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "IXF_REQUESTED")); + exprsFrom = EntityCondition.makeCondition(EntityOperator.AND, + EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId), + EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "IXF_REQUESTED")); } return delegator.findByAnd("InventoryTransfer", exprsFrom, UtilMisc.toList("sendDate")); } } /** * Conveniance method to call findFacilityTransfer. * * @param facilityId The Id of the warehouse to look on * @param delegator The delegator object to look up on * @return The list of the transfers elements */ public static List<GenericValue> findFacilitytoTransfer(String facilityId, GenericDelegator delegator) throws GenericEntityException { return UtilWarehouse.findFacilityTransfer(facilityId, false, false, true, delegator); } public static List<GenericValue> findFacilityfromTransfer(String facilityId, GenericDelegator delegator) throws GenericEntityException { return UtilWarehouse.findFacilityTransfer(facilityId, false, false, false, delegator); } public static List<GenericValue> findFacilityActiveOnlytoTransfer(String facilityId, GenericDelegator delegator) throws GenericEntityException { return UtilWarehouse.findFacilityTransfer(facilityId, true, false, true, delegator); } public static List<GenericValue> findFacilityActiveOnlyfromTransfer(String facilityId, GenericDelegator delegator) throws GenericEntityException { return UtilWarehouse.findFacilityTransfer(facilityId, true, false, false, delegator); } public static List<GenericValue> findFacilityCompleteReqtoTransfer(String facilityId, GenericDelegator delegator) throws GenericEntityException { return UtilWarehouse.findFacilityTransfer(facilityId, false, true, true, delegator); } public static List<GenericValue> findFacilityCompleteReqfromTransfer(String facilityId, GenericDelegator delegator) throws GenericEntityException { return UtilWarehouse.findFacilityTransfer(facilityId, false, true, false, delegator); } }
false
true
public static List<GenericValue> findFacilityTransfer(String facilityId, boolean activeOnly, boolean completeRequested, boolean toTransfer, GenericDelegator delegator) throws GenericEntityException { if (facilityId == null) { return null; } GenericValue facility = delegator.findByPrimaryKey("Facility", UtilMisc.toMap("facilityId", facilityId)); if (facility == null) { return null; } if (toTransfer) { // get the 'to' this facility transfers EntityCondition exprsTo = null; if (activeOnly) { exprsTo = EntityCondition.makeCondition(EntityCondition.makeCondition("facilityIdTo", EntityOperator.EQUALS, facilityId), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "IXF_COMPLETE"), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "IXF_CANCELLED")); } else { exprsTo = EntityCondition.makeCondition(EntityCondition.makeCondition("facilityIdTo", EntityOperator.EQUALS, facilityId)); } if (completeRequested) { exprsTo = EntityCondition.makeCondition(EntityCondition.makeCondition("facilityIdTo", EntityOperator.EQUALS, facilityId), EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "IXF_REQUESTED")); } return delegator.findByAnd("InventoryTransfer", exprsTo, UtilMisc.toList("sendDate")); } else { // get the 'from' this facility transfers EntityCondition exprsFrom = null; if (activeOnly) { exprsFrom = EntityCondition.makeCondition(EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "IXF_COMPLETE"), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "IXF_CANCELLED")); } else { exprsFrom = EntityCondition.makeCondition(EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId)); } if (completeRequested) { exprsFrom = EntityCondition.makeCondition(EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId), EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "IXF_REQUESTED")); } return delegator.findByAnd("InventoryTransfer", exprsFrom, UtilMisc.toList("sendDate")); } }
public static List<GenericValue> findFacilityTransfer(String facilityId, boolean activeOnly, boolean completeRequested, boolean toTransfer, GenericDelegator delegator) throws GenericEntityException { if (facilityId == null) { return null; } GenericValue facility = delegator.findByPrimaryKey("Facility", UtilMisc.toMap("facilityId", facilityId)); if (facility == null) { return null; } if (toTransfer) { // get the 'to' this facility transfers EntityCondition exprsTo = null; if (activeOnly) { exprsTo = EntityCondition.makeCondition(EntityOperator.AND, EntityCondition.makeCondition("facilityIdTo", EntityOperator.EQUALS, facilityId), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "IXF_COMPLETE"), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "IXF_CANCELLED")); } else { exprsTo = EntityCondition.makeCondition(EntityOperator.AND, EntityCondition.makeCondition("facilityIdTo", EntityOperator.EQUALS, facilityId)); } if (completeRequested) { exprsTo = EntityCondition.makeCondition(EntityOperator.AND, EntityCondition.makeCondition("facilityIdTo", EntityOperator.EQUALS, facilityId), EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "IXF_REQUESTED")); } return delegator.findByAnd("InventoryTransfer", exprsTo, UtilMisc.toList("sendDate")); } else { // get the 'from' this facility transfers EntityCondition exprsFrom = null; if (activeOnly) { exprsFrom = EntityCondition.makeCondition(EntityOperator.AND, EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "IXF_COMPLETE"), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "IXF_CANCELLED")); } else { exprsFrom = EntityCondition.makeCondition(EntityOperator.AND, EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId)); } if (completeRequested) { exprsFrom = EntityCondition.makeCondition(EntityOperator.AND, EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId), EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "IXF_REQUESTED")); } return delegator.findByAnd("InventoryTransfer", exprsFrom, UtilMisc.toList("sendDate")); } }
diff --git a/source/trunk/plugins/org.marketcetera.photon/src/main/java/org/marketcetera/photon/views/OptionSeriesManager.java b/source/trunk/plugins/org.marketcetera.photon/src/main/java/org/marketcetera/photon/views/OptionSeriesManager.java index 448e18daf..ffdbe0e49 100644 --- a/source/trunk/plugins/org.marketcetera.photon/src/main/java/org/marketcetera/photon/views/OptionSeriesManager.java +++ b/source/trunk/plugins/org.marketcetera.photon/src/main/java/org/marketcetera/photon/views/OptionSeriesManager.java @@ -1,464 +1,465 @@ package org.marketcetera.photon.views; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Text; import org.marketcetera.core.MSymbol; import org.marketcetera.core.MarketceteraException; import org.marketcetera.photon.PhotonPlugin; import org.marketcetera.photon.marketdata.IMarketDataListCallback; import org.marketcetera.photon.marketdata.MarketDataFeedService; import org.marketcetera.photon.marketdata.MarketDataFeedTracker; import org.marketcetera.photon.marketdata.OptionContractData; import org.marketcetera.photon.marketdata.OptionMarketDataUtils; import org.marketcetera.photon.ui.ToggledListener; import org.marketcetera.quickfix.FIXMessageUtil; import org.marketcetera.quickfix.MarketceteraFIXException; import quickfix.FieldNotFound; import quickfix.Message; import quickfix.StringField; import quickfix.field.MsgType; import quickfix.field.NoRelatedSym; import quickfix.field.UnderlyingSymbol; import quickfix.fix44.DerivativeSecurityList; public class OptionSeriesManager implements IMarketDataListCallback { IOptionOrderTicket ticket; /** * Map from option root symbol to cache entry. */ private HashMap<String, OptionSeriesCollection> optionContractCache = new HashMap<String, OptionSeriesCollection>(); private HashMap<MSymbol, OptionContractData> symbolToContractMap = new HashMap<MSymbol, OptionContractData>(); private String lastOptionRoot; private List<String> putOrCallComboChoices = new ArrayList<String>(); private List<ToggledListener> optionSpecifierModifyListeners; private ToggledListener optionContractSymbolModifyListener; private MarketDataFeedTracker marketDataTracker; public OptionSeriesManager(IOptionOrderTicket ticket) { this.ticket = ticket; initPutOrCallComboChoices(); marketDataTracker = new MarketDataFeedTracker( PhotonPlugin.getDefault().getBundleContext()); marketDataTracker.open(); initListeners(); } public void initListeners(){ optionSpecifierModifyListeners = new ArrayList<ToggledListener>(); addOptionSeriesInfoModifyListener(ticket.getExpireYearCombo()); addOptionSeriesInfoModifyListener(ticket.getExpireMonthCombo()); addOptionSeriesInfoModifyListener(ticket.getStrikePriceControl()); addOptionSeriesInfoModifyListener(ticket.getPutOrCallCombo()); /** * This modify listener ensures that the option contract specifiers * (month, year, strike, put/call) stay in sync when the user enters an * option contract symbol (MSQ+HA) directly. */ optionContractSymbolModifyListener = new ToggledListener() { @Override protected void handleEventWhenEnabled(Event event) { try { setOptionSeriesInfoListenersEnabled(false); updateOptionSeriesInfoForSymbol(ticket.getOptionSymbolControl().getText()); } finally { setOptionSeriesInfoListenersEnabled(true); } } }; optionContractSymbolModifyListener.setEnabled(true); ticket.getOptionSymbolControl().addListener(SWT.Modify, optionContractSymbolModifyListener); ticket.getSymbolText().addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { } public void focusLost(FocusEvent e) { String requestSymbol = ((Text)e.getSource()).getText(); if (OptionMarketDataUtils.isOptionSymbol(requestSymbol)){ requestSymbol = OptionMarketDataUtils.getOptionRootSymbol(requestSymbol); } requestOptionRootInfo(requestSymbol); - try { - optionContractSymbolModifyListener.setEnabled(false); - ticket.getOptionSymbolControl().setText(requestSymbol); - } finally { - optionContractSymbolModifyListener.setEnabled(true); - } + // Looks like the following code was causing: http://trac.marketcetera.org/trac.fcgi/ticket/327 +// try { +// optionContractSymbolModifyListener.setEnabled(false); +// ticket.getOptionSymbolControl().setText(requestSymbol); +// } finally { +// optionContractSymbolModifyListener.setEnabled(true); +// } } }); } /** * Update the option series details (expiration etc.) based on the * option contract symbol (e.g. MSQ+GE). */ private void updateOptionSeriesInfoForSymbol(String optionSymbolText) { if (optionSymbolText == null || optionSymbolText.length() == 0) { return; } MSymbol optionContractSymbol = new MSymbol( optionSymbolText); if (symbolToContractMap.containsKey(optionContractSymbol)) { OptionContractData optionInfo = symbolToContractMap.get(optionContractSymbol); if (optionInfo != null) { String expirationYear = optionInfo.getExpirationYearUIString(); ticket.getExpireYearCombo().setText(expirationYear); String expirationMonth = optionInfo.getExpirationMonthUIString(); ticket.getExpireMonthCombo().setText(expirationMonth); String strikePrice = optionInfo.getStrikePriceUIString(); ticket.getStrikePriceControl().setText(strikePrice); Integer optionIsPut = optionInfo.getPutOrCall(); ticket.setPutOrCall(optionIsPut); } } } /** * Update the option symbol (e.g. MSQ+GE) based on the option specifiers * (expiration etc.) */ private boolean updateOptionSymbol( OptionSeriesCollection cacheEntry) { String expirationYear = ticket.getExpireYearCombo().getText(); String expirationMonth = ticket.getExpireMonthCombo().getText(); String strikePrice = ticket.getStrikePriceControl().getText(); Integer putOrCall = ticket.getPutOrCall(); String optionRoot = ticket.getSymbolText().getText(); boolean textWasSet = false; OptionContractData optionContract = cacheEntry.getOptionContractData( optionRoot, expirationYear, expirationMonth, strikePrice, putOrCall); if (optionContract != null) { MSymbol optionContractSymbol = optionContract.getOptionSymbol(); if (optionContractSymbol != null) { String fullSymbol = optionContractSymbol.getFullSymbol(); try { optionContractSymbolModifyListener.setEnabled(false); ticket.getOptionSymbolControl().setText(fullSymbol); textWasSet = true; } finally { optionContractSymbolModifyListener.setEnabled(true); } } } if (!textWasSet) { clearOptionSymbolControl(); } return textWasSet; } /** * Only update the option contract symbol (e.g. MSQ+GE) based on the option * info (expiration etc.) if there is a mapping available for this * option series. If not, clears the option contract symbol text. */ public void updateOptionSymbolFromLocalCache() { String symbolText = ticket.getSymbolText().getText(); if (symbolText != null) { OptionSeriesCollection cacheEntry = optionContractCache .get(symbolText); if (cacheEntry != null) { updateOptionSymbol(cacheEntry); } } } public void requestOptionRootInfo(String optionRoot) { MarketDataFeedService service = marketDataTracker.getMarketDataFeedService(); if (!optionContractCache.containsKey(optionRoot)) { Message query = OptionMarketDataUtils.newOptionRootQuery(optionRoot); try { service.getMarketDataFeed().asyncQuery(query); } catch (MarketceteraException e) { PhotonPlugin.getDefault().getMarketDataLogger().error("Exception getting market data: "+e); } } else { conditionallyUpdateInputControls(optionRoot); } } // private void requestOptionInfoForUnderlying() { // MarketDataFeedService service = marketDataTracker.getMarketDataFeedService(); // // Message query = null; // // //Returns a query for all option contracts for the underlying symbol // //symbol = underlyingSymbol (e.g. MSFT) // query = OptionMarketDataUtils.newRelatedOptionsQuery(selectedSymbol); // // try { // service.getMarketDataFeed().asyncQuery(query); // } catch (MarketceteraException e) { // PhotonPlugin.getDefault().getMarketDataLogger().error("Exception getting market data: "+e); // } // } private void handleMarketDataList(Message derivativeSecurityList) { String optionRoot = null; try { StringField underlyingSymbolField = derivativeSecurityList.getField(new UnderlyingSymbol()); if(underlyingSymbolField != null) { optionRoot = underlyingSymbolField.getValue(); } } catch(Exception anyException) { PhotonPlugin.getMainConsoleLogger().debug("Failed to find underlying symbol in DerivativeSecurityList: " + derivativeSecurityList, anyException); } if(optionRoot == null || optionRoot.length() == 0) { // todo: Should we throw an exception here? return; } // This old code assumed the derivativeSecurityList coming back // was for the same underlying symbol as the current SymbolText. // // String symbolText = ticket.getSymbolText().getText(); // if (OptionMarketDataUtils.isOptionSymbol(symbolText)){ // symbolText = OptionMarketDataUtils.getOptionRootSymbol(symbolText); // } handleMarketDataList(derivativeSecurityList, optionRoot); } private void handleMarketDataList(Message derivativeSecurityList, String optionRoot) { List<OptionContractData> optionContracts = new ArrayList<OptionContractData>(); try { optionContracts = getOptionExpirationMarketData(optionRoot, derivativeSecurityList); } catch (Exception anyException) { PhotonPlugin.getMainConsoleLogger().warn("Error getting market data - ", anyException); return; } if (optionContracts != null && !optionContracts.isEmpty()) { OptionSeriesCollection cacheEntry = new OptionSeriesCollection( optionContracts); optionContractCache.put(optionRoot, cacheEntry); for (OptionContractData optionContractData : optionContracts) { symbolToContractMap.put( optionContractData.getOptionSymbol(), optionContractData); } conditionallyUpdateInputControls(optionRoot); } } /** * @param symbolFilter * the UnderlyingSymbol in each message is checked to ensure that * it starts with the symbolFilter. Underliers that do not match * are not processed. Specify null to process all messages. * @throws MarketceteraFIXException */ private List<OptionContractData> getOptionExpirationMarketData( final String symbolFilter, Message derivativeSecurityListMessage) throws MarketceteraException { List<OptionContractData> optionExpirations = new ArrayList<OptionContractData>(); if(derivativeSecurityListMessage == null) { return optionExpirations; } String messageUnderlyingSymbolStr = ""; try { if (FIXMessageUtil.isDerivativeSecurityList(derivativeSecurityListMessage)) { messageUnderlyingSymbolStr = derivativeSecurityListMessage .getString(UnderlyingSymbol.FIELD); // if (isApplicableUnderlyingSymbol( // messageUnderlyingSymbolStr, symbolFilter)) { MSymbol messageUnderlyingSymbol = new MSymbol( messageUnderlyingSymbolStr); addExpirationFromMessage(messageUnderlyingSymbol, derivativeSecurityListMessage, optionExpirations); // } } else { throw new MarketceteraFIXException( "FIX message was not a DerivativeSecurityList (" + MsgType.DERIVATIVE_SECURITY_LIST + ")."); } } catch (Exception anyException) { throw new MarketceteraException( "Failed to get option contracts data for underlying symbol \"" + messageUnderlyingSymbolStr + "\" - " + "\nProblematic message is : [" + derivativeSecurityListMessage + "]", anyException); } return optionExpirations; } private void addExpirationFromMessage(MSymbol underlyingSymbol, Message message, List<OptionContractData> optionExpirations) throws FieldNotFound, MarketceteraFIXException { int numDerivs = 0; try { numDerivs = message.getInt(NoRelatedSym.FIELD); } catch (FieldNotFound fnf){ // do nothing... } for (int index = 1; index <= numDerivs; index++) { DerivativeSecurityList.NoRelatedSym optionGroup = new DerivativeSecurityList.NoRelatedSym(); message.getGroup(index, optionGroup); OptionContractData optionData; try { optionData = OptionContractData.fromFieldMap(underlyingSymbol, optionGroup); optionExpirations.add(optionData); } catch (ParseException e) { PhotonPlugin.getDefault().getMarketDataLogger().info(e.getLocalizedMessage()); } } } // private static boolean isApplicableUnderlyingSymbol( // String messageUnderlyingSymbolStr, String symbolFilter) { // if (messageUnderlyingSymbolStr != null) { // if (symbolFilter == null || symbolFilter.trim().length() == 0 // || messageUnderlyingSymbolStr.startsWith(symbolFilter)) { // return true; // } // } // return false; // } private void conditionallyUpdateInputControls(String optionRoot) { if (optionRoot != null && (lastOptionRoot == null || !lastOptionRoot.equals(optionRoot))) { lastOptionRoot = optionRoot; OptionSeriesCollection cacheEntry = optionContractCache .get(optionRoot); if (cacheEntry != null) { updateComboChoices(cacheEntry); updateOptionSymbol(cacheEntry); } } } // private void updateComboChoicesFromDefaults() { // OptionDateHelper dateHelper = new OptionDateHelper(); // List<String> months = dateHelper.createDefaultMonths(); // updateComboChoices(ticket.getExpireMonthCombo(), months); // List<String> years = dateHelper.createDefaultYears(); // updateComboChoices(ticket.getExpireYearCombo(), years); // // todo: What should the defaults be for strike price? // List<String> strikePrices = new ArrayList<String>(); // updateComboChoices(ticket.getStrikePriceControl(), strikePrices); // } private void updateComboChoices(Combo combo, Collection<String> choices) { if (combo == null || combo.isDisposed()) { return; } String originalText = combo.getText(); String newText = ""; combo.removeAll(); boolean first = true; for (String choice : choices) { if (choice != null) { combo.add(choice); // Use the first choice if none match the original text. if (first) { newText = choice; first = false; } if (choice.equals(originalText)) { newText = choice; } } } combo.setText(newText); if (combo.isFocusControl()) { combo.setSelection(new Point(0, 3)); } } private void updateComboChoices(OptionSeriesCollection cacheEntry) { try { setOptionSeriesInfoListenersEnabled(false); updateComboChoices(ticket.getExpireMonthCombo(), cacheEntry .getExpirationMonthsForUI()); updateComboChoices(ticket.getExpireYearCombo(), cacheEntry .getExpirationYearsForUI()); updateComboChoices(ticket.getStrikePriceControl(), cacheEntry .getStrikePricesForUI()); updateComboChoices(ticket.getPutOrCallCombo(), putOrCallComboChoices); } finally { setOptionSeriesInfoListenersEnabled(true); } } private void clearOptionSymbolControl() { ticket.getOptionSymbolControl().setText(ticket.getSymbolText().getText()); } private void addOptionSeriesInfoModifyListener(Control targetControl) { ToggledListener modifyListener = new ToggledListener() { public void handleEventWhenEnabled(Event event) { try { setOptionSeriesInfoListenersEnabled(false); updateOptionSymbolFromLocalCache(); } finally { setOptionSeriesInfoListenersEnabled(true); } } }; optionSpecifierModifyListeners.add(modifyListener); targetControl.addListener(SWT.Modify, modifyListener); } private void setOptionSeriesInfoListenersEnabled(boolean enabled) { for (ToggledListener listener : optionSpecifierModifyListeners) { listener.setEnabled(enabled); } } private void initPutOrCallComboChoices() { Combo combo = ticket.getPutOrCallCombo(); String[] items = combo.getItems(); if(items != null) { putOrCallComboChoices = Arrays.asList(items); } } public void clear() { lastOptionRoot = null; } public void onMarketDataFailure(MSymbol symbol) { } public void onMessage(Message message) { handleMarketDataList(message); } public void onMessages(Message[] messages) { for (Message message : messages) { handleMarketDataList(message); } } }
true
true
public void initListeners(){ optionSpecifierModifyListeners = new ArrayList<ToggledListener>(); addOptionSeriesInfoModifyListener(ticket.getExpireYearCombo()); addOptionSeriesInfoModifyListener(ticket.getExpireMonthCombo()); addOptionSeriesInfoModifyListener(ticket.getStrikePriceControl()); addOptionSeriesInfoModifyListener(ticket.getPutOrCallCombo()); /** * This modify listener ensures that the option contract specifiers * (month, year, strike, put/call) stay in sync when the user enters an * option contract symbol (MSQ+HA) directly. */ optionContractSymbolModifyListener = new ToggledListener() { @Override protected void handleEventWhenEnabled(Event event) { try { setOptionSeriesInfoListenersEnabled(false); updateOptionSeriesInfoForSymbol(ticket.getOptionSymbolControl().getText()); } finally { setOptionSeriesInfoListenersEnabled(true); } } }; optionContractSymbolModifyListener.setEnabled(true); ticket.getOptionSymbolControl().addListener(SWT.Modify, optionContractSymbolModifyListener); ticket.getSymbolText().addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { } public void focusLost(FocusEvent e) { String requestSymbol = ((Text)e.getSource()).getText(); if (OptionMarketDataUtils.isOptionSymbol(requestSymbol)){ requestSymbol = OptionMarketDataUtils.getOptionRootSymbol(requestSymbol); } requestOptionRootInfo(requestSymbol); try { optionContractSymbolModifyListener.setEnabled(false); ticket.getOptionSymbolControl().setText(requestSymbol); } finally { optionContractSymbolModifyListener.setEnabled(true); } } }); }
public void initListeners(){ optionSpecifierModifyListeners = new ArrayList<ToggledListener>(); addOptionSeriesInfoModifyListener(ticket.getExpireYearCombo()); addOptionSeriesInfoModifyListener(ticket.getExpireMonthCombo()); addOptionSeriesInfoModifyListener(ticket.getStrikePriceControl()); addOptionSeriesInfoModifyListener(ticket.getPutOrCallCombo()); /** * This modify listener ensures that the option contract specifiers * (month, year, strike, put/call) stay in sync when the user enters an * option contract symbol (MSQ+HA) directly. */ optionContractSymbolModifyListener = new ToggledListener() { @Override protected void handleEventWhenEnabled(Event event) { try { setOptionSeriesInfoListenersEnabled(false); updateOptionSeriesInfoForSymbol(ticket.getOptionSymbolControl().getText()); } finally { setOptionSeriesInfoListenersEnabled(true); } } }; optionContractSymbolModifyListener.setEnabled(true); ticket.getOptionSymbolControl().addListener(SWT.Modify, optionContractSymbolModifyListener); ticket.getSymbolText().addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { } public void focusLost(FocusEvent e) { String requestSymbol = ((Text)e.getSource()).getText(); if (OptionMarketDataUtils.isOptionSymbol(requestSymbol)){ requestSymbol = OptionMarketDataUtils.getOptionRootSymbol(requestSymbol); } requestOptionRootInfo(requestSymbol); // Looks like the following code was causing: http://trac.marketcetera.org/trac.fcgi/ticket/327 // try { // optionContractSymbolModifyListener.setEnabled(false); // ticket.getOptionSymbolControl().setText(requestSymbol); // } finally { // optionContractSymbolModifyListener.setEnabled(true); // } } }); }
diff --git a/src/ibis/satin/impl/Stats.java b/src/ibis/satin/impl/Stats.java index 4b052ed0..037a6add 100644 --- a/src/ibis/satin/impl/Stats.java +++ b/src/ibis/satin/impl/Stats.java @@ -1,624 +1,624 @@ package ibis.satin.impl; import ibis.util.Timer; public abstract class Stats extends TupleSpace { void initTimers() { if (totalTimer == null) totalTimer = Timer.createTimer(); if (stealTimer == null) stealTimer = Timer.createTimer(); if (handleStealTimer == null) handleStealTimer = Timer.createTimer(); if (abortTimer == null) abortTimer = Timer.createTimer(); if (idleTimer == null) idleTimer = Timer.createTimer(); if (pollTimer == null) pollTimer = Timer.createTimer(); if (tupleTimer == null) tupleTimer = Timer.createTimer(); if (invocationRecordWriteTimer == null) invocationRecordWriteTimer = Timer.createTimer(); if (invocationRecordReadTimer == null) invocationRecordReadTimer = Timer.createTimer(); if (tupleOrderingWaitTimer == null) tupleOrderingWaitTimer = Timer.createTimer(); if (lookupTimer == null) lookupTimer = Timer.createTimer(); if (updateTimer == null) updateTimer = Timer.createTimer(); if (handleUpdateTimer == null) handleUpdateTimer = Timer.createTimer(); if (handleLookupTimer == null) handleLookupTimer = Timer.createTimer(); if (tableSerializationTimer == null) tableSerializationTimer = Timer.createTimer(); if (tableDeserializationTimer == null) tableDeserializationTimer = Timer.createTimer(); if (crashTimer == null) crashTimer = Timer.createTimer(); if (redoTimer == null) redoTimer = Timer.createTimer(); if (addReplicaTimer == null) addReplicaTimer = Timer.createTimer(); } protected StatsMessage createStats() { StatsMessage s = new StatsMessage(); s.spawns = spawns; s.jobsExecuted = jobsExecuted; s.syncs = syncs; s.aborts = aborts; s.abortMessages = abortMessages; s.abortedJobs = abortedJobs; s.stealAttempts = stealAttempts; s.stealSuccess = stealSuccess; s.tupleMsgs = tupleMsgs; s.tupleBytes = tupleBytes; s.stolenJobs = stolenJobs; s.stealRequests = stealRequests; s.interClusterMessages = interClusterMessages; s.intraClusterMessages = intraClusterMessages; s.interClusterBytes = interClusterBytes; s.intraClusterBytes = intraClusterBytes; s.stealTime = stealTimer.totalTimeVal(); s.handleStealTime = handleStealTimer.totalTimeVal(); s.abortTime = abortTimer.totalTimeVal(); s.idleTime = idleTimer.totalTimeVal(); s.idleCount = idleTimer.nrTimes(); s.pollTime = pollTimer.totalTimeVal(); s.pollCount = pollTimer.nrTimes(); s.tupleTime = tupleTimer.totalTimeVal(); s.tupleWaitTime = tupleOrderingWaitTimer.totalTimeVal(); s.tupleWaitCount = tupleOrderingWaitTimer.nrTimes(); s.invocationRecordWriteTime = invocationRecordWriteTimer.totalTimeVal(); s.invocationRecordWriteCount = invocationRecordWriteTimer.nrTimes(); s.invocationRecordReadTime = invocationRecordReadTimer.totalTimeVal(); s.invocationRecordReadCount = invocationRecordReadTimer.nrTimes(); //fault tolerance if (FAULT_TOLERANCE) { s.tableResultUpdates = globalResultTable.numResultUpdates; s.tableLockUpdates = globalResultTable.numLockUpdates; s.tableUpdateMessages = globalResultTable.numUpdateMessages; s.tableLookups = globalResultTable.numLookups; s.tableSuccessfulLookups = globalResultTable.numLookupsSucceded; s.tableRemoteLookups = globalResultTable.numRemoteLookups; s.killedOrphans = killedOrphans; s.restartedJobs = restartedJobs; s.tableLookupTime = lookupTimer.totalTimeVal(); s.tableUpdateTime = updateTimer.totalTimeVal(); s.tableHandleUpdateTime = handleUpdateTimer.totalTimeVal(); s.tableHandleLookupTime = handleLookupTimer.totalTimeVal(); s.tableSerializationTime = tableSerializationTimer.totalTimeVal(); s.tableDeserializationTime = tableDeserializationTimer.totalTimeVal(); s.tableCheckTime = redoTimer.totalTimeVal(); s.crashHandlingTime = crashTimer.totalTimeVal(); s.addReplicaTime = addReplicaTimer.totalTimeVal(); } return s; } protected void printStats() { int size; synchronized (this) { // size = victims.size(); // No, this is one too few. (Ceriel) size = victims.size() + 1; } // add my own stats StatsMessage me = createStats(); totalStats.add(me); java.text.NumberFormat nf = java.text.NumberFormat.getInstance(); // pf.setMaximumIntegerDigits(3); // pf.setMinimumIntegerDigits(3); // for percentages java.text.NumberFormat pf = java.text.NumberFormat.getInstance(); pf.setMaximumFractionDigits(3); pf.setMinimumFractionDigits(3); pf.setGroupingUsed(false); out .println("-------------------------------SATIN STATISTICS--------------------------------"); if (SPAWN_STATS) { out.println("SATIN: SPAWN: " + nf.format(totalStats.spawns) + " spawns, " + nf.format(totalStats.jobsExecuted) + " executed, " + nf.format(totalStats.syncs) + " syncs"); if (ABORTS) { out.println("SATIN: ABORT: " + nf.format(totalStats.aborts) + " aborts, " + nf.format(totalStats.abortMessages) + " abort msgs, " + nf.format(totalStats.abortedJobs) + " aborted jobs"); } } if (TUPLE_STATS) { out.println("SATIN: TUPLE_SPACE: " + nf.format(totalStats.tupleMsgs) + " bcasts, " + nf.format(totalStats.tupleBytes) + " bytes"); } if (POLL_FREQ != 0 && POLL_TIMING) { out.println("SATIN: POLL: poll count = " + nf.format(totalStats.pollCount)); } if (IDLE_TIMING) { out.println("SATIN: IDLE: idle count = " + nf.format(totalStats.idleCount)); } if (STEAL_STATS) { out .println("SATIN: STEAL: " + nf.format(totalStats.stealAttempts) + " attempts, " + nf.format(totalStats.stealSuccess) + " successes (" + pf .format(((double) totalStats.stealSuccess / totalStats.stealAttempts) * 100.0) + " %)"); out.println("SATIN: MESSAGES: intra " + nf.format(totalStats.intraClusterMessages) + " msgs, " + nf.format(totalStats.intraClusterBytes) + " bytes; inter " + nf.format(totalStats.interClusterMessages) + " msgs, " + nf.format(totalStats.interClusterBytes) + " bytes"); } if (FAULT_TOLERANCE && GRT_STATS) { out.println("SATIN: GLOBAL_RESULT_TABLE: result updates " + nf.format(totalStats.tableResultUpdates) + ",update messages " + nf.format(totalStats.tableUpdateMessages) + ", lock updates " + nf.format(totalStats.tableLockUpdates) + ",lookups " + nf.format(totalStats.tableLookups) + ",successful " + nf.format(totalStats.tableSuccessfulLookups) + ",remote " + nf.format(totalStats.tableRemoteLookups)); } if (FAULT_TOLERANCE && FT_STATS) { out.println("SATIN: FAULT_TOLERANCE: killed orphans " + nf.format(totalStats.killedOrphans)); out.println("SATIN: FAULT_TOLERANCE: restarted jobs " + nf.format(totalStats.restartedJobs)); } out .println("-------------------------------SATIN TOTAL TIMES-------------------------------"); if (STEAL_TIMING) { out.println("SATIN: STEAL_TIME: total " + Timer.format(totalStats.stealTime) + " time/req " + Timer.format(totalStats.stealTime / totalStats.stealAttempts)); out.println("SATIN: HANDLE_STEAL_TIME: total " + Timer.format(totalStats.handleStealTime) + " time/handle " + Timer.format((totalStats.handleStealTime) / totalStats.stealAttempts)); out.println("SATIN: SERIALIZATION_TIME: total " + Timer.format(totalStats.invocationRecordWriteTime) + " time/write " + Timer.format(totalStats.invocationRecordWriteTime / totalStats.stealSuccess)); out.println("SATIN: DESERIALIZATION_TIME: total " + Timer.format(totalStats.invocationRecordReadTime) + " time/read " + Timer.format(totalStats.invocationRecordReadTime / totalStats.stealSuccess)); } if (ABORT_TIMING) { out.println("SATIN: ABORT_TIME: total " + Timer.format(totalStats.abortTime) + " time/abort " + Timer.format(totalStats.abortTime / totalStats.aborts)); } if (TUPLE_TIMING) { out.println("SATIN: TUPLE_SPACE_BCAST_TIME: total " + Timer.format(totalStats.tupleTime) + " time/bcast " + Timer.format(totalStats.tupleTime / totalStats.tupleMsgs)); out.println("SATIN: TUPLE_SPACE_WAIT_TIME: total " + Timer.format(totalStats.tupleWaitTime) + " time/bcast " + Timer.format(totalStats.tupleWaitTime / totalStats.tupleWaitCount)); } if (POLL_FREQ != 0 && POLL_TIMING) { out.println("SATIN: POLL_TIME: total " + Timer.format(totalStats.pollTime) + " time/poll " + Timer.format(totalStats.pollTime / totalStats.pollCount)); } if (IDLE_TIMING) { out.println("SATIN: IDLE_TIME: total " + Timer.format(totalStats.idleTime) + " time/idle " + Timer.format(totalStats.idleTime / totalStats.idleCount)); } if (FAULT_TOLERANCE && GRT_TIMING) { out.println("SATIN: GRT_UPDATE_TIME: total " + Timer.format(totalStats.tableUpdateTime) + " time/update " + Timer.format(totalStats.tableUpdateTime / (totalStats.tableResultUpdates + totalStats.tableLockUpdates))); out.println("SATIN: GRT_LOOKUP_TIME: total " + Timer.format(totalStats.tableLookupTime) + " time/lookup " + Timer.format(totalStats.tableLookupTime / totalStats.tableLookups)); out.println("SATIN: GRT_HANDLE_UPDATE_TIME: total " + Timer.format(totalStats.tableHandleUpdateTime) + " time/handle " + Timer.format(totalStats.tableHandleUpdateTime / totalStats.tableResultUpdates * (size - 1))); out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: total " + Timer.format(totalStats.tableHandleLookupTime) + " time/handle " + Timer.format(totalStats.tableHandleLookupTime / totalStats.tableRemoteLookups)); out.println("SATIN: GRT_SERIALIZATION_TIME: total " + Timer.format(totalStats.tableSerializationTime)); out.println("SATIN: GRT_DESERIALIZATION_TIME: total " + Timer.format(totalStats.tableDeserializationTime)); out.println("SATIN: GRT_CHECK_TIME: total " + Timer.format(totalStats.tableCheckTime) + " time/check " + Timer.format(totalStats.tableCheckTime / totalStats.tableLookups)); } if (FAULT_TOLERANCE && CRASH_TIMING) { out.println("SATIN: CRASH_HANDLING_TIME: total " + Timer.format(totalStats.crashHandlingTime)); } if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) { out.println("SATIN: ADD_REPLICA_TIME: total " + Timer.format(totalStats.addReplicaTime)); } out .println("-------------------------------SATIN RUN TIME BREAKDOWN------------------------"); out.println("SATIN: TOTAL_RUN_TIME: " + Timer.format(totalTimer.totalTimeVal())); double lbTime = (totalStats.stealTime + totalStats.handleStealTime - totalStats.invocationRecordReadTime - totalStats.invocationRecordWriteTime) / size; if (lbTime < 0.0) lbTime = 0.0; double lbPerc = lbTime / totalTimer.totalTimeVal() * 100.0; double serTime = (totalStats.invocationRecordWriteTime + totalStats.invocationRecordReadTime) / size; double serPerc = serTime / totalTimer.totalTimeVal() * 100.0; double abortTime = totalStats.abortTime / size; double abortPerc = abortTime / totalTimer.totalTimeVal() * 100.0; double tupleTime = totalStats.tupleTime / size; double tuplePerc = tupleTime / totalTimer.totalTimeVal() * 100.0; double tupleWaitTime = totalStats.tupleWaitTime / size; double tupleWaitPerc = tupleWaitTime / totalTimer.totalTimeVal() * 100.0; double pollTime = totalStats.pollTime / size; double pollPerc = pollTime / totalTimer.totalTimeVal() * 100.0; double tableUpdateTime = totalStats.tableUpdateTime / size; double tableUpdatePerc = tableUpdateTime / totalTimer.totalTimeVal() * 100.0; double tableLookupTime = totalStats.tableLookupTime / size; double tableLookupPerc = tableLookupTime / totalTimer.totalTimeVal() * 100.0; double tableHandleUpdateTime = totalStats.tableHandleUpdateTime / size; double tableHandleUpdatePerc = tableHandleUpdateTime / totalTimer.totalTimeVal() * 100.0; double tableHandleLookupTime = totalStats.tableHandleLookupTime / size; double tableHandleLookupPerc = tableHandleLookupTime / totalTimer.totalTimeVal() * 100.0; double tableSerializationTime = totalStats.tableSerializationTime / size; double tableSerializationPerc = tableSerializationTime / totalTimer.totalTimeVal() * 100; double tableDeserializationTime = totalStats.tableDeserializationTime / size; double tableDeserializationPerc = tableDeserializationTime / totalTimer.totalTimeVal() * 100; double crashHandlingTime = totalStats.crashHandlingTime / size; double crashHandlingPerc = crashHandlingTime / totalTimer.totalTimeVal() * 100.0; double addReplicaTime = totalStats.addReplicaTime / size; double addReplicaPerc = addReplicaTime / totalTimer.totalTimeVal() * 100.0; - double totalOverhead = (totalStats.stealTime / size) + abortTime + tupleTime + double totalOverhead = (totalStats.stealTime + totalStats.handleStealTime) / size + abortTime + tupleTime + tupleWaitTime + pollTime + tableUpdateTime + tableLookupTime + tableHandleUpdateTime + tableHandleLookupTime; double totalPerc = totalOverhead / totalTimer.totalTimeVal() * 100.0; double appTime = totalTimer.totalTimeVal() - totalOverhead; if (appTime < 0.0) appTime = 0.0; double appPerc = appTime / totalTimer.totalTimeVal() * 100.0; if (STEAL_TIMING) { out.println("SATIN: LOAD_BALANCING_TIME: avg. per machine " + Timer.format(lbTime) + " (" + (lbPerc < 10 ? " " : "") + pf.format(lbPerc) + " %)"); out.println("SATIN: (DE)SERIALIZATION_TIME: avg. per machine " + Timer.format(serTime) + " (" + (serPerc < 10 ? " " : "") + pf.format(serPerc) + " %)"); } if (ABORT_TIMING) { out.println("SATIN: ABORT_TIME: avg. per machine " + Timer.format(abortTime) + " (" + (abortPerc < 10 ? " " : "") + pf.format(abortPerc) + " %)"); } if (TUPLE_TIMING) { out.println("SATIN: TUPLE_SPACE_BCAST_TIME: avg. per machine " + Timer.format(tupleTime) + " (" + (tuplePerc < 10 ? " " : "") + pf.format(tuplePerc) + " %)"); out.println("SATIN: TUPLE_SPACE_WAIT_TIME: avg. per machine " + Timer.format(tupleWaitTime) + " (" + (tupleWaitPerc < 10 ? " " : "") + pf.format(tupleWaitPerc) + " %)"); } if (POLL_FREQ != 0 && POLL_TIMING) { out.println("SATIN: POLL_TIME: avg. per machine " + Timer.format(pollTime) + " (" + (pollPerc < 10 ? " " : "") + pf.format(pollPerc) + " %)"); } if (FAULT_TOLERANCE && GRT_TIMING) { out .println("SATIN: GRT_UPDATE_TIME: avg. per machine " + Timer.format(tableUpdateTime) + " (" + pf.format(tableUpdatePerc) + " %)"); out .println("SATIN: GRT_LOOKUP_TIME: avg. per machine " + Timer.format(tableLookupTime) + " (" + pf.format(tableLookupPerc) + " %)"); out .println("SATIN: GRT_HANDLE_UPDATE_TIME: avg. per machine " + Timer.format(tableHandleUpdateTime) + " (" + pf.format(tableHandleUpdatePerc) + " %)"); out .println("SATIN: GRT_HANDLE_LOOKUP_TIME: avg. per machine " + Timer.format(tableHandleLookupTime) + " (" + pf.format(tableHandleLookupPerc) + " %)"); out .println("SATIN: GRT_SERIALIZATION_TIME: avg. per machine " + Timer.format(tableSerializationTime) + " (" + pf.format(tableSerializationPerc) + " %)"); out.println("SATIN: GRT_DESERIALIZATION_TIME: avg. per machine " + Timer.format(tableDeserializationTime) + " (" + pf.format(tableDeserializationPerc) + " %)"); } if (FAULT_TOLERANCE && CRASH_TIMING) { out.println("SATIN: CRASH_HANDLING_TIME: avg. per machine " + Timer.format(crashHandlingTime) + " (" + pf.format(crashHandlingPerc) + " %)"); } if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) { out.println("SATIN: ADD_REPLICA_TIME: avg. per machine " + Timer.format(addReplicaTime) + " (" + pf.format(addReplicaPerc) + " %)"); } out.println("\nSATIN: TOTAL_PARALLEL_OVERHEAD: avg. per machine " + Timer.format(totalOverhead) + " (" + (totalPerc < 10 ? " " : "") + pf.format(totalPerc) + " %)"); out.println("SATIN: USEFUL_APP_TIME: avg. per machine " + Timer.format(appTime) + " (" + (appPerc < 10 ? " " : "") + pf.format(appPerc) + " %)"); } protected void printDetailedStats() { java.text.NumberFormat nf = java.text.NumberFormat.getInstance(); if (SPAWN_STATS) { out.println("SATIN '" + ident.name() + "': SPAWN_STATS: spawns = " + spawns + " executed = " + jobsExecuted + " syncs = " + syncs); if (ABORTS) { out.println("SATIN '" + ident.name() + "': ABORT_STATS 1: aborts = " + aborts + " abort msgs = " + abortMessages + " aborted jobs = " + abortedJobs); } } if (TUPLE_STATS) { out.println("SATIN '" + ident.name() + "': TUPLE_STATS 1: tuple bcast msgs: " + tupleMsgs + ", bytes = " + nf.format(tupleBytes)); } if (STEAL_STATS) { out.println("SATIN '" + ident.name() + "': INTRA_STATS: messages = " + intraClusterMessages + ", bytes = " + nf.format(intraClusterBytes)); out.println("SATIN '" + ident.name() + "': INTER_STATS: messages = " + interClusterMessages + ", bytes = " + nf.format(interClusterBytes)); out .println("SATIN '" + ident.name() + "': STEAL_STATS 1: attempts = " + stealAttempts + " success = " + stealSuccess + " (" + (((double) stealSuccess / stealAttempts) * 100.0) + " %)"); out.println("SATIN '" + ident.name() + "': STEAL_STATS 2: requests = " + stealRequests + " jobs stolen = " + stolenJobs); if (STEAL_TIMING) { out.println("SATIN '" + ident.name() + "': STEAL_STATS 3: attempts = " + stealTimer.nrTimes() + " total time = " + stealTimer.totalTime() + " avg time = " + stealTimer.averageTime()); out.println("SATIN '" + ident.name() + "': STEAL_STATS 4: handleSteals = " + handleStealTimer.nrTimes() + " total time = " + handleStealTimer.totalTime() + " avg time = " + handleStealTimer.averageTime()); out.println("SATIN '" + ident.name() + "': STEAL_STATS 5: invocationRecordWrites = " + invocationRecordWriteTimer.nrTimes() + " total time = " + invocationRecordWriteTimer.totalTime() + " avg time = " + invocationRecordWriteTimer.averageTime()); out.println("SATIN '" + ident.name() + "': STEAL_STATS 6: invocationRecordReads = " + invocationRecordReadTimer.nrTimes() + " total time = " + invocationRecordReadTimer.totalTime() + " avg time = " + invocationRecordReadTimer.averageTime()); } if (ABORTS && ABORT_TIMING) { out.println("SATIN '" + ident.name() + "': ABORT_STATS 2: aborts = " + abortTimer.nrTimes() + " total time = " + abortTimer.totalTime() + " avg time = " + abortTimer.averageTime()); } if (IDLE_TIMING) { out.println("SATIN '" + ident.name() + "': IDLE_STATS: idle count = " + idleTimer.nrTimes() + " total time = " + idleTimer.totalTime() + " avg time = " + idleTimer.averageTime()); } if (POLL_FREQ != 0 && POLL_TIMING) { out.println("SATIN '" + ident.name() + "': POLL_STATS: poll count = " + pollTimer.nrTimes() + " total time = " + pollTimer.totalTime() + " avg time = " + pollTimer.averageTime()); } if (STEAL_TIMING && IDLE_TIMING) { out.println("SATIN '" + ident.name() + "': COMM_STATS: software comm time = " + Timer.format(stealTimer.totalTimeVal() + handleStealTimer.totalTimeVal() - idleTimer.totalTimeVal())); } if (TUPLE_TIMING) { out.println("SATIN '" + ident.name() + "': TUPLE_STATS 2: bcasts = " + tupleTimer.nrTimes() + " total time = " + tupleTimer.totalTime() + " avg time = " + tupleTimer.averageTime()); out.println("SATIN '" + ident.name() + "': TUPLE_STATS 3: waits = " + tupleOrderingWaitTimer.nrTimes() + " total time = " + tupleOrderingWaitTimer.totalTime() + " avg time = " + tupleOrderingWaitTimer.averageTime()); } algorithm.printStats(out); } if (FAULT_TOLERANCE) { if (GRT_STATS) { out.println("SATIN '" + ident.name() + "': " + globalResultTable.numResultUpdates + " result updates of the table."); out.println("SATIN '" + ident.name() + "': " + globalResultTable.numLockUpdates + " lock updates of the table."); out.println("SATIN '" + ident.name() + "': " + globalResultTable.numUpdateMessages + " update messages."); out.println("SATIN '" + ident.name() + "': " + globalResultTable.numLookupsSucceded + " lookups succeded, of which:"); out.println("SATIN '" + ident.name() + "': " + globalResultTable.numRemoteLookups + " remote lookups."); out.println("SATIN '" + ident.name() + "': " + globalResultTable.maxNumEntries + " entries maximally."); } if (GRT_TIMING) { out.println("SATIN '" + ident.name() + "': " + lookupTimer.totalTime() + " spent in lookups"); out.println("SATIN '" + ident.name() + "': " + lookupTimer.averageTime() + " per lookup"); out.println("SATIN '" + ident.name() + "': " + updateTimer.totalTime() + " spent in updates"); out.println("SATIN '" + ident.name() + "': " + updateTimer.averageTime() + " per update"); out.println("SATIN '" + ident.name() + "': " + handleUpdateTimer.totalTime() + " spent in handling updates"); out.println("SATIN '" + ident.name() + "': " + handleUpdateTimer.averageTime() + " per update handle"); out.println("SATIN '" + ident.name() + "': " + handleLookupTimer.totalTime() + " spent in handling lookups"); out.println("SATIN '" + ident.name() + "': " + handleLookupTimer.averageTime() + " per lookup handle"); } if (CRASH_TIMING) { out .println("SATIN '" + ident.name() + "': " + crashTimer.totalTime() + " spent in handling crashes"); } if (TABLE_CHECK_TIMING) { out.println("SATIN '" + ident.name() + "': " + redoTimer.totalTime() + " spent in redoing"); } if (FT_STATS) { out.println("SATIN '" + ident.name() + "': " + killedOrphans + " orphans killed"); out.println("SATIN '" + ident.name() + "': " + restartedJobs + " jobs restarted"); } } } }
true
true
protected void printStats() { int size; synchronized (this) { // size = victims.size(); // No, this is one too few. (Ceriel) size = victims.size() + 1; } // add my own stats StatsMessage me = createStats(); totalStats.add(me); java.text.NumberFormat nf = java.text.NumberFormat.getInstance(); // pf.setMaximumIntegerDigits(3); // pf.setMinimumIntegerDigits(3); // for percentages java.text.NumberFormat pf = java.text.NumberFormat.getInstance(); pf.setMaximumFractionDigits(3); pf.setMinimumFractionDigits(3); pf.setGroupingUsed(false); out .println("-------------------------------SATIN STATISTICS--------------------------------"); if (SPAWN_STATS) { out.println("SATIN: SPAWN: " + nf.format(totalStats.spawns) + " spawns, " + nf.format(totalStats.jobsExecuted) + " executed, " + nf.format(totalStats.syncs) + " syncs"); if (ABORTS) { out.println("SATIN: ABORT: " + nf.format(totalStats.aborts) + " aborts, " + nf.format(totalStats.abortMessages) + " abort msgs, " + nf.format(totalStats.abortedJobs) + " aborted jobs"); } } if (TUPLE_STATS) { out.println("SATIN: TUPLE_SPACE: " + nf.format(totalStats.tupleMsgs) + " bcasts, " + nf.format(totalStats.tupleBytes) + " bytes"); } if (POLL_FREQ != 0 && POLL_TIMING) { out.println("SATIN: POLL: poll count = " + nf.format(totalStats.pollCount)); } if (IDLE_TIMING) { out.println("SATIN: IDLE: idle count = " + nf.format(totalStats.idleCount)); } if (STEAL_STATS) { out .println("SATIN: STEAL: " + nf.format(totalStats.stealAttempts) + " attempts, " + nf.format(totalStats.stealSuccess) + " successes (" + pf .format(((double) totalStats.stealSuccess / totalStats.stealAttempts) * 100.0) + " %)"); out.println("SATIN: MESSAGES: intra " + nf.format(totalStats.intraClusterMessages) + " msgs, " + nf.format(totalStats.intraClusterBytes) + " bytes; inter " + nf.format(totalStats.interClusterMessages) + " msgs, " + nf.format(totalStats.interClusterBytes) + " bytes"); } if (FAULT_TOLERANCE && GRT_STATS) { out.println("SATIN: GLOBAL_RESULT_TABLE: result updates " + nf.format(totalStats.tableResultUpdates) + ",update messages " + nf.format(totalStats.tableUpdateMessages) + ", lock updates " + nf.format(totalStats.tableLockUpdates) + ",lookups " + nf.format(totalStats.tableLookups) + ",successful " + nf.format(totalStats.tableSuccessfulLookups) + ",remote " + nf.format(totalStats.tableRemoteLookups)); } if (FAULT_TOLERANCE && FT_STATS) { out.println("SATIN: FAULT_TOLERANCE: killed orphans " + nf.format(totalStats.killedOrphans)); out.println("SATIN: FAULT_TOLERANCE: restarted jobs " + nf.format(totalStats.restartedJobs)); } out .println("-------------------------------SATIN TOTAL TIMES-------------------------------"); if (STEAL_TIMING) { out.println("SATIN: STEAL_TIME: total " + Timer.format(totalStats.stealTime) + " time/req " + Timer.format(totalStats.stealTime / totalStats.stealAttempts)); out.println("SATIN: HANDLE_STEAL_TIME: total " + Timer.format(totalStats.handleStealTime) + " time/handle " + Timer.format((totalStats.handleStealTime) / totalStats.stealAttempts)); out.println("SATIN: SERIALIZATION_TIME: total " + Timer.format(totalStats.invocationRecordWriteTime) + " time/write " + Timer.format(totalStats.invocationRecordWriteTime / totalStats.stealSuccess)); out.println("SATIN: DESERIALIZATION_TIME: total " + Timer.format(totalStats.invocationRecordReadTime) + " time/read " + Timer.format(totalStats.invocationRecordReadTime / totalStats.stealSuccess)); } if (ABORT_TIMING) { out.println("SATIN: ABORT_TIME: total " + Timer.format(totalStats.abortTime) + " time/abort " + Timer.format(totalStats.abortTime / totalStats.aborts)); } if (TUPLE_TIMING) { out.println("SATIN: TUPLE_SPACE_BCAST_TIME: total " + Timer.format(totalStats.tupleTime) + " time/bcast " + Timer.format(totalStats.tupleTime / totalStats.tupleMsgs)); out.println("SATIN: TUPLE_SPACE_WAIT_TIME: total " + Timer.format(totalStats.tupleWaitTime) + " time/bcast " + Timer.format(totalStats.tupleWaitTime / totalStats.tupleWaitCount)); } if (POLL_FREQ != 0 && POLL_TIMING) { out.println("SATIN: POLL_TIME: total " + Timer.format(totalStats.pollTime) + " time/poll " + Timer.format(totalStats.pollTime / totalStats.pollCount)); } if (IDLE_TIMING) { out.println("SATIN: IDLE_TIME: total " + Timer.format(totalStats.idleTime) + " time/idle " + Timer.format(totalStats.idleTime / totalStats.idleCount)); } if (FAULT_TOLERANCE && GRT_TIMING) { out.println("SATIN: GRT_UPDATE_TIME: total " + Timer.format(totalStats.tableUpdateTime) + " time/update " + Timer.format(totalStats.tableUpdateTime / (totalStats.tableResultUpdates + totalStats.tableLockUpdates))); out.println("SATIN: GRT_LOOKUP_TIME: total " + Timer.format(totalStats.tableLookupTime) + " time/lookup " + Timer.format(totalStats.tableLookupTime / totalStats.tableLookups)); out.println("SATIN: GRT_HANDLE_UPDATE_TIME: total " + Timer.format(totalStats.tableHandleUpdateTime) + " time/handle " + Timer.format(totalStats.tableHandleUpdateTime / totalStats.tableResultUpdates * (size - 1))); out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: total " + Timer.format(totalStats.tableHandleLookupTime) + " time/handle " + Timer.format(totalStats.tableHandleLookupTime / totalStats.tableRemoteLookups)); out.println("SATIN: GRT_SERIALIZATION_TIME: total " + Timer.format(totalStats.tableSerializationTime)); out.println("SATIN: GRT_DESERIALIZATION_TIME: total " + Timer.format(totalStats.tableDeserializationTime)); out.println("SATIN: GRT_CHECK_TIME: total " + Timer.format(totalStats.tableCheckTime) + " time/check " + Timer.format(totalStats.tableCheckTime / totalStats.tableLookups)); } if (FAULT_TOLERANCE && CRASH_TIMING) { out.println("SATIN: CRASH_HANDLING_TIME: total " + Timer.format(totalStats.crashHandlingTime)); } if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) { out.println("SATIN: ADD_REPLICA_TIME: total " + Timer.format(totalStats.addReplicaTime)); } out .println("-------------------------------SATIN RUN TIME BREAKDOWN------------------------"); out.println("SATIN: TOTAL_RUN_TIME: " + Timer.format(totalTimer.totalTimeVal())); double lbTime = (totalStats.stealTime + totalStats.handleStealTime - totalStats.invocationRecordReadTime - totalStats.invocationRecordWriteTime) / size; if (lbTime < 0.0) lbTime = 0.0; double lbPerc = lbTime / totalTimer.totalTimeVal() * 100.0; double serTime = (totalStats.invocationRecordWriteTime + totalStats.invocationRecordReadTime) / size; double serPerc = serTime / totalTimer.totalTimeVal() * 100.0; double abortTime = totalStats.abortTime / size; double abortPerc = abortTime / totalTimer.totalTimeVal() * 100.0; double tupleTime = totalStats.tupleTime / size; double tuplePerc = tupleTime / totalTimer.totalTimeVal() * 100.0; double tupleWaitTime = totalStats.tupleWaitTime / size; double tupleWaitPerc = tupleWaitTime / totalTimer.totalTimeVal() * 100.0; double pollTime = totalStats.pollTime / size; double pollPerc = pollTime / totalTimer.totalTimeVal() * 100.0; double tableUpdateTime = totalStats.tableUpdateTime / size; double tableUpdatePerc = tableUpdateTime / totalTimer.totalTimeVal() * 100.0; double tableLookupTime = totalStats.tableLookupTime / size; double tableLookupPerc = tableLookupTime / totalTimer.totalTimeVal() * 100.0; double tableHandleUpdateTime = totalStats.tableHandleUpdateTime / size; double tableHandleUpdatePerc = tableHandleUpdateTime / totalTimer.totalTimeVal() * 100.0; double tableHandleLookupTime = totalStats.tableHandleLookupTime / size; double tableHandleLookupPerc = tableHandleLookupTime / totalTimer.totalTimeVal() * 100.0; double tableSerializationTime = totalStats.tableSerializationTime / size; double tableSerializationPerc = tableSerializationTime / totalTimer.totalTimeVal() * 100; double tableDeserializationTime = totalStats.tableDeserializationTime / size; double tableDeserializationPerc = tableDeserializationTime / totalTimer.totalTimeVal() * 100; double crashHandlingTime = totalStats.crashHandlingTime / size; double crashHandlingPerc = crashHandlingTime / totalTimer.totalTimeVal() * 100.0; double addReplicaTime = totalStats.addReplicaTime / size; double addReplicaPerc = addReplicaTime / totalTimer.totalTimeVal() * 100.0; double totalOverhead = (totalStats.stealTime / size) + abortTime + tupleTime + tupleWaitTime + pollTime + tableUpdateTime + tableLookupTime + tableHandleUpdateTime + tableHandleLookupTime; double totalPerc = totalOverhead / totalTimer.totalTimeVal() * 100.0; double appTime = totalTimer.totalTimeVal() - totalOverhead; if (appTime < 0.0) appTime = 0.0; double appPerc = appTime / totalTimer.totalTimeVal() * 100.0; if (STEAL_TIMING) { out.println("SATIN: LOAD_BALANCING_TIME: avg. per machine " + Timer.format(lbTime) + " (" + (lbPerc < 10 ? " " : "") + pf.format(lbPerc) + " %)"); out.println("SATIN: (DE)SERIALIZATION_TIME: avg. per machine " + Timer.format(serTime) + " (" + (serPerc < 10 ? " " : "") + pf.format(serPerc) + " %)"); } if (ABORT_TIMING) { out.println("SATIN: ABORT_TIME: avg. per machine " + Timer.format(abortTime) + " (" + (abortPerc < 10 ? " " : "") + pf.format(abortPerc) + " %)"); } if (TUPLE_TIMING) { out.println("SATIN: TUPLE_SPACE_BCAST_TIME: avg. per machine " + Timer.format(tupleTime) + " (" + (tuplePerc < 10 ? " " : "") + pf.format(tuplePerc) + " %)"); out.println("SATIN: TUPLE_SPACE_WAIT_TIME: avg. per machine " + Timer.format(tupleWaitTime) + " (" + (tupleWaitPerc < 10 ? " " : "") + pf.format(tupleWaitPerc) + " %)"); } if (POLL_FREQ != 0 && POLL_TIMING) { out.println("SATIN: POLL_TIME: avg. per machine " + Timer.format(pollTime) + " (" + (pollPerc < 10 ? " " : "") + pf.format(pollPerc) + " %)"); } if (FAULT_TOLERANCE && GRT_TIMING) { out .println("SATIN: GRT_UPDATE_TIME: avg. per machine " + Timer.format(tableUpdateTime) + " (" + pf.format(tableUpdatePerc) + " %)"); out .println("SATIN: GRT_LOOKUP_TIME: avg. per machine " + Timer.format(tableLookupTime) + " (" + pf.format(tableLookupPerc) + " %)"); out .println("SATIN: GRT_HANDLE_UPDATE_TIME: avg. per machine " + Timer.format(tableHandleUpdateTime) + " (" + pf.format(tableHandleUpdatePerc) + " %)"); out .println("SATIN: GRT_HANDLE_LOOKUP_TIME: avg. per machine " + Timer.format(tableHandleLookupTime) + " (" + pf.format(tableHandleLookupPerc) + " %)"); out .println("SATIN: GRT_SERIALIZATION_TIME: avg. per machine " + Timer.format(tableSerializationTime) + " (" + pf.format(tableSerializationPerc) + " %)"); out.println("SATIN: GRT_DESERIALIZATION_TIME: avg. per machine " + Timer.format(tableDeserializationTime) + " (" + pf.format(tableDeserializationPerc) + " %)"); } if (FAULT_TOLERANCE && CRASH_TIMING) { out.println("SATIN: CRASH_HANDLING_TIME: avg. per machine " + Timer.format(crashHandlingTime) + " (" + pf.format(crashHandlingPerc) + " %)"); } if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) { out.println("SATIN: ADD_REPLICA_TIME: avg. per machine " + Timer.format(addReplicaTime) + " (" + pf.format(addReplicaPerc) + " %)"); } out.println("\nSATIN: TOTAL_PARALLEL_OVERHEAD: avg. per machine " + Timer.format(totalOverhead) + " (" + (totalPerc < 10 ? " " : "") + pf.format(totalPerc) + " %)"); out.println("SATIN: USEFUL_APP_TIME: avg. per machine " + Timer.format(appTime) + " (" + (appPerc < 10 ? " " : "") + pf.format(appPerc) + " %)"); }
protected void printStats() { int size; synchronized (this) { // size = victims.size(); // No, this is one too few. (Ceriel) size = victims.size() + 1; } // add my own stats StatsMessage me = createStats(); totalStats.add(me); java.text.NumberFormat nf = java.text.NumberFormat.getInstance(); // pf.setMaximumIntegerDigits(3); // pf.setMinimumIntegerDigits(3); // for percentages java.text.NumberFormat pf = java.text.NumberFormat.getInstance(); pf.setMaximumFractionDigits(3); pf.setMinimumFractionDigits(3); pf.setGroupingUsed(false); out .println("-------------------------------SATIN STATISTICS--------------------------------"); if (SPAWN_STATS) { out.println("SATIN: SPAWN: " + nf.format(totalStats.spawns) + " spawns, " + nf.format(totalStats.jobsExecuted) + " executed, " + nf.format(totalStats.syncs) + " syncs"); if (ABORTS) { out.println("SATIN: ABORT: " + nf.format(totalStats.aborts) + " aborts, " + nf.format(totalStats.abortMessages) + " abort msgs, " + nf.format(totalStats.abortedJobs) + " aborted jobs"); } } if (TUPLE_STATS) { out.println("SATIN: TUPLE_SPACE: " + nf.format(totalStats.tupleMsgs) + " bcasts, " + nf.format(totalStats.tupleBytes) + " bytes"); } if (POLL_FREQ != 0 && POLL_TIMING) { out.println("SATIN: POLL: poll count = " + nf.format(totalStats.pollCount)); } if (IDLE_TIMING) { out.println("SATIN: IDLE: idle count = " + nf.format(totalStats.idleCount)); } if (STEAL_STATS) { out .println("SATIN: STEAL: " + nf.format(totalStats.stealAttempts) + " attempts, " + nf.format(totalStats.stealSuccess) + " successes (" + pf .format(((double) totalStats.stealSuccess / totalStats.stealAttempts) * 100.0) + " %)"); out.println("SATIN: MESSAGES: intra " + nf.format(totalStats.intraClusterMessages) + " msgs, " + nf.format(totalStats.intraClusterBytes) + " bytes; inter " + nf.format(totalStats.interClusterMessages) + " msgs, " + nf.format(totalStats.interClusterBytes) + " bytes"); } if (FAULT_TOLERANCE && GRT_STATS) { out.println("SATIN: GLOBAL_RESULT_TABLE: result updates " + nf.format(totalStats.tableResultUpdates) + ",update messages " + nf.format(totalStats.tableUpdateMessages) + ", lock updates " + nf.format(totalStats.tableLockUpdates) + ",lookups " + nf.format(totalStats.tableLookups) + ",successful " + nf.format(totalStats.tableSuccessfulLookups) + ",remote " + nf.format(totalStats.tableRemoteLookups)); } if (FAULT_TOLERANCE && FT_STATS) { out.println("SATIN: FAULT_TOLERANCE: killed orphans " + nf.format(totalStats.killedOrphans)); out.println("SATIN: FAULT_TOLERANCE: restarted jobs " + nf.format(totalStats.restartedJobs)); } out .println("-------------------------------SATIN TOTAL TIMES-------------------------------"); if (STEAL_TIMING) { out.println("SATIN: STEAL_TIME: total " + Timer.format(totalStats.stealTime) + " time/req " + Timer.format(totalStats.stealTime / totalStats.stealAttempts)); out.println("SATIN: HANDLE_STEAL_TIME: total " + Timer.format(totalStats.handleStealTime) + " time/handle " + Timer.format((totalStats.handleStealTime) / totalStats.stealAttempts)); out.println("SATIN: SERIALIZATION_TIME: total " + Timer.format(totalStats.invocationRecordWriteTime) + " time/write " + Timer.format(totalStats.invocationRecordWriteTime / totalStats.stealSuccess)); out.println("SATIN: DESERIALIZATION_TIME: total " + Timer.format(totalStats.invocationRecordReadTime) + " time/read " + Timer.format(totalStats.invocationRecordReadTime / totalStats.stealSuccess)); } if (ABORT_TIMING) { out.println("SATIN: ABORT_TIME: total " + Timer.format(totalStats.abortTime) + " time/abort " + Timer.format(totalStats.abortTime / totalStats.aborts)); } if (TUPLE_TIMING) { out.println("SATIN: TUPLE_SPACE_BCAST_TIME: total " + Timer.format(totalStats.tupleTime) + " time/bcast " + Timer.format(totalStats.tupleTime / totalStats.tupleMsgs)); out.println("SATIN: TUPLE_SPACE_WAIT_TIME: total " + Timer.format(totalStats.tupleWaitTime) + " time/bcast " + Timer.format(totalStats.tupleWaitTime / totalStats.tupleWaitCount)); } if (POLL_FREQ != 0 && POLL_TIMING) { out.println("SATIN: POLL_TIME: total " + Timer.format(totalStats.pollTime) + " time/poll " + Timer.format(totalStats.pollTime / totalStats.pollCount)); } if (IDLE_TIMING) { out.println("SATIN: IDLE_TIME: total " + Timer.format(totalStats.idleTime) + " time/idle " + Timer.format(totalStats.idleTime / totalStats.idleCount)); } if (FAULT_TOLERANCE && GRT_TIMING) { out.println("SATIN: GRT_UPDATE_TIME: total " + Timer.format(totalStats.tableUpdateTime) + " time/update " + Timer.format(totalStats.tableUpdateTime / (totalStats.tableResultUpdates + totalStats.tableLockUpdates))); out.println("SATIN: GRT_LOOKUP_TIME: total " + Timer.format(totalStats.tableLookupTime) + " time/lookup " + Timer.format(totalStats.tableLookupTime / totalStats.tableLookups)); out.println("SATIN: GRT_HANDLE_UPDATE_TIME: total " + Timer.format(totalStats.tableHandleUpdateTime) + " time/handle " + Timer.format(totalStats.tableHandleUpdateTime / totalStats.tableResultUpdates * (size - 1))); out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: total " + Timer.format(totalStats.tableHandleLookupTime) + " time/handle " + Timer.format(totalStats.tableHandleLookupTime / totalStats.tableRemoteLookups)); out.println("SATIN: GRT_SERIALIZATION_TIME: total " + Timer.format(totalStats.tableSerializationTime)); out.println("SATIN: GRT_DESERIALIZATION_TIME: total " + Timer.format(totalStats.tableDeserializationTime)); out.println("SATIN: GRT_CHECK_TIME: total " + Timer.format(totalStats.tableCheckTime) + " time/check " + Timer.format(totalStats.tableCheckTime / totalStats.tableLookups)); } if (FAULT_TOLERANCE && CRASH_TIMING) { out.println("SATIN: CRASH_HANDLING_TIME: total " + Timer.format(totalStats.crashHandlingTime)); } if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) { out.println("SATIN: ADD_REPLICA_TIME: total " + Timer.format(totalStats.addReplicaTime)); } out .println("-------------------------------SATIN RUN TIME BREAKDOWN------------------------"); out.println("SATIN: TOTAL_RUN_TIME: " + Timer.format(totalTimer.totalTimeVal())); double lbTime = (totalStats.stealTime + totalStats.handleStealTime - totalStats.invocationRecordReadTime - totalStats.invocationRecordWriteTime) / size; if (lbTime < 0.0) lbTime = 0.0; double lbPerc = lbTime / totalTimer.totalTimeVal() * 100.0; double serTime = (totalStats.invocationRecordWriteTime + totalStats.invocationRecordReadTime) / size; double serPerc = serTime / totalTimer.totalTimeVal() * 100.0; double abortTime = totalStats.abortTime / size; double abortPerc = abortTime / totalTimer.totalTimeVal() * 100.0; double tupleTime = totalStats.tupleTime / size; double tuplePerc = tupleTime / totalTimer.totalTimeVal() * 100.0; double tupleWaitTime = totalStats.tupleWaitTime / size; double tupleWaitPerc = tupleWaitTime / totalTimer.totalTimeVal() * 100.0; double pollTime = totalStats.pollTime / size; double pollPerc = pollTime / totalTimer.totalTimeVal() * 100.0; double tableUpdateTime = totalStats.tableUpdateTime / size; double tableUpdatePerc = tableUpdateTime / totalTimer.totalTimeVal() * 100.0; double tableLookupTime = totalStats.tableLookupTime / size; double tableLookupPerc = tableLookupTime / totalTimer.totalTimeVal() * 100.0; double tableHandleUpdateTime = totalStats.tableHandleUpdateTime / size; double tableHandleUpdatePerc = tableHandleUpdateTime / totalTimer.totalTimeVal() * 100.0; double tableHandleLookupTime = totalStats.tableHandleLookupTime / size; double tableHandleLookupPerc = tableHandleLookupTime / totalTimer.totalTimeVal() * 100.0; double tableSerializationTime = totalStats.tableSerializationTime / size; double tableSerializationPerc = tableSerializationTime / totalTimer.totalTimeVal() * 100; double tableDeserializationTime = totalStats.tableDeserializationTime / size; double tableDeserializationPerc = tableDeserializationTime / totalTimer.totalTimeVal() * 100; double crashHandlingTime = totalStats.crashHandlingTime / size; double crashHandlingPerc = crashHandlingTime / totalTimer.totalTimeVal() * 100.0; double addReplicaTime = totalStats.addReplicaTime / size; double addReplicaPerc = addReplicaTime / totalTimer.totalTimeVal() * 100.0; double totalOverhead = (totalStats.stealTime + totalStats.handleStealTime) / size + abortTime + tupleTime + tupleWaitTime + pollTime + tableUpdateTime + tableLookupTime + tableHandleUpdateTime + tableHandleLookupTime; double totalPerc = totalOverhead / totalTimer.totalTimeVal() * 100.0; double appTime = totalTimer.totalTimeVal() - totalOverhead; if (appTime < 0.0) appTime = 0.0; double appPerc = appTime / totalTimer.totalTimeVal() * 100.0; if (STEAL_TIMING) { out.println("SATIN: LOAD_BALANCING_TIME: avg. per machine " + Timer.format(lbTime) + " (" + (lbPerc < 10 ? " " : "") + pf.format(lbPerc) + " %)"); out.println("SATIN: (DE)SERIALIZATION_TIME: avg. per machine " + Timer.format(serTime) + " (" + (serPerc < 10 ? " " : "") + pf.format(serPerc) + " %)"); } if (ABORT_TIMING) { out.println("SATIN: ABORT_TIME: avg. per machine " + Timer.format(abortTime) + " (" + (abortPerc < 10 ? " " : "") + pf.format(abortPerc) + " %)"); } if (TUPLE_TIMING) { out.println("SATIN: TUPLE_SPACE_BCAST_TIME: avg. per machine " + Timer.format(tupleTime) + " (" + (tuplePerc < 10 ? " " : "") + pf.format(tuplePerc) + " %)"); out.println("SATIN: TUPLE_SPACE_WAIT_TIME: avg. per machine " + Timer.format(tupleWaitTime) + " (" + (tupleWaitPerc < 10 ? " " : "") + pf.format(tupleWaitPerc) + " %)"); } if (POLL_FREQ != 0 && POLL_TIMING) { out.println("SATIN: POLL_TIME: avg. per machine " + Timer.format(pollTime) + " (" + (pollPerc < 10 ? " " : "") + pf.format(pollPerc) + " %)"); } if (FAULT_TOLERANCE && GRT_TIMING) { out .println("SATIN: GRT_UPDATE_TIME: avg. per machine " + Timer.format(tableUpdateTime) + " (" + pf.format(tableUpdatePerc) + " %)"); out .println("SATIN: GRT_LOOKUP_TIME: avg. per machine " + Timer.format(tableLookupTime) + " (" + pf.format(tableLookupPerc) + " %)"); out .println("SATIN: GRT_HANDLE_UPDATE_TIME: avg. per machine " + Timer.format(tableHandleUpdateTime) + " (" + pf.format(tableHandleUpdatePerc) + " %)"); out .println("SATIN: GRT_HANDLE_LOOKUP_TIME: avg. per machine " + Timer.format(tableHandleLookupTime) + " (" + pf.format(tableHandleLookupPerc) + " %)"); out .println("SATIN: GRT_SERIALIZATION_TIME: avg. per machine " + Timer.format(tableSerializationTime) + " (" + pf.format(tableSerializationPerc) + " %)"); out.println("SATIN: GRT_DESERIALIZATION_TIME: avg. per machine " + Timer.format(tableDeserializationTime) + " (" + pf.format(tableDeserializationPerc) + " %)"); } if (FAULT_TOLERANCE && CRASH_TIMING) { out.println("SATIN: CRASH_HANDLING_TIME: avg. per machine " + Timer.format(crashHandlingTime) + " (" + pf.format(crashHandlingPerc) + " %)"); } if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) { out.println("SATIN: ADD_REPLICA_TIME: avg. per machine " + Timer.format(addReplicaTime) + " (" + pf.format(addReplicaPerc) + " %)"); } out.println("\nSATIN: TOTAL_PARALLEL_OVERHEAD: avg. per machine " + Timer.format(totalOverhead) + " (" + (totalPerc < 10 ? " " : "") + pf.format(totalPerc) + " %)"); out.println("SATIN: USEFUL_APP_TIME: avg. per machine " + Timer.format(appTime) + " (" + (appPerc < 10 ? " " : "") + pf.format(appPerc) + " %)"); }
diff --git a/src/com/bigpupdev/synodroid/server/SynoServerConnection.java b/src/com/bigpupdev/synodroid/server/SynoServerConnection.java index 97e7cfd..6573d54 100644 --- a/src/com/bigpupdev/synodroid/server/SynoServerConnection.java +++ b/src/com/bigpupdev/synodroid/server/SynoServerConnection.java @@ -1,102 +1,108 @@ /** * */ package com.bigpupdev.synodroid.server; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import com.bigpupdev.synodroid.Synodroid; import com.bigpupdev.synodroid.preference.ListPreferenceMultiSelectWithValue; import com.bigpupdev.synodroid.preference.PreferenceFacade; import com.bigpupdev.synodroid.data.SynoProtocol; import android.util.Log; /** * A technical connection definition to a SynoServer * * @author Eric Taix */ public class SynoServerConnection { // The protocol used to communicate with the server public SynoProtocol protocol = SynoProtocol.HTTP; // The hostname or ip address public String host; // The port public Integer port = 5000; // The refresh interval in seconds public Integer refreshInterval = 10; // The resfresh state (enable or disable autorefresh) public boolean autoRefresh = true; // Show (or not) the upload progress in the main activity public boolean showUpload = true; // Wifi SSID allowed for this server (empty when used for a public connection) public List<String> wifiSSID = new ArrayList<String>(); /** * Create an instance of SynoServerConnection * * @param props * @return */ public static SynoServerConnection createFromProperties(boolean local, Properties props, boolean debug) { SynoServerConnection result = null; try { String radical = ""; boolean valid = false; if (local) { radical += PreferenceFacade.WLAN_RADICAL; String usewifi = props.getProperty(radical + PreferenceFacade.USEWIFI_SUFFIX); if (usewifi != null && usewifi.equals("true")) { valid = true; } } else { String useext = props.getProperty(radical + PreferenceFacade.USEEXT_SUFFIX); if (useext != null && useext.equals("true")) { valid = true; } } if (valid) { - SynoProtocol protocol = SynoProtocol.valueOf(props.getProperty(radical + PreferenceFacade.PROTOCOL_SUFFIX)); - int port = 5000; + SynoProtocol protocol = SynoProtocol.valueOf("HTTPS"); + try{ + protocol = SynoProtocol.valueOf(props.getProperty(radical + PreferenceFacade.PROTOCOL_SUFFIX)); + } + catch (IllegalArgumentException ex){ + if (debug) Log.w(Synodroid.DS_TAG, "An invalid protocol was detected while loading " + (local ? "local" : "public") + " connection. Will use default protocol (HTTPS)."); + } + int port = 5001; try{ port = Integer.parseInt(props.getProperty(radical + PreferenceFacade.PORT_SUFFIX)); } catch (NumberFormatException numEx){ - if (debug) Log.w(Synodroid.DS_TAG, "An invalid port number was detected while loading " + (local ? "local" : "public") + " connection. This connection will be ignored."); + if (debug) Log.w(Synodroid.DS_TAG, "An invalid port number was detected while loading " + (local ? "local" : "public") + " connection. Will use default HTTPS port (5001)."); } String host = props.getProperty(radical + PreferenceFacade.HOST_SUFFIX); if (protocol != null && port != 0 && host != null && host.length() > 0) { result = new SynoServerConnection(); result.protocol = protocol; result.host = host; result.port = port; result.showUpload = Boolean.parseBoolean(props.getProperty(radical + PreferenceFacade.SHOWUPLOAD_SUFFIX)); result.refreshInterval = Integer.parseInt(props.getProperty(radical + PreferenceFacade.REFRESHVALUE_SUFFIX)); result.autoRefresh = Boolean.parseBoolean(props.getProperty(radical + PreferenceFacade.REFRESHSTATE_SUFFIX)); if (local) { String separatedValues = props.getProperty(radical + PreferenceFacade.SSID_SUFFIX); String[] ssids = ListPreferenceMultiSelectWithValue.parseStoredValue(separatedValues); if (ssids != null) { result.wifiSSID = Arrays.asList(ssids); } else { result = null; } } else { result.wifiSSID = null; } } } } catch (Exception ex) { if (debug) Log.e(Synodroid.DS_TAG, "An exception occured while loading " + (local ? "local" : "public") + " connection", ex); } return result; } }
false
true
public static SynoServerConnection createFromProperties(boolean local, Properties props, boolean debug) { SynoServerConnection result = null; try { String radical = ""; boolean valid = false; if (local) { radical += PreferenceFacade.WLAN_RADICAL; String usewifi = props.getProperty(radical + PreferenceFacade.USEWIFI_SUFFIX); if (usewifi != null && usewifi.equals("true")) { valid = true; } } else { String useext = props.getProperty(radical + PreferenceFacade.USEEXT_SUFFIX); if (useext != null && useext.equals("true")) { valid = true; } } if (valid) { SynoProtocol protocol = SynoProtocol.valueOf(props.getProperty(radical + PreferenceFacade.PROTOCOL_SUFFIX)); int port = 5000; try{ port = Integer.parseInt(props.getProperty(radical + PreferenceFacade.PORT_SUFFIX)); } catch (NumberFormatException numEx){ if (debug) Log.w(Synodroid.DS_TAG, "An invalid port number was detected while loading " + (local ? "local" : "public") + " connection. This connection will be ignored."); } String host = props.getProperty(radical + PreferenceFacade.HOST_SUFFIX); if (protocol != null && port != 0 && host != null && host.length() > 0) { result = new SynoServerConnection(); result.protocol = protocol; result.host = host; result.port = port; result.showUpload = Boolean.parseBoolean(props.getProperty(radical + PreferenceFacade.SHOWUPLOAD_SUFFIX)); result.refreshInterval = Integer.parseInt(props.getProperty(radical + PreferenceFacade.REFRESHVALUE_SUFFIX)); result.autoRefresh = Boolean.parseBoolean(props.getProperty(radical + PreferenceFacade.REFRESHSTATE_SUFFIX)); if (local) { String separatedValues = props.getProperty(radical + PreferenceFacade.SSID_SUFFIX); String[] ssids = ListPreferenceMultiSelectWithValue.parseStoredValue(separatedValues); if (ssids != null) { result.wifiSSID = Arrays.asList(ssids); } else { result = null; } } else { result.wifiSSID = null; } } } } catch (Exception ex) { if (debug) Log.e(Synodroid.DS_TAG, "An exception occured while loading " + (local ? "local" : "public") + " connection", ex); } return result; }
public static SynoServerConnection createFromProperties(boolean local, Properties props, boolean debug) { SynoServerConnection result = null; try { String radical = ""; boolean valid = false; if (local) { radical += PreferenceFacade.WLAN_RADICAL; String usewifi = props.getProperty(radical + PreferenceFacade.USEWIFI_SUFFIX); if (usewifi != null && usewifi.equals("true")) { valid = true; } } else { String useext = props.getProperty(radical + PreferenceFacade.USEEXT_SUFFIX); if (useext != null && useext.equals("true")) { valid = true; } } if (valid) { SynoProtocol protocol = SynoProtocol.valueOf("HTTPS"); try{ protocol = SynoProtocol.valueOf(props.getProperty(radical + PreferenceFacade.PROTOCOL_SUFFIX)); } catch (IllegalArgumentException ex){ if (debug) Log.w(Synodroid.DS_TAG, "An invalid protocol was detected while loading " + (local ? "local" : "public") + " connection. Will use default protocol (HTTPS)."); } int port = 5001; try{ port = Integer.parseInt(props.getProperty(radical + PreferenceFacade.PORT_SUFFIX)); } catch (NumberFormatException numEx){ if (debug) Log.w(Synodroid.DS_TAG, "An invalid port number was detected while loading " + (local ? "local" : "public") + " connection. Will use default HTTPS port (5001)."); } String host = props.getProperty(radical + PreferenceFacade.HOST_SUFFIX); if (protocol != null && port != 0 && host != null && host.length() > 0) { result = new SynoServerConnection(); result.protocol = protocol; result.host = host; result.port = port; result.showUpload = Boolean.parseBoolean(props.getProperty(radical + PreferenceFacade.SHOWUPLOAD_SUFFIX)); result.refreshInterval = Integer.parseInt(props.getProperty(radical + PreferenceFacade.REFRESHVALUE_SUFFIX)); result.autoRefresh = Boolean.parseBoolean(props.getProperty(radical + PreferenceFacade.REFRESHSTATE_SUFFIX)); if (local) { String separatedValues = props.getProperty(radical + PreferenceFacade.SSID_SUFFIX); String[] ssids = ListPreferenceMultiSelectWithValue.parseStoredValue(separatedValues); if (ssids != null) { result.wifiSSID = Arrays.asList(ssids); } else { result = null; } } else { result.wifiSSID = null; } } } } catch (Exception ex) { if (debug) Log.e(Synodroid.DS_TAG, "An exception occured while loading " + (local ? "local" : "public") + " connection", ex); } return result; }
diff --git a/src/org/waveprotocol/box/server/persistence/file/FileAccountStore.java b/src/org/waveprotocol/box/server/persistence/file/FileAccountStore.java index ecfbcc12..96ba5097 100644 --- a/src/org/waveprotocol/box/server/persistence/file/FileAccountStore.java +++ b/src/org/waveprotocol/box/server/persistence/file/FileAccountStore.java @@ -1,201 +1,211 @@ /** * Copyright 2010 Google Inc. * * 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.waveprotocol.box.server.persistence.file; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.google.inject.name.Named; import org.waveprotocol.box.server.account.AccountData; import org.waveprotocol.box.server.persistence.AccountStore; import org.waveprotocol.box.server.persistence.PersistenceException; import org.waveprotocol.box.server.persistence.protos.ProtoAccountDataSerializer; import org.waveprotocol.box.server.persistence.protos.ProtoAccountStoreData.ProtoAccountData; import org.waveprotocol.box.server.util.Log; import org.waveprotocol.wave.model.wave.ParticipantId; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.OutputStream; import java.util.Map; /** * A flat file based implementation of {@link AccountStore} * * @author [email protected] (Tad Glines) */ public class FileAccountStore implements AccountStore { private static final String ACCOUNT_FILE_EXTENSION = ".account"; private final String accountStoreBasePath; private final Map<ParticipantId, AccountData> accounts = Maps.newHashMap(); private static final Log LOG = Log.get(FileAccountStore.class); @Inject public FileAccountStore(@Named("account_store_directory") String accountStoreBasePath) { Preconditions.checkNotNull(accountStoreBasePath, "Requested path is null"); this.accountStoreBasePath = accountStoreBasePath; } @Override public void initializeAccountStore() throws PersistenceException { File baseDir = new File(accountStoreBasePath); // Make sure accountStoreBasePath exists. if (!baseDir.exists()) { // It doesn't so try and create it. if (!baseDir.mkdirs()) { throw new PersistenceException("Configured account store directory (" + accountStoreBasePath + ") doesn't exist and could not be created!"); } } // Make sure accountStoreBasePath is a directory. if (!baseDir.isDirectory()) { throw new PersistenceException("Configured account store path (" + accountStoreBasePath + ") isn't a directory!"); } // Make sure we can read accounts by trying to read one of the account files. File[] files = baseDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(ACCOUNT_FILE_EXTENSION); } }); if (files == null) { throw new PersistenceException("Configured account store directory (" + accountStoreBasePath + ") does not appear to be readable!"); } - // Open first file in list and try to read on byte from it. - try { - FileInputStream file = new FileInputStream(files[0]); - file.read(); - } catch (IOException e) { - throw new PersistenceException("Configured account store directory (" - + accountStoreBasePath + ") does not appear to be readable!"); + /* + * If file list isn't empty, try opening the first file in the list to make sure it + * is readable. If the first file is readable, then it is likely that the rest will + * be readable as well. + */ + if (files.length > 0) { + try { + FileInputStream file = new FileInputStream(files[0]); + file.read(); + } catch (IOException e) { + throw new PersistenceException("Failed to read '" + files[0].getName() + + "' in configured account store directory '" + accountStoreBasePath + + "'. The directory's contents do not appear to be readable.", e); + } } // Make sure accountStoreBasePath is a writable. try { File tmp = File.createTempFile("tempInitialization", ".bugus_account", baseDir); + FileOutputStream stream = new FileOutputStream(tmp); + stream.write(new byte[]{'H','e','l','l','o'}); + stream.close(); tmp.delete(); } catch (IOException e) { throw new PersistenceException("Configured account store directory (" - + accountStoreBasePath + ") does not appear to be writable!"); + + accountStoreBasePath + ") does not appear to be writable!", e); } } @Override public AccountData getAccount(ParticipantId id) throws PersistenceException { synchronized (accounts) { AccountData account = accounts.get(id); if (account == null) { account = readAccount(id); if (account != null) { accounts.put(id, account); } } return account; } } @Override public void putAccount(AccountData account) throws PersistenceException { synchronized (accounts) { Preconditions.checkNotNull(account); writeAccount(account); accounts.put(account.getId(), account); } } @Override public void removeAccount(ParticipantId id) throws PersistenceException { synchronized (accounts) { File file = new File(participantIdToFileName(id)); if (file.exists()) { if (!file.delete()) { throw new PersistenceException("Failed to delete account data associated with " + id.getAddress()); } } accounts.remove(id); } } private String participantIdToFileName(ParticipantId id) { return accountStoreBasePath + File.separator + id.getAddress().toLowerCase() + ACCOUNT_FILE_EXTENSION; } /* * This is here instead of in a utility class so that a more useful error message * can be generated. */ private void closeAndIgnoreException(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { // This should never happen in practice. But just in case... log it. LOG.warning("Failed to close account data file!", e); } } } private AccountData readAccount(ParticipantId id) throws PersistenceException { FileInputStream file = null; try { File accountFile = new File(participantIdToFileName(id)); if (!accountFile.exists()) { return null; } file = new FileInputStream(accountFile); ProtoAccountData data = ProtoAccountData.newBuilder().mergeFrom(file).build(); return ProtoAccountDataSerializer.deserialize(data); } catch (IOException e) { LOG.severe("Failed to read account data from disk!", e); throw new PersistenceException(e); } finally { closeAndIgnoreException(file); } } private void writeAccount(AccountData account) throws PersistenceException { OutputStream file = null; try { File accountFile = new File(participantIdToFileName(account.getId())); file = new FileOutputStream(accountFile); ProtoAccountData data = ProtoAccountDataSerializer.serialize(account); file.write(data.toByteArray()); file.flush(); } catch (IOException e) { LOG.severe("Failed to write account data to disk!", e); throw new PersistenceException(e); } finally { closeAndIgnoreException(file); } } }
false
true
public void initializeAccountStore() throws PersistenceException { File baseDir = new File(accountStoreBasePath); // Make sure accountStoreBasePath exists. if (!baseDir.exists()) { // It doesn't so try and create it. if (!baseDir.mkdirs()) { throw new PersistenceException("Configured account store directory (" + accountStoreBasePath + ") doesn't exist and could not be created!"); } } // Make sure accountStoreBasePath is a directory. if (!baseDir.isDirectory()) { throw new PersistenceException("Configured account store path (" + accountStoreBasePath + ") isn't a directory!"); } // Make sure we can read accounts by trying to read one of the account files. File[] files = baseDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(ACCOUNT_FILE_EXTENSION); } }); if (files == null) { throw new PersistenceException("Configured account store directory (" + accountStoreBasePath + ") does not appear to be readable!"); } // Open first file in list and try to read on byte from it. try { FileInputStream file = new FileInputStream(files[0]); file.read(); } catch (IOException e) { throw new PersistenceException("Configured account store directory (" + accountStoreBasePath + ") does not appear to be readable!"); } // Make sure accountStoreBasePath is a writable. try { File tmp = File.createTempFile("tempInitialization", ".bugus_account", baseDir); tmp.delete(); } catch (IOException e) { throw new PersistenceException("Configured account store directory (" + accountStoreBasePath + ") does not appear to be writable!"); } }
public void initializeAccountStore() throws PersistenceException { File baseDir = new File(accountStoreBasePath); // Make sure accountStoreBasePath exists. if (!baseDir.exists()) { // It doesn't so try and create it. if (!baseDir.mkdirs()) { throw new PersistenceException("Configured account store directory (" + accountStoreBasePath + ") doesn't exist and could not be created!"); } } // Make sure accountStoreBasePath is a directory. if (!baseDir.isDirectory()) { throw new PersistenceException("Configured account store path (" + accountStoreBasePath + ") isn't a directory!"); } // Make sure we can read accounts by trying to read one of the account files. File[] files = baseDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(ACCOUNT_FILE_EXTENSION); } }); if (files == null) { throw new PersistenceException("Configured account store directory (" + accountStoreBasePath + ") does not appear to be readable!"); } /* * If file list isn't empty, try opening the first file in the list to make sure it * is readable. If the first file is readable, then it is likely that the rest will * be readable as well. */ if (files.length > 0) { try { FileInputStream file = new FileInputStream(files[0]); file.read(); } catch (IOException e) { throw new PersistenceException("Failed to read '" + files[0].getName() + "' in configured account store directory '" + accountStoreBasePath + "'. The directory's contents do not appear to be readable.", e); } } // Make sure accountStoreBasePath is a writable. try { File tmp = File.createTempFile("tempInitialization", ".bugus_account", baseDir); FileOutputStream stream = new FileOutputStream(tmp); stream.write(new byte[]{'H','e','l','l','o'}); stream.close(); tmp.delete(); } catch (IOException e) { throw new PersistenceException("Configured account store directory (" + accountStoreBasePath + ") does not appear to be writable!", e); } }
diff --git a/org.eclipse.riena.core/src/org/eclipse/riena/internal/core/Activator.java b/org.eclipse.riena.core/src/org/eclipse/riena/internal/core/Activator.java index 137911e5c..ad82e5553 100644 --- a/org.eclipse.riena.core/src/org/eclipse/riena/internal/core/Activator.java +++ b/org.eclipse.riena.core/src/org/eclipse/riena/internal/core/Activator.java @@ -1,175 +1,176 @@ /******************************************************************************* * Copyright (c) 2007, 2008 compeople AG 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: * compeople AG - initial API and implementation *******************************************************************************/ package org.eclipse.riena.internal.core; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.variables.IStringVariableManager; import org.eclipse.core.variables.VariablesPlugin; import org.eclipse.equinox.log.Logger; import org.eclipse.riena.core.RienaConstants; import org.eclipse.riena.core.RienaPlugin; import org.eclipse.riena.internal.core.logging.LoggerMill; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; import org.osgi.framework.ServiceRegistration; import org.osgi.service.log.LogService; public class Activator extends RienaPlugin { /** * Bundles marked with this header set to <code>true</code> will be started * by Riena. */ public static final String RIENA_FORCE_START = "Riena-ForceStart"; //$NON-NLS-1$ // The plug-in ID public static final String PLUGIN_ID = "org.eclipse.riena.core"; //$NON-NLS-1$ // �startup� status of Riena private boolean active = false; private ServiceRegistration loggerMillServiceReg; private LoggerMill loggerMill; // The shared instance private static Activator plugin; { plugin = this; } /* * (non-Javadoc) * * @see * org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext * ) */ public void start(BundleContext context) throws Exception { super.start(context); Activator.plugin = this; startLogging(context); final Logger logger = getLogger(Activator.class); logStage(logger); startForcedRienaBundles(logger); active = true; } /** * */ private void startLogging(BundleContext context) { loggerMill = new LoggerMill(context); loggerMillServiceReg = context.registerService(LoggerMill.class.getName(), loggerMill, RienaConstants .newDefaultServiceProperties()); } /** * @param logger */ private void logStage(Logger logger) { IStringVariableManager variableManager = VariablesPlugin.getDefault().getStringVariableManager(); String stage; try { stage = variableManager.performStringSubstitution("Riena is running in stage '${riena.stage}'."); //$NON-NLS-1$ } catch (CoreException e) { stage = "No stage information set."; //$NON-NLS-1$ } logger.log(LogService.LOG_INFO, stage); } /** * Force starting of bundles that are marked true with the * <code>RIENA_FORCE_START</code> bundle header. * * @param context * @param logger * @throws BundleException */ private void startForcedRienaBundles(final Logger logger) throws BundleException { Bundle[] bundles = getContext().getBundles(); for (Bundle bundle : bundles) { boolean forceStart = Boolean.parseBoolean((String) bundle.getHeaders().get(RIENA_FORCE_START)); if (bundle.getState() != Bundle.ACTIVE && (bundle.getSymbolicName().equals("org.eclipse.equinox.cm") || bundle.getSymbolicName().equals( //$NON-NLS-1$ "org.eclipse.equinox.log"))) { //$NON-NLS-1$ forceStart = true; } if (!forceStart) { continue; } if (bundle.getState() == Bundle.RESOLVED) { try { bundle.start(); logger.log(LogService.LOG_INFO, "Forced start: '" + bundle.getSymbolicName() + "' succesful."); //$NON-NLS-1$ //$NON-NLS-2$ } catch (RuntimeException rte) { logger.log(LogService.LOG_ERROR, "Forced start: '" + bundle.getSymbolicName() //$NON-NLS-1$ + "' failed with exception.", rte); //$NON-NLS-1$ throw rte; } } else if (bundle.getState() == Bundle.STARTING && Constants.ACTIVATION_LAZY.equals(bundle.getHeaders().get(Constants.BUNDLE_ACTIVATIONPOLICY))) { try { bundle.start(); logger.log(LogService.LOG_INFO, "Forced <<lazy>> start(): '" + bundle.getSymbolicName() + "' succesful."); //$NON-NLS-1$ //$NON-NLS-2$ } catch (BundleException be) { logger.log(LogService.LOG_WARNING, "Forced <<lazy>> start(): '" + bundle.getSymbolicName() //$NON-NLS-1$ - + "' failed but may succeed (bundle state is in transition):\n\t\t" + be.getMessage()); //$NON-NLS-1$ + + "' failed but may succeed (bundle state is in transition):\n\t\t" + be.getMessage() //$NON-NLS-1$ + + (be.getCause() != null ? " cause: " + be.getCause() : "")); //$NON-NLS-1$ //$NON-NLS-2$ } catch (RuntimeException rte) { logger.log(LogService.LOG_ERROR, "Forced <<lazy>> start(): '" + bundle.getSymbolicName() //$NON-NLS-1$ + "' failed with exception.", rte); //$NON-NLS-1$ throw rte; } } else if (bundle.getState() == Bundle.INSTALLED) { logger.log(LogService.LOG_ERROR, "Forced start: '" + bundle.getSymbolicName() + "' failed. Header '" //$NON-NLS-1$ //$NON-NLS-2$ + RIENA_FORCE_START + "' is set but is only in state INSTALLED (not RESOLVED)."); //$NON-NLS-1$ } else if (bundle.getState() == Bundle.ACTIVE) { logger.log(LogService.LOG_DEBUG, "Forced start: '" + bundle.getSymbolicName() + "' is already ACTIVE."); //$NON-NLS-1$ //$NON-NLS-2$ } } } /* * @see * org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { active = false; Activator.plugin = null; context.ungetService(loggerMillServiceReg.getReference()); super.stop(context); } /** * Get the plugin instance. * * @return */ public static Activator getDefault() { return plugin; } /** * Riena status? * * @return */ public boolean isActive() { return active; } }
true
true
private void startForcedRienaBundles(final Logger logger) throws BundleException { Bundle[] bundles = getContext().getBundles(); for (Bundle bundle : bundles) { boolean forceStart = Boolean.parseBoolean((String) bundle.getHeaders().get(RIENA_FORCE_START)); if (bundle.getState() != Bundle.ACTIVE && (bundle.getSymbolicName().equals("org.eclipse.equinox.cm") || bundle.getSymbolicName().equals( //$NON-NLS-1$ "org.eclipse.equinox.log"))) { //$NON-NLS-1$ forceStart = true; } if (!forceStart) { continue; } if (bundle.getState() == Bundle.RESOLVED) { try { bundle.start(); logger.log(LogService.LOG_INFO, "Forced start: '" + bundle.getSymbolicName() + "' succesful."); //$NON-NLS-1$ //$NON-NLS-2$ } catch (RuntimeException rte) { logger.log(LogService.LOG_ERROR, "Forced start: '" + bundle.getSymbolicName() //$NON-NLS-1$ + "' failed with exception.", rte); //$NON-NLS-1$ throw rte; } } else if (bundle.getState() == Bundle.STARTING && Constants.ACTIVATION_LAZY.equals(bundle.getHeaders().get(Constants.BUNDLE_ACTIVATIONPOLICY))) { try { bundle.start(); logger.log(LogService.LOG_INFO, "Forced <<lazy>> start(): '" + bundle.getSymbolicName() + "' succesful."); //$NON-NLS-1$ //$NON-NLS-2$ } catch (BundleException be) { logger.log(LogService.LOG_WARNING, "Forced <<lazy>> start(): '" + bundle.getSymbolicName() //$NON-NLS-1$ + "' failed but may succeed (bundle state is in transition):\n\t\t" + be.getMessage()); //$NON-NLS-1$ } catch (RuntimeException rte) { logger.log(LogService.LOG_ERROR, "Forced <<lazy>> start(): '" + bundle.getSymbolicName() //$NON-NLS-1$ + "' failed with exception.", rte); //$NON-NLS-1$ throw rte; } } else if (bundle.getState() == Bundle.INSTALLED) { logger.log(LogService.LOG_ERROR, "Forced start: '" + bundle.getSymbolicName() + "' failed. Header '" //$NON-NLS-1$ //$NON-NLS-2$ + RIENA_FORCE_START + "' is set but is only in state INSTALLED (not RESOLVED)."); //$NON-NLS-1$ } else if (bundle.getState() == Bundle.ACTIVE) { logger.log(LogService.LOG_DEBUG, "Forced start: '" + bundle.getSymbolicName() + "' is already ACTIVE."); //$NON-NLS-1$ //$NON-NLS-2$ } } }
private void startForcedRienaBundles(final Logger logger) throws BundleException { Bundle[] bundles = getContext().getBundles(); for (Bundle bundle : bundles) { boolean forceStart = Boolean.parseBoolean((String) bundle.getHeaders().get(RIENA_FORCE_START)); if (bundle.getState() != Bundle.ACTIVE && (bundle.getSymbolicName().equals("org.eclipse.equinox.cm") || bundle.getSymbolicName().equals( //$NON-NLS-1$ "org.eclipse.equinox.log"))) { //$NON-NLS-1$ forceStart = true; } if (!forceStart) { continue; } if (bundle.getState() == Bundle.RESOLVED) { try { bundle.start(); logger.log(LogService.LOG_INFO, "Forced start: '" + bundle.getSymbolicName() + "' succesful."); //$NON-NLS-1$ //$NON-NLS-2$ } catch (RuntimeException rte) { logger.log(LogService.LOG_ERROR, "Forced start: '" + bundle.getSymbolicName() //$NON-NLS-1$ + "' failed with exception.", rte); //$NON-NLS-1$ throw rte; } } else if (bundle.getState() == Bundle.STARTING && Constants.ACTIVATION_LAZY.equals(bundle.getHeaders().get(Constants.BUNDLE_ACTIVATIONPOLICY))) { try { bundle.start(); logger.log(LogService.LOG_INFO, "Forced <<lazy>> start(): '" + bundle.getSymbolicName() + "' succesful."); //$NON-NLS-1$ //$NON-NLS-2$ } catch (BundleException be) { logger.log(LogService.LOG_WARNING, "Forced <<lazy>> start(): '" + bundle.getSymbolicName() //$NON-NLS-1$ + "' failed but may succeed (bundle state is in transition):\n\t\t" + be.getMessage() //$NON-NLS-1$ + (be.getCause() != null ? " cause: " + be.getCause() : "")); //$NON-NLS-1$ //$NON-NLS-2$ } catch (RuntimeException rte) { logger.log(LogService.LOG_ERROR, "Forced <<lazy>> start(): '" + bundle.getSymbolicName() //$NON-NLS-1$ + "' failed with exception.", rte); //$NON-NLS-1$ throw rte; } } else if (bundle.getState() == Bundle.INSTALLED) { logger.log(LogService.LOG_ERROR, "Forced start: '" + bundle.getSymbolicName() + "' failed. Header '" //$NON-NLS-1$ //$NON-NLS-2$ + RIENA_FORCE_START + "' is set but is only in state INSTALLED (not RESOLVED)."); //$NON-NLS-1$ } else if (bundle.getState() == Bundle.ACTIVE) { logger.log(LogService.LOG_DEBUG, "Forced start: '" + bundle.getSymbolicName() + "' is already ACTIVE."); //$NON-NLS-1$ //$NON-NLS-2$ } } }
diff --git a/core/plugins/org.eclipse.dltk.ui/src/org/eclipse/dltk/internal/ui/text/LineComparator.java b/core/plugins/org.eclipse.dltk.ui/src/org/eclipse/dltk/internal/ui/text/LineComparator.java index 57926c777..28325fdc7 100644 --- a/core/plugins/org.eclipse.dltk.ui/src/org/eclipse/dltk/internal/ui/text/LineComparator.java +++ b/core/plugins/org.eclipse.dltk.ui/src/org/eclipse/dltk/internal/ui/text/LineComparator.java @@ -1,113 +1,118 @@ /******************************************************************************* * Copyright (c) 2007, 2008 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.dltk.internal.ui.text; import java.util.ArrayList; import org.eclipse.compare.rangedifferencer.IRangeComparator; import org.eclipse.dltk.ui.DLTKUIPlugin; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; /** * This implementation of <code>IRangeComparator</code> compares lines of a * document. The lines are compared using a DJB hash function. * * @since 3.0 */ public class LineComparator implements IRangeComparator { private final IDocument fDocument; private final ArrayList<Integer> fHashes; /** * Create a line comparator for the given document. * * @param document */ public LineComparator(IDocument document) { fDocument = document; fHashes = new ArrayList<Integer>(fDocument.getNumberOfLines()); } /* * @see * org.eclipse.compare.rangedifferencer.IRangeComparator#getRangeCount() */ public int getRangeCount() { return fDocument.getNumberOfLines(); } /* * @see * org.eclipse.compare.rangedifferencer.IRangeComparator#rangesEqual(int, * org.eclipse.compare.rangedifferencer.IRangeComparator, int) */ public boolean rangesEqual(int thisIndex, IRangeComparator other, int otherIndex) { try { return getHash(thisIndex).equals( ((LineComparator) other).getHash(otherIndex)); } catch (BadLocationException e) { DLTKUIPlugin.log(e); return false; } } /* * @see * org.eclipse.compare.rangedifferencer.IRangeComparator#skipRangeComparison * (int, int, org.eclipse.compare.rangedifferencer.IRangeComparator) */ public boolean skipRangeComparison(int length, int maxLength, IRangeComparator other) { return false; } /** * @param line * the number of the line in the document to get the hash for * @return the hash of the line * @throws BadLocationException * if the line number is invalid */ private Integer getHash(int line) throws BadLocationException { - Integer hash = (Integer) fHashes.get(line); + Integer hash = null; + if (fHashes.size() > line) { + hash = (Integer) fHashes.get(line); + } if (hash == null) { IRegion lineRegion = fDocument.getLineInformation(line); String lineContents = fDocument.get(lineRegion.getOffset(), lineRegion.getLength()); hash = new Integer(computeDJBHash(lineContents)); + while (fHashes.size() <= line) + fHashes.add(null); fHashes.set(line, hash); } return hash; } /** * Compute a hash using the DJB hash algorithm * * @param string * the string for which to compute a hash * @return the DJB hash value of the string */ private int computeDJBHash(String string) { int hash = 5381; int len = string.length(); for (int i = 0; i < len; i++) { char ch = string.charAt(i); hash = (hash << 5) + hash + ch; } return hash; } }
false
true
private Integer getHash(int line) throws BadLocationException { Integer hash = (Integer) fHashes.get(line); if (hash == null) { IRegion lineRegion = fDocument.getLineInformation(line); String lineContents = fDocument.get(lineRegion.getOffset(), lineRegion.getLength()); hash = new Integer(computeDJBHash(lineContents)); fHashes.set(line, hash); } return hash; }
private Integer getHash(int line) throws BadLocationException { Integer hash = null; if (fHashes.size() > line) { hash = (Integer) fHashes.get(line); } if (hash == null) { IRegion lineRegion = fDocument.getLineInformation(line); String lineContents = fDocument.get(lineRegion.getOffset(), lineRegion.getLength()); hash = new Integer(computeDJBHash(lineContents)); while (fHashes.size() <= line) fHashes.add(null); fHashes.set(line, hash); } return hash; }
diff --git a/src/test/webui/objects/topology/ApplicationMap.java b/src/test/webui/objects/topology/ApplicationMap.java index caaee83d..5f42a2dd 100644 --- a/src/test/webui/objects/topology/ApplicationMap.java +++ b/src/test/webui/objects/topology/ApplicationMap.java @@ -1,464 +1,464 @@ package test.webui.objects.topology; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.RemoteWebElement; import org.openspaces.admin.pu.DeploymentStatus; import test.webui.interfaces.RenderedWebUIElement; import test.webui.resources.WebConstants; import com.thoughtworks.selenium.Selenium; import framework.utils.AssertUtils; import framework.utils.AssertUtils.RepetitiveConditionProvider; public class ApplicationMap { Selenium selenium; WebDriver driver; public static final String CONN_STATUS_OK = "conn-status-ok"; public static final String CONN_STATUS_WARN = "conn-status-warn"; public static final String CONN_STATUS_CRITICAL = "conn-status-critical"; public static final String CONN_STATUS_EMPTY = "conn-status-empty"; public ApplicationMap(Selenium selenium, WebDriver driver) { this.selenium = selenium; this.driver = driver; } public static ApplicationMap getInstance(Selenium selenium, WebDriver driver) { return new ApplicationMap(selenium, driver); } public enum DumpType { JVM_THREAD,NETWORK,LOG,PU,JVM_HEAP, } public enum ServiceTypes { UNDEFINED, LOAD_BALANCER, WEB_SERVER, SECURITY_SERVER, APP_SERVER, ESB_SERVER, MESSAGE_BUS, DATABASE, NOSQL_DB; } public class ApplicationNode implements RenderedWebUIElement { private String name; public ApplicationNode(String name) { this.name = getNameFromUI(name); } public String getName() { return name; } private String getNameFromUI(String name) { JavascriptExecutor js = (JavascriptExecutor) driver; try { String label = (String)js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].id"); return label; } catch (NoSuchElementException e) { return null; } catch (WebDriverException e) { return null; } } public List<Connector> getTargets() { List<Connector> connectors = new ArrayList<Connector>(); JavascriptExecutor js = (JavascriptExecutor) driver; try { Long length = (Long)js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].edges.length"); for (int i = 0 ; i < length ; i++) { String sourceNodeName = (String) js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].edges[" + i + "].source.id"); if (sourceNodeName.equals(name)) { String targetNodeName = (String) js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].edges[" + i + "].target.id"); String status = (String) js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].edges[" + i + "].style.status"); connectors.add(new Connector(new ApplicationNode(sourceNodeName), new ApplicationNode(targetNodeName), status)); } } return connectors; } catch (NoSuchElementException e) { return null; } catch (WebDriverException e) { return null; } } public List<Connector> getTargeted() { List<Connector> connectors = new ArrayList<Connector>(); JavascriptExecutor js = (JavascriptExecutor) driver; try { Long length = (Long)js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].edges.length"); for (int i = 0 ; i < length ; i++) { String sourceNodeName = (String) js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].edges[" + i + "].source.id"); String targetNodeName = (String) js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].edges[" + i + "].target.id"); if (targetNodeName.equals(name)) { String status = (String) js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].edges[" + i + "].style.status"); connectors.add(new Connector(new ApplicationNode(sourceNodeName), new ApplicationNode(targetNodeName), status)); } } return connectors; } catch (NoSuchElementException e) { return null; } catch (WebDriverException e) { return null; } } public List<Connector> getConnectors() { List<Connector> connectors = new ArrayList<Connector>(); JavascriptExecutor js = (JavascriptExecutor) driver; try { Long length = (Long)js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].edges.length"); for (int i = 0 ; i < length ; i++) { String sourceNodeName = (String) js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].edges[" + i + "].source.id"); String targetNodeName = (String) js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].edges[" + i + "].target.id"); String status = (String) js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].edges[" + i + "].style.status"); connectors.add(new Connector(new ApplicationNode(sourceNodeName), new ApplicationNode(targetNodeName), status)); } return connectors; } catch (NoSuchElementException e) { return null; } catch (WebDriverException e) { return null; } } @SuppressWarnings("unchecked") public List<String> getComponents() { List<String> comps = new ArrayList<String>(); JavascriptExecutor js = (JavascriptExecutor) driver; try { comps = (List<String>)js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].components"); return comps; } catch (NoSuchElementException e) { return null; } catch (WebDriverException e) { return null; } } public Long getxPosition() { Long xPosition = null; JavascriptExecutor js = (JavascriptExecutor) driver; try { xPosition = (Long)js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].layoutPosX"); return xPosition; } catch (NoSuchElementException e) { return null; } catch (WebDriverException e) { return null; } } public Long getyPosition() { Long xPosition = null; JavascriptExecutor js = (JavascriptExecutor) driver; try { xPosition = (Long)js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].layoutPosY"); return xPosition; } catch (NoSuchElementException e) { return null; } catch (WebDriverException e) { return null; } } public String getNodeColor() { JavascriptExecutor js = (JavascriptExecutor) driver; try { String color = (String)js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].nodeColor"); return color; } catch (NoSuchElementException e) { return null; } catch (WebDriverException e) { return null; } } public String getNodeType() { JavascriptExecutor js = (JavascriptExecutor) driver; try { String type = (String)js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].nodeType"); return type; } catch (NoSuchElementException e) { return null; } catch (WebDriverException e) { return null; } } public String getPuType() { JavascriptExecutor js = (JavascriptExecutor) driver; try { String type = (String)js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].puType"); return type; } catch (NoSuchElementException e) { return null; } catch (WebDriverException e) { return null; } } public DeploymentStatus getStatus() { String stat; JavascriptExecutor js = (JavascriptExecutor) driver; try { stat = (String)js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].status"); } catch (NoSuchElementException e) { return null; } catch (WebDriverException e) { return null; } if (stat.equals(WebConstants.ID.nodeStatusOk)) return DeploymentStatus.INTACT; if (stat.equals(WebConstants.ID.nodeStatusWarning)) return DeploymentStatus.COMPROMISED; if (stat.equals(WebConstants.ID.nodeStatusBroken)) return DeploymentStatus.BROKEN; else return DeploymentStatus.SCHEDULED; } public Long getPlannedInstances() { Long actualInstances = null; JavascriptExecutor js = (JavascriptExecutor) driver; try { actualInstances = (Long)js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].plannedInstances"); return actualInstances; } catch (NoSuchElementException e) { return null; } catch (WebDriverException e) { return null; } } public Long getActualInstances() { Long actualInstances = null; JavascriptExecutor js = (JavascriptExecutor) driver; try { actualInstances = (Long)js.executeScript("return this.dGraphAppMap.nodes[" + '"' + name + '"' + "].actualInstances"); return actualInstances; } catch (NoSuchElementException e) { return null; } catch (WebDriverException e) { return null; } } public boolean verifyNodeVisible() { return selenium.isTextPresent(this.getName()); } public void select() { selenium.click(WebConstants.ID.nodePath + this.name); } public void clickOnActions() { WebElement actionsButton = driver.findElement(By.id(WebConstants.ID.getActionToolBoxId(this.name))); actionsButton.click(); } public void clickOnInfo() { WebElement infoButton = driver.findElement(By.id(WebConstants.ID.getInfoToolBoxId(this.name))); infoButton.click(); } public void assertActionMenuVisible() { WebElement menu = driver.findElement(By.className("x-menu-list")); AssertUtils.assertTrue(menu.isDisplayed()); List<WebElement> items = menu.findElements(By.className("x-menu-list-item")); AssertUtils.assertTrue(items.size() == 2); } public void assertActionMenuNotVisible() { try { @SuppressWarnings("unused") WebElement menu = driver.findElement(By.className("x-menu-list")); Assert.fail("Menu list item is still visible"); } catch (WebDriverException e) { return; } } public void undeploy() { clickOnActions(); assertActionMenuVisible(); selenium.click(WebConstants.Xpath.pathToUndeployNode); selenium.click(WebConstants.Xpath.acceptAlert); assertActionMenuNotVisible(); } /** * generates dump of a processing unit from a pu node in the application map * this currently can only be executed fully on chrome browser * since it downloads files without opening a file dialog * @param reason - reason for requesting dump * @throws InterruptedException */ public void generateDump(String reason) throws InterruptedException { clickOnActions(); assertActionMenuVisible(); selenium.click(WebConstants.Xpath.pathToGenerateNodeDump); WebElement dumpWindow = driver.findElement(By.className("servicesDumpWindow")); WebElement reasonInput = dumpWindow.findElement(By.tagName("input")); reasonInput.sendKeys(reason); selenium.click(WebConstants.Xpath.generateDumpButton); Thread.sleep(5000); selenium.click(WebConstants.Xpath.closeWindow); assertActionMenuNotVisible(); } public void showInfo() { clickOnInfo(); } public boolean isDisplayed() { RemoteWebElement node = (RemoteWebElement) driver.findElement(By.id(WebConstants.ID.nodePath + this.name)); return node.isDisplayed(); } public void restart() { //TODO implement } public class Connector { private ApplicationNode source; private ApplicationNode target; private String status; public Connector(ApplicationNode source, ApplicationNode target, String status) { this.source = source; this.target = target; this.status = status; } public ApplicationNode getSource() { return source; } public ApplicationNode getTarget() { return target; } public String getStatus() { return status; } } } public void selectApplication(final String applicationName) { RepetitiveConditionProvider condition = new RepetitiveConditionProvider() { public boolean getCondition() { WebElement arrowDown = driver.findElement(By.id(WebConstants.ID.topologyCombobox)).findElement(By.className("icon")); arrowDown.click(); List<WebElement> visibleApps = driver.findElement(By.id(WebConstants.ID.topologyCombobox)).findElements(By.xpath("//li[@class='visible']")); WebElement activeApp = driver.findElement(By.id(WebConstants.ID.topologyCombobox)).findElement(By.xpath("//li[@class='visible active']")); List<WebElement> allApps = visibleApps; allApps.add(activeApp); WebElement app = null; for (WebElement e : allApps) { if (e.getText().equals(applicationName)) app = e; } - if (app.isDisplayed()) { + if ((app != null) && app.isDisplayed()) { app.click(); return true; } else { return false; } } }; AssertUtils.repetitiveAssertTrue("Application is not present in the applications menu panel", condition,10000); } public ApplicationNode getApplicationNode(String name) { ApplicationNode appNode = new ApplicationNode(name); if (appNode.getName() != null) { return appNode; } return null; } }
true
true
public void selectApplication(final String applicationName) { RepetitiveConditionProvider condition = new RepetitiveConditionProvider() { public boolean getCondition() { WebElement arrowDown = driver.findElement(By.id(WebConstants.ID.topologyCombobox)).findElement(By.className("icon")); arrowDown.click(); List<WebElement> visibleApps = driver.findElement(By.id(WebConstants.ID.topologyCombobox)).findElements(By.xpath("//li[@class='visible']")); WebElement activeApp = driver.findElement(By.id(WebConstants.ID.topologyCombobox)).findElement(By.xpath("//li[@class='visible active']")); List<WebElement> allApps = visibleApps; allApps.add(activeApp); WebElement app = null; for (WebElement e : allApps) { if (e.getText().equals(applicationName)) app = e; } if (app.isDisplayed()) { app.click(); return true; } else { return false; } } }; AssertUtils.repetitiveAssertTrue("Application is not present in the applications menu panel", condition,10000); }
public void selectApplication(final String applicationName) { RepetitiveConditionProvider condition = new RepetitiveConditionProvider() { public boolean getCondition() { WebElement arrowDown = driver.findElement(By.id(WebConstants.ID.topologyCombobox)).findElement(By.className("icon")); arrowDown.click(); List<WebElement> visibleApps = driver.findElement(By.id(WebConstants.ID.topologyCombobox)).findElements(By.xpath("//li[@class='visible']")); WebElement activeApp = driver.findElement(By.id(WebConstants.ID.topologyCombobox)).findElement(By.xpath("//li[@class='visible active']")); List<WebElement> allApps = visibleApps; allApps.add(activeApp); WebElement app = null; for (WebElement e : allApps) { if (e.getText().equals(applicationName)) app = e; } if ((app != null) && app.isDisplayed()) { app.click(); return true; } else { return false; } } }; AssertUtils.repetitiveAssertTrue("Application is not present in the applications menu panel", condition,10000); }
diff --git a/Team2RecipeFinder/src/ca/ualberta/team2recipefinder/views/ViewRecipeActivity.java b/Team2RecipeFinder/src/ca/ualberta/team2recipefinder/views/ViewRecipeActivity.java index c1e7a74..fe721fe 100644 --- a/Team2RecipeFinder/src/ca/ualberta/team2recipefinder/views/ViewRecipeActivity.java +++ b/Team2RecipeFinder/src/ca/ualberta/team2recipefinder/views/ViewRecipeActivity.java @@ -1,329 +1,331 @@ /* ViewRecipeAcivity * * Last Edited: March 7, 2013 * * */ package ca.ualberta.team2recipefinder.views; import java.io.File; import java.io.IOException; import java.util.List; import java.util.concurrent.ExecutionException; import ca.ualberta.team2recipefinder.R; import ca.ualberta.team2recipefinder.R.id; import ca.ualberta.team2recipefinder.R.layout; import ca.ualberta.team2recipefinder.controller.Controller; import ca.ualberta.team2recipefinder.controller.RecipeFinderApplication; import ca.ualberta.team2recipefinder.controller.SearchResult; import ca.ualberta.team2recipefinder.model.Ingredient; import ca.ualberta.team2recipefinder.model.Recipe; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; /** * ViewRecipeActivity is an android activity for displaying information about * a single recipe. * * @author cmput-301 team 2 * @see ca.ualberta.team2recipefinder.model.Recipe */ public class ViewRecipeActivity extends Activity implements ca.ualberta.team2recipefinder.views.View<Recipe> { long recipeID = -1; Recipe currentRecipe = new Recipe(); String serverID = ""; int imageIndex = 0; boolean isLocal; int source = -1; private static final int EDIT_SERVER_RECIPE = 0; Controller c; /** * Sets up all button listeners for this activity. Called when the activity is first created. * * @param savedInstanceState Bundle containing the activity's previously frozen state, if there was one. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_recipe); c = RecipeFinderApplication.getController(); Recipe localRecipe = null; if (savedInstanceState == null) { Bundle extras = getIntent().getExtras(); if (extras != null) { source = extras.getInt("source"); recipeID = extras.getLong("recipeID"); serverID = extras.getString("serverID"); localRecipe = c.getRecipe(recipeID); } } isLocal = localRecipe != null; if (source == SearchResult.SOURCE_LOCAL) { currentRecipe = localRecipe; } Button publishDownloadButton = (Button) findViewById(R.id.publish_download_button); publishDownloadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // if local, then publish if (source == SearchResult.SOURCE_LOCAL) { AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... arg0) { try { c.publishRecipe(currentRecipe); } catch (IOException e) { e.printStackTrace(); } return null; } }.execute(); try { task.get(); // if successful, mark the recipe as on the server currentRecipe.setOnServer(true); c.replaceRecipe(currentRecipe, currentRecipe.getRecipeID()); update(currentRecipe); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); Toast.makeText(ViewRecipeActivity.this, getString(R.string.no_connection), Toast.LENGTH_LONG).show(); } } // otherwise, save it locally else if (source == SearchResult.SOURCE_REMOTE) { c.addRecipe(currentRecipe); + isLocal = true; + update(currentRecipe); } } }); Button shareButton = (Button) findViewById(R.id.share_button); shareButton.setText("Share"); shareButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(ViewRecipeActivity.this, ShareRecipeActivity.class); intent.putExtra("recipeID", recipeID); startActivity(intent); } }); Button editButton = (Button) findViewById(R.id.edit_button); editButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(ViewRecipeActivity.this, EditRecipeActivity.class); intent.putExtra("source", source); if (source == SearchResult.SOURCE_LOCAL) { intent.putExtra("recipeID", recipeID); startActivity(intent); } else { intent.putExtra("serverID", serverID); startActivityForResult(intent, EDIT_SERVER_RECIPE); } } }); Button deleteButton = (Button) findViewById(R.id.delete_button); deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { /* CALL DELETE FROM CONTROLLER, EXIT ACTIVITY */ c.deleteRecipe(currentRecipe); finish(); } }); Button rightButton = (Button) findViewById(R.id.button_forward); rightButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (imageIndex < (currentRecipe.getAllPhotos().size()-1)) { imageIndex++; } update(currentRecipe); } }); Button leftButton = (Button) findViewById(R.id.button_back); leftButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (imageIndex > 0) { imageIndex--; } update(currentRecipe); } }); update(currentRecipe); currentRecipe.addView(this); } /** * Updates the current info being displayed. Use if the recipe is changed. * * @param model the model that called the method */ public void update(Recipe model) { Button publishDownloadButton = (Button) findViewById(R.id.publish_download_button); if (source == SearchResult.SOURCE_LOCAL) { publishDownloadButton.setText("Publish"); // if already on server, user can not publish the recipe if (!c.canPublish(currentRecipe) || currentRecipe.getOnServer()) { publishDownloadButton.setEnabled(false); } } else { publishDownloadButton.setText("Download"); // you cannot download a recipe that you downloaded already if (isLocal) { publishDownloadButton.setEnabled(false); } AsyncTask<Void, Void, Recipe> task = (new AsyncTask<Void, Void, Recipe>() { @Override protected Recipe doInBackground(Void... arg0) { try { return c.downloadRecipe(serverID); } catch (IOException e) { e.printStackTrace(); } return null; } }).execute(); try { currentRecipe = task.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); Toast.makeText(ViewRecipeActivity.this, getString(R.string.no_connection), Toast.LENGTH_LONG).show(); finish(); } } Button editButton = (Button) findViewById(R.id.edit_button); editButton.setText("Edit"); Button deleteButton = (Button) findViewById(R.id.delete_button); deleteButton.setText("Delete"); if (source == SearchResult.SOURCE_LOCAL) { deleteButton.setEnabled(true); } else { deleteButton.setEnabled(false); } TextView recipeName = (TextView) findViewById(R.id.recipe_name); recipeName.setText(currentRecipe.getName()); TextView procedure = (TextView) findViewById(R.id.procedure_text); String procedureText = currentRecipe.getProcedure(); procedure.setText(procedureText); TextView ingredients = (TextView) findViewById(R.id.ingredients_text); List<Ingredient> ingredientTextArray = currentRecipe.getIngredients(); TextView comments = (TextView) findViewById(R.id.comment_text); List<String> commentsTextArray = currentRecipe.getAllComments(); String ingredientText = new String(); String nl = System.getProperty("line.separator"); for (int i = 0; i < ingredientTextArray.size(); i++) { ingredientText += ingredientTextArray.get(i).toString() + nl; } ingredients.setText(ingredientText); String commentsText = new String(); String cl = System.getProperty("line.separator"); for (int i = 0; i < commentsTextArray.size(); i++) { commentsText += commentsTextArray.get(i) + cl; } comments.setText(commentsText); ImageView pictureBox = (ImageView) findViewById(R.id.recipe_images); Bitmap image = currentRecipe.getPhoto(imageIndex); if (image != null) { pictureBox.setImageBitmap(image); } TextView imageInfo = (TextView) findViewById(R.id.image_numbers); String info; if (currentRecipe.hasPhotos()) { info = (imageIndex+1)+"/"+currentRecipe.getAllPhotos().size(); } else { info = "No photos for this recipe"; } imageInfo.setText(info); } /** * Called when the recipe is being edited remotely. Checks if the edit was okay * * @param requestCode the ID of the request code * @param resultCode the ID of the result code */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == EDIT_SERVER_RECIPE) { if (resultCode == RESULT_OK) { update(currentRecipe); } } } /** * Removes this view from the model */ @Override public void onDestroy() { super.onDestroy(); currentRecipe.removeView(this); } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_recipe); c = RecipeFinderApplication.getController(); Recipe localRecipe = null; if (savedInstanceState == null) { Bundle extras = getIntent().getExtras(); if (extras != null) { source = extras.getInt("source"); recipeID = extras.getLong("recipeID"); serverID = extras.getString("serverID"); localRecipe = c.getRecipe(recipeID); } } isLocal = localRecipe != null; if (source == SearchResult.SOURCE_LOCAL) { currentRecipe = localRecipe; } Button publishDownloadButton = (Button) findViewById(R.id.publish_download_button); publishDownloadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // if local, then publish if (source == SearchResult.SOURCE_LOCAL) { AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... arg0) { try { c.publishRecipe(currentRecipe); } catch (IOException e) { e.printStackTrace(); } return null; } }.execute(); try { task.get(); // if successful, mark the recipe as on the server currentRecipe.setOnServer(true); c.replaceRecipe(currentRecipe, currentRecipe.getRecipeID()); update(currentRecipe); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); Toast.makeText(ViewRecipeActivity.this, getString(R.string.no_connection), Toast.LENGTH_LONG).show(); } } // otherwise, save it locally else if (source == SearchResult.SOURCE_REMOTE) { c.addRecipe(currentRecipe); } } }); Button shareButton = (Button) findViewById(R.id.share_button); shareButton.setText("Share"); shareButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(ViewRecipeActivity.this, ShareRecipeActivity.class); intent.putExtra("recipeID", recipeID); startActivity(intent); } }); Button editButton = (Button) findViewById(R.id.edit_button); editButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(ViewRecipeActivity.this, EditRecipeActivity.class); intent.putExtra("source", source); if (source == SearchResult.SOURCE_LOCAL) { intent.putExtra("recipeID", recipeID); startActivity(intent); } else { intent.putExtra("serverID", serverID); startActivityForResult(intent, EDIT_SERVER_RECIPE); } } }); Button deleteButton = (Button) findViewById(R.id.delete_button); deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { /* CALL DELETE FROM CONTROLLER, EXIT ACTIVITY */ c.deleteRecipe(currentRecipe); finish(); } }); Button rightButton = (Button) findViewById(R.id.button_forward); rightButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (imageIndex < (currentRecipe.getAllPhotos().size()-1)) { imageIndex++; } update(currentRecipe); } }); Button leftButton = (Button) findViewById(R.id.button_back); leftButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (imageIndex > 0) { imageIndex--; } update(currentRecipe); } }); update(currentRecipe); currentRecipe.addView(this); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_recipe); c = RecipeFinderApplication.getController(); Recipe localRecipe = null; if (savedInstanceState == null) { Bundle extras = getIntent().getExtras(); if (extras != null) { source = extras.getInt("source"); recipeID = extras.getLong("recipeID"); serverID = extras.getString("serverID"); localRecipe = c.getRecipe(recipeID); } } isLocal = localRecipe != null; if (source == SearchResult.SOURCE_LOCAL) { currentRecipe = localRecipe; } Button publishDownloadButton = (Button) findViewById(R.id.publish_download_button); publishDownloadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // if local, then publish if (source == SearchResult.SOURCE_LOCAL) { AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... arg0) { try { c.publishRecipe(currentRecipe); } catch (IOException e) { e.printStackTrace(); } return null; } }.execute(); try { task.get(); // if successful, mark the recipe as on the server currentRecipe.setOnServer(true); c.replaceRecipe(currentRecipe, currentRecipe.getRecipeID()); update(currentRecipe); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); Toast.makeText(ViewRecipeActivity.this, getString(R.string.no_connection), Toast.LENGTH_LONG).show(); } } // otherwise, save it locally else if (source == SearchResult.SOURCE_REMOTE) { c.addRecipe(currentRecipe); isLocal = true; update(currentRecipe); } } }); Button shareButton = (Button) findViewById(R.id.share_button); shareButton.setText("Share"); shareButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(ViewRecipeActivity.this, ShareRecipeActivity.class); intent.putExtra("recipeID", recipeID); startActivity(intent); } }); Button editButton = (Button) findViewById(R.id.edit_button); editButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(ViewRecipeActivity.this, EditRecipeActivity.class); intent.putExtra("source", source); if (source == SearchResult.SOURCE_LOCAL) { intent.putExtra("recipeID", recipeID); startActivity(intent); } else { intent.putExtra("serverID", serverID); startActivityForResult(intent, EDIT_SERVER_RECIPE); } } }); Button deleteButton = (Button) findViewById(R.id.delete_button); deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { /* CALL DELETE FROM CONTROLLER, EXIT ACTIVITY */ c.deleteRecipe(currentRecipe); finish(); } }); Button rightButton = (Button) findViewById(R.id.button_forward); rightButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (imageIndex < (currentRecipe.getAllPhotos().size()-1)) { imageIndex++; } update(currentRecipe); } }); Button leftButton = (Button) findViewById(R.id.button_back); leftButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (imageIndex > 0) { imageIndex--; } update(currentRecipe); } }); update(currentRecipe); currentRecipe.addView(this); }
diff --git a/src/au/com/addstar/truehardcore/CommandTH.java b/src/au/com/addstar/truehardcore/CommandTH.java index 9630c0c..c35f50b 100644 --- a/src/au/com/addstar/truehardcore/CommandTH.java +++ b/src/au/com/addstar/truehardcore/CommandTH.java @@ -1,113 +1,113 @@ package au.com.addstar.truehardcore; /* * TrueHardcore * Copyright (C) 2013 add5tar <copyright at addstar dot com dot au> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import au.com.addstar.truehardcore.HardcorePlayers.HardcorePlayer; public class CommandTH implements CommandExecutor { private TrueHardcore plugin; public CommandTH(TrueHardcore instance) { plugin = instance; } /* * Handle the /truehardcore command */ public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { String action = ""; if (args.length > 0) { action = args[0].toUpperCase(); } if (action.equals("PLAY")) { if (Util.RequirePermission((Player) sender, "truehardcore.use")) { if (args.length > 1) { World world = plugin.getServer().getWorld(args[1]); if (world == null) { sender.sendMessage(ChatColor.RED + "Error: Unknown world!"); return true; } if (plugin.IsHardcoreWorld(world)) { plugin.PlayGame(world.getName(), (Player) sender); } else { sender.sendMessage(ChatColor.RED + "Error: That is not a hardcore world!"); } } else { sender.sendMessage(ChatColor.YELLOW + "Usage: /th play <world>"); } } } else if (action.equals("LEAVE")) { plugin.LeaveGame((Player) sender); } else if (action.equals("INFO")) { HardcorePlayer hcp = null; if (args.length == 1) { if (sender instanceof Player) { Player player = (Player) sender; hcp = plugin.HCPlayers.Get(player); } else { sender.sendMessage(ChatColor.RED + "Usage: /th info <player> [world]"); } } else if (args.length == 2) { Player player = (Player) plugin.getServer().getPlayer(args[2]); if (player != null) { hcp = plugin.HCPlayers.Get(player); } else { sender.sendMessage(ChatColor.RED + "Unknown player"); } } else if (args.length == 3) { - hcp = plugin.HCPlayers.Get(args[3], args[2]); + hcp = plugin.HCPlayers.Get(args[2], args[1]); } if (hcp != null) { sender.sendMessage("Player: " + hcp.getPlayerName()); sender.sendMessage("World: " + hcp.getWorld()); sender.sendMessage("State: " + hcp.getState()); sender.sendMessage("Current XP: " + hcp.getExp()); sender.sendMessage("Total Score: " + hcp.getScore()); sender.sendMessage("Total Deaths: " + hcp.getDeaths()); sender.sendMessage("Top Score: " + hcp.getTopScore()); } } else if (action.equals("LIST")) { for (String key : plugin.HCPlayers.AllRecords().keySet()) { HardcorePlayer hcp = plugin.HCPlayers.Get(key); sender.sendMessage(Util.padRight(key, 30) + " " + hcp.getState()); } } else { sender.sendMessage(ChatColor.LIGHT_PURPLE + "TrueHardcore Commands:"); sender.sendMessage(ChatColor.AQUA + "/th play " + ChatColor.YELLOW + ": Start or resume your hardcore game"); sender.sendMessage(ChatColor.AQUA + "/th leave " + ChatColor.YELLOW + ": Leave the hardcore game (progress is saved)"); } return true; } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { String action = ""; if (args.length > 0) { action = args[0].toUpperCase(); } if (action.equals("PLAY")) { if (Util.RequirePermission((Player) sender, "truehardcore.use")) { if (args.length > 1) { World world = plugin.getServer().getWorld(args[1]); if (world == null) { sender.sendMessage(ChatColor.RED + "Error: Unknown world!"); return true; } if (plugin.IsHardcoreWorld(world)) { plugin.PlayGame(world.getName(), (Player) sender); } else { sender.sendMessage(ChatColor.RED + "Error: That is not a hardcore world!"); } } else { sender.sendMessage(ChatColor.YELLOW + "Usage: /th play <world>"); } } } else if (action.equals("LEAVE")) { plugin.LeaveGame((Player) sender); } else if (action.equals("INFO")) { HardcorePlayer hcp = null; if (args.length == 1) { if (sender instanceof Player) { Player player = (Player) sender; hcp = plugin.HCPlayers.Get(player); } else { sender.sendMessage(ChatColor.RED + "Usage: /th info <player> [world]"); } } else if (args.length == 2) { Player player = (Player) plugin.getServer().getPlayer(args[2]); if (player != null) { hcp = plugin.HCPlayers.Get(player); } else { sender.sendMessage(ChatColor.RED + "Unknown player"); } } else if (args.length == 3) { hcp = plugin.HCPlayers.Get(args[3], args[2]); } if (hcp != null) { sender.sendMessage("Player: " + hcp.getPlayerName()); sender.sendMessage("World: " + hcp.getWorld()); sender.sendMessage("State: " + hcp.getState()); sender.sendMessage("Current XP: " + hcp.getExp()); sender.sendMessage("Total Score: " + hcp.getScore()); sender.sendMessage("Total Deaths: " + hcp.getDeaths()); sender.sendMessage("Top Score: " + hcp.getTopScore()); } } else if (action.equals("LIST")) { for (String key : plugin.HCPlayers.AllRecords().keySet()) { HardcorePlayer hcp = plugin.HCPlayers.Get(key); sender.sendMessage(Util.padRight(key, 30) + " " + hcp.getState()); } } else { sender.sendMessage(ChatColor.LIGHT_PURPLE + "TrueHardcore Commands:"); sender.sendMessage(ChatColor.AQUA + "/th play " + ChatColor.YELLOW + ": Start or resume your hardcore game"); sender.sendMessage(ChatColor.AQUA + "/th leave " + ChatColor.YELLOW + ": Leave the hardcore game (progress is saved)"); } return true; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { String action = ""; if (args.length > 0) { action = args[0].toUpperCase(); } if (action.equals("PLAY")) { if (Util.RequirePermission((Player) sender, "truehardcore.use")) { if (args.length > 1) { World world = plugin.getServer().getWorld(args[1]); if (world == null) { sender.sendMessage(ChatColor.RED + "Error: Unknown world!"); return true; } if (plugin.IsHardcoreWorld(world)) { plugin.PlayGame(world.getName(), (Player) sender); } else { sender.sendMessage(ChatColor.RED + "Error: That is not a hardcore world!"); } } else { sender.sendMessage(ChatColor.YELLOW + "Usage: /th play <world>"); } } } else if (action.equals("LEAVE")) { plugin.LeaveGame((Player) sender); } else if (action.equals("INFO")) { HardcorePlayer hcp = null; if (args.length == 1) { if (sender instanceof Player) { Player player = (Player) sender; hcp = plugin.HCPlayers.Get(player); } else { sender.sendMessage(ChatColor.RED + "Usage: /th info <player> [world]"); } } else if (args.length == 2) { Player player = (Player) plugin.getServer().getPlayer(args[2]); if (player != null) { hcp = plugin.HCPlayers.Get(player); } else { sender.sendMessage(ChatColor.RED + "Unknown player"); } } else if (args.length == 3) { hcp = plugin.HCPlayers.Get(args[2], args[1]); } if (hcp != null) { sender.sendMessage("Player: " + hcp.getPlayerName()); sender.sendMessage("World: " + hcp.getWorld()); sender.sendMessage("State: " + hcp.getState()); sender.sendMessage("Current XP: " + hcp.getExp()); sender.sendMessage("Total Score: " + hcp.getScore()); sender.sendMessage("Total Deaths: " + hcp.getDeaths()); sender.sendMessage("Top Score: " + hcp.getTopScore()); } } else if (action.equals("LIST")) { for (String key : plugin.HCPlayers.AllRecords().keySet()) { HardcorePlayer hcp = plugin.HCPlayers.Get(key); sender.sendMessage(Util.padRight(key, 30) + " " + hcp.getState()); } } else { sender.sendMessage(ChatColor.LIGHT_PURPLE + "TrueHardcore Commands:"); sender.sendMessage(ChatColor.AQUA + "/th play " + ChatColor.YELLOW + ": Start or resume your hardcore game"); sender.sendMessage(ChatColor.AQUA + "/th leave " + ChatColor.YELLOW + ": Leave the hardcore game (progress is saved)"); } return true; }
diff --git a/xsdlib/src/com/sun/msv/datatype/xsd/LanguageType.java b/xsdlib/src/com/sun/msv/datatype/xsd/LanguageType.java index 608d014b..d35cde4e 100644 --- a/xsdlib/src/com/sun/msv/datatype/xsd/LanguageType.java +++ b/xsdlib/src/com/sun/msv/datatype/xsd/LanguageType.java @@ -1,62 +1,63 @@ /* * @(#)$Id$ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.tranquilo.datatype; import java.util.Hashtable; /** * "language" type. * * See http://www.w3.org/TR/xmlschema-2/#language for the spec */ public class LanguageType extends TokenType { public static final LanguageType theInstance = new LanguageType(); private LanguageType() { super("language"); } public Object convertToValue( String content, ValidationContextProvider context ) { /* RFC1766 defines the following BNF Language-Tag = Primary-tag *( "-" Subtag ) Primary-tag = 1*8ALPHA Subtag = 1*8ALPHA Whitespace is not allowed within the tag. + All tags are to be treated as case insensitive. */ final int len = content.length(); int i=0; int tokenSize=0; while( i<len ) { - final char ch = content.charAt(i); + final char ch = content.charAt(i++); if( ('a'<=ch && ch<='z') || ('A'<=ch && ch<='Z') ) { tokenSize++; if( tokenSize==9 ) return null; // maximum 8 characters are allowed. } else if( ch=='-' ) { if( tokenSize==0 ) return null; // at least one alphabet preceeds '-' tokenSize=0; } else return null; // invalid characters } if( tokenSize==0 ) return null; // this means either string is empty or ends with '-' - return content; + return content.toLowerCase(); } }
false
true
public Object convertToValue( String content, ValidationContextProvider context ) { /* RFC1766 defines the following BNF Language-Tag = Primary-tag *( "-" Subtag ) Primary-tag = 1*8ALPHA Subtag = 1*8ALPHA Whitespace is not allowed within the tag. */ final int len = content.length(); int i=0; int tokenSize=0; while( i<len ) { final char ch = content.charAt(i); if( ('a'<=ch && ch<='z') || ('A'<=ch && ch<='Z') ) { tokenSize++; if( tokenSize==9 ) return null; // maximum 8 characters are allowed. } else if( ch=='-' ) { if( tokenSize==0 ) return null; // at least one alphabet preceeds '-' tokenSize=0; } else return null; // invalid characters } if( tokenSize==0 ) return null; // this means either string is empty or ends with '-' return content; }
public Object convertToValue( String content, ValidationContextProvider context ) { /* RFC1766 defines the following BNF Language-Tag = Primary-tag *( "-" Subtag ) Primary-tag = 1*8ALPHA Subtag = 1*8ALPHA Whitespace is not allowed within the tag. All tags are to be treated as case insensitive. */ final int len = content.length(); int i=0; int tokenSize=0; while( i<len ) { final char ch = content.charAt(i++); if( ('a'<=ch && ch<='z') || ('A'<=ch && ch<='Z') ) { tokenSize++; if( tokenSize==9 ) return null; // maximum 8 characters are allowed. } else if( ch=='-' ) { if( tokenSize==0 ) return null; // at least one alphabet preceeds '-' tokenSize=0; } else return null; // invalid characters } if( tokenSize==0 ) return null; // this means either string is empty or ends with '-' return content.toLowerCase(); }
diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java b/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java index 37eced5d6..236c198ad 100644 --- a/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java +++ b/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java @@ -1,302 +1,312 @@ /* * Copyright (C) 2011 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.android.inputmethod.latin; import android.content.ContentResolver; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.database.Cursor; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import java.io.BufferedInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; /** * Group class for static methods to help with creation and getting of the binary dictionary * file from the dictionary provider */ public class BinaryDictionaryFileDumper { private static final String TAG = BinaryDictionaryFileDumper.class.getSimpleName(); private static final boolean DEBUG = false; /** * The size of the temporary buffer to copy files. */ private static final int FILE_READ_BUFFER_SIZE = 1024; // TODO: make the following data common with the native code private static final byte[] MAGIC_NUMBER_VERSION_1 = new byte[] { (byte)0x78, (byte)0xB1, (byte)0x00, (byte)0x00 }; private static final byte[] MAGIC_NUMBER_VERSION_2 = new byte[] { (byte)0x9B, (byte)0xC1, (byte)0x3A, (byte)0xFE }; private static final String DICTIONARY_PROJECTION[] = { "id" }; public static final String QUERY_PARAMETER_MAY_PROMPT_USER = "mayPrompt"; public static final String QUERY_PARAMETER_TRUE = "true"; public static final String QUERY_PARAMETER_DELETE_RESULT = "result"; public static final String QUERY_PARAMETER_SUCCESS = "success"; public static final String QUERY_PARAMETER_FAILURE = "failure"; // Prevents this class to be accidentally instantiated. private BinaryDictionaryFileDumper() { } /** * Returns a URI builder pointing to the dictionary pack. * * This creates a URI builder able to build a URI pointing to the dictionary * pack content provider for a specific dictionary id. */ private static Uri.Builder getProviderUriBuilder(final String path) { return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) .authority(BinaryDictionary.DICTIONARY_PACK_AUTHORITY).appendPath( path); } /** * Queries a content provider for the list of word lists for a specific locale * available to copy into Latin IME. */ private static List<WordListInfo> getWordListWordListInfos(final Locale locale, final Context context, final boolean hasDefaultWordList) { final ContentResolver resolver = context.getContentResolver(); final Uri.Builder builder = getProviderUriBuilder(locale.toString()); if (!hasDefaultWordList) { builder.appendQueryParameter(QUERY_PARAMETER_MAY_PROMPT_USER, QUERY_PARAMETER_TRUE); } final Uri dictionaryPackUri = builder.build(); final Cursor c = resolver.query(dictionaryPackUri, DICTIONARY_PROJECTION, null, null, null); if (null == c) return Collections.<WordListInfo>emptyList(); if (c.getCount() <= 0 || !c.moveToFirst()) { c.close(); return Collections.<WordListInfo>emptyList(); } try { final List<WordListInfo> list = new ArrayList<WordListInfo>(); do { final String wordListId = c.getString(0); final String wordListLocale = c.getString(1); if (TextUtils.isEmpty(wordListId)) continue; list.add(new WordListInfo(wordListId, wordListLocale)); } while (c.moveToNext()); c.close(); return list; } catch (Exception e) { // Just in case we hit a problem in communication with the dictionary pack. // We don't want to die. Log.e(TAG, "Exception communicating with the dictionary pack : " + e); return Collections.<WordListInfo>emptyList(); } } /** * Helper method to encapsulate exception handling. */ private static AssetFileDescriptor openAssetFileDescriptor(final ContentResolver resolver, final Uri uri) { try { return resolver.openAssetFileDescriptor(uri, "r"); } catch (FileNotFoundException e) { // I don't want to log the word list URI here for security concerns Log.e(TAG, "Could not find a word list from the dictionary provider."); return null; } } /** * Caches a word list the id of which is passed as an argument. This will write the file * to the cache file name designated by its id and locale, overwriting it if already present * and creating it (and its containing directory) if necessary. */ private static AssetFileAddress cacheWordList(final String id, final String locale, final ContentResolver resolver, final Context context) { final int COMPRESSED_CRYPTED_COMPRESSED = 0; final int CRYPTED_COMPRESSED = 1; final int COMPRESSED_CRYPTED = 2; final int COMPRESSED_ONLY = 3; final int CRYPTED_ONLY = 4; final int NONE = 5; final int MODE_MIN = COMPRESSED_CRYPTED_COMPRESSED; final int MODE_MAX = NONE; final Uri.Builder wordListUriBuilder = getProviderUriBuilder(id); - final String outputFileName = BinaryDictionaryGetter.getCacheFileName(id, locale, context); + final String finalFileName = BinaryDictionaryGetter.getCacheFileName(id, locale, context); + final String tempFileName = finalFileName + ".tmp"; for (int mode = MODE_MIN; mode <= MODE_MAX; ++mode) { InputStream originalSourceStream = null; InputStream inputStream = null; File outputFile = null; FileOutputStream outputStream = null; AssetFileDescriptor afd = null; final Uri wordListUri = wordListUriBuilder.build(); try { // Open input. afd = openAssetFileDescriptor(resolver, wordListUri); // If we can't open it at all, don't even try a number of times. if (null == afd) return null; originalSourceStream = afd.createInputStream(); // Open output. - outputFile = new File(outputFileName); + outputFile = new File(tempFileName); + // Just to be sure, delete the file. This may fail silently, and return false: this + // is the right thing to do, as we just want to continue anyway. + outputFile.delete(); outputStream = new FileOutputStream(outputFile); // Get the appropriate decryption method for this try switch (mode) { case COMPRESSED_CRYPTED_COMPRESSED: inputStream = FileTransforms.getUncompressedStream( FileTransforms.getDecryptedStream( FileTransforms.getUncompressedStream( originalSourceStream))); break; case CRYPTED_COMPRESSED: inputStream = FileTransforms.getUncompressedStream( FileTransforms.getDecryptedStream(originalSourceStream)); break; case COMPRESSED_CRYPTED: inputStream = FileTransforms.getDecryptedStream( FileTransforms.getUncompressedStream(originalSourceStream)); break; case COMPRESSED_ONLY: inputStream = FileTransforms.getUncompressedStream(originalSourceStream); break; case CRYPTED_ONLY: inputStream = FileTransforms.getDecryptedStream(originalSourceStream); break; case NONE: inputStream = originalSourceStream; break; } checkMagicAndCopyFileTo(new BufferedInputStream(inputStream), outputStream); + outputStream.flush(); + outputStream.close(); + final File finalFile = new File(finalFileName); + if (!outputFile.renameTo(finalFile)) { + throw new IOException("Can't move the file to its final name"); + } wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT, QUERY_PARAMETER_SUCCESS); if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) { Log.e(TAG, "Could not have the dictionary pack delete a word list"); } - BinaryDictionaryGetter.removeFilesWithIdExcept(context, id, outputFile); + BinaryDictionaryGetter.removeFilesWithIdExcept(context, id, finalFile); // Success! Close files (through the finally{} clause) and return. - return AssetFileAddress.makeFromFileName(outputFileName); + return AssetFileAddress.makeFromFileName(finalFileName); } catch (Exception e) { if (DEBUG) { Log.i(TAG, "Can't open word list in mode " + mode + " : " + e); } if (null != outputFile) { // This may or may not fail. The file may not have been created if the // exception was thrown before it could be. Hence, both failure and // success are expected outcomes, so we don't check the return value. outputFile.delete(); } // Try the next method. } finally { // Ignore exceptions while closing files. try { // inputStream.close() will close afd, we should not call afd.close(). if (null != inputStream) inputStream.close(); } catch (Exception e) { Log.e(TAG, "Exception while closing a cross-process file descriptor : " + e); } try { if (null != outputStream) outputStream.close(); } catch (Exception e) { Log.e(TAG, "Exception while closing a file : " + e); } } } // We could not copy the file at all. This is very unexpected. // I'd rather not print the word list ID to the log out of security concerns Log.e(TAG, "Could not copy a word list. Will not be able to use it."); // If we can't copy it we should warn the dictionary provider so that it can mark it // as invalid. wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT, QUERY_PARAMETER_FAILURE); if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) { Log.e(TAG, "In addition, we were unable to delete it."); } return null; } /** * Queries a content provider for word list data for some locale and cache the returned files * * This will query a content provider for word list data for a given locale, and copy the * files locally so that they can be mmap'ed. This may overwrite previously cached word lists * with newer versions if a newer version is made available by the content provider. * @returns the addresses of the word list files, or null if no data could be obtained. * @throw FileNotFoundException if the provider returns non-existent data. * @throw IOException if the provider-returned data could not be read. */ public static List<AssetFileAddress> cacheWordListsFromContentProvider(final Locale locale, final Context context, final boolean hasDefaultWordList) { final ContentResolver resolver = context.getContentResolver(); final List<WordListInfo> idList = getWordListWordListInfos(locale, context, hasDefaultWordList); final List<AssetFileAddress> fileAddressList = new ArrayList<AssetFileAddress>(); for (WordListInfo id : idList) { final AssetFileAddress afd = cacheWordList(id.mId, id.mLocale, resolver, context); if (null != afd) { fileAddressList.add(afd); } } return fileAddressList; } /** * Copies the data in an input stream to a target file if the magic number matches. * * If the magic number does not match the expected value, this method throws an * IOException. Other usual conditions for IOException or FileNotFoundException * also apply. * * @param input the stream to be copied. * @param output an output stream to copy the data to. */ private static void checkMagicAndCopyFileTo(final BufferedInputStream input, final FileOutputStream output) throws FileNotFoundException, IOException { // Check the magic number final int length = MAGIC_NUMBER_VERSION_2.length; final byte[] magicNumberBuffer = new byte[length]; final int readMagicNumberSize = input.read(magicNumberBuffer, 0, length); if (readMagicNumberSize < length) { throw new IOException("Less bytes to read than the magic number length"); } if (!Arrays.equals(MAGIC_NUMBER_VERSION_2, magicNumberBuffer)) { if (!Arrays.equals(MAGIC_NUMBER_VERSION_1, magicNumberBuffer)) { throw new IOException("Wrong magic number for downloaded file"); } } output.write(magicNumberBuffer); // Actually copy the file final byte[] buffer = new byte[FILE_READ_BUFFER_SIZE]; for (int readBytes = input.read(buffer); readBytes >= 0; readBytes = input.read(buffer)) output.write(buffer, 0, readBytes); input.close(); } }
false
true
private static AssetFileAddress cacheWordList(final String id, final String locale, final ContentResolver resolver, final Context context) { final int COMPRESSED_CRYPTED_COMPRESSED = 0; final int CRYPTED_COMPRESSED = 1; final int COMPRESSED_CRYPTED = 2; final int COMPRESSED_ONLY = 3; final int CRYPTED_ONLY = 4; final int NONE = 5; final int MODE_MIN = COMPRESSED_CRYPTED_COMPRESSED; final int MODE_MAX = NONE; final Uri.Builder wordListUriBuilder = getProviderUriBuilder(id); final String outputFileName = BinaryDictionaryGetter.getCacheFileName(id, locale, context); for (int mode = MODE_MIN; mode <= MODE_MAX; ++mode) { InputStream originalSourceStream = null; InputStream inputStream = null; File outputFile = null; FileOutputStream outputStream = null; AssetFileDescriptor afd = null; final Uri wordListUri = wordListUriBuilder.build(); try { // Open input. afd = openAssetFileDescriptor(resolver, wordListUri); // If we can't open it at all, don't even try a number of times. if (null == afd) return null; originalSourceStream = afd.createInputStream(); // Open output. outputFile = new File(outputFileName); outputStream = new FileOutputStream(outputFile); // Get the appropriate decryption method for this try switch (mode) { case COMPRESSED_CRYPTED_COMPRESSED: inputStream = FileTransforms.getUncompressedStream( FileTransforms.getDecryptedStream( FileTransforms.getUncompressedStream( originalSourceStream))); break; case CRYPTED_COMPRESSED: inputStream = FileTransforms.getUncompressedStream( FileTransforms.getDecryptedStream(originalSourceStream)); break; case COMPRESSED_CRYPTED: inputStream = FileTransforms.getDecryptedStream( FileTransforms.getUncompressedStream(originalSourceStream)); break; case COMPRESSED_ONLY: inputStream = FileTransforms.getUncompressedStream(originalSourceStream); break; case CRYPTED_ONLY: inputStream = FileTransforms.getDecryptedStream(originalSourceStream); break; case NONE: inputStream = originalSourceStream; break; } checkMagicAndCopyFileTo(new BufferedInputStream(inputStream), outputStream); wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT, QUERY_PARAMETER_SUCCESS); if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) { Log.e(TAG, "Could not have the dictionary pack delete a word list"); } BinaryDictionaryGetter.removeFilesWithIdExcept(context, id, outputFile); // Success! Close files (through the finally{} clause) and return. return AssetFileAddress.makeFromFileName(outputFileName); } catch (Exception e) { if (DEBUG) { Log.i(TAG, "Can't open word list in mode " + mode + " : " + e); } if (null != outputFile) { // This may or may not fail. The file may not have been created if the // exception was thrown before it could be. Hence, both failure and // success are expected outcomes, so we don't check the return value. outputFile.delete(); } // Try the next method. } finally { // Ignore exceptions while closing files. try { // inputStream.close() will close afd, we should not call afd.close(). if (null != inputStream) inputStream.close(); } catch (Exception e) { Log.e(TAG, "Exception while closing a cross-process file descriptor : " + e); } try { if (null != outputStream) outputStream.close(); } catch (Exception e) { Log.e(TAG, "Exception while closing a file : " + e); } } } // We could not copy the file at all. This is very unexpected. // I'd rather not print the word list ID to the log out of security concerns Log.e(TAG, "Could not copy a word list. Will not be able to use it."); // If we can't copy it we should warn the dictionary provider so that it can mark it // as invalid. wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT, QUERY_PARAMETER_FAILURE); if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) { Log.e(TAG, "In addition, we were unable to delete it."); } return null; }
private static AssetFileAddress cacheWordList(final String id, final String locale, final ContentResolver resolver, final Context context) { final int COMPRESSED_CRYPTED_COMPRESSED = 0; final int CRYPTED_COMPRESSED = 1; final int COMPRESSED_CRYPTED = 2; final int COMPRESSED_ONLY = 3; final int CRYPTED_ONLY = 4; final int NONE = 5; final int MODE_MIN = COMPRESSED_CRYPTED_COMPRESSED; final int MODE_MAX = NONE; final Uri.Builder wordListUriBuilder = getProviderUriBuilder(id); final String finalFileName = BinaryDictionaryGetter.getCacheFileName(id, locale, context); final String tempFileName = finalFileName + ".tmp"; for (int mode = MODE_MIN; mode <= MODE_MAX; ++mode) { InputStream originalSourceStream = null; InputStream inputStream = null; File outputFile = null; FileOutputStream outputStream = null; AssetFileDescriptor afd = null; final Uri wordListUri = wordListUriBuilder.build(); try { // Open input. afd = openAssetFileDescriptor(resolver, wordListUri); // If we can't open it at all, don't even try a number of times. if (null == afd) return null; originalSourceStream = afd.createInputStream(); // Open output. outputFile = new File(tempFileName); // Just to be sure, delete the file. This may fail silently, and return false: this // is the right thing to do, as we just want to continue anyway. outputFile.delete(); outputStream = new FileOutputStream(outputFile); // Get the appropriate decryption method for this try switch (mode) { case COMPRESSED_CRYPTED_COMPRESSED: inputStream = FileTransforms.getUncompressedStream( FileTransforms.getDecryptedStream( FileTransforms.getUncompressedStream( originalSourceStream))); break; case CRYPTED_COMPRESSED: inputStream = FileTransforms.getUncompressedStream( FileTransforms.getDecryptedStream(originalSourceStream)); break; case COMPRESSED_CRYPTED: inputStream = FileTransforms.getDecryptedStream( FileTransforms.getUncompressedStream(originalSourceStream)); break; case COMPRESSED_ONLY: inputStream = FileTransforms.getUncompressedStream(originalSourceStream); break; case CRYPTED_ONLY: inputStream = FileTransforms.getDecryptedStream(originalSourceStream); break; case NONE: inputStream = originalSourceStream; break; } checkMagicAndCopyFileTo(new BufferedInputStream(inputStream), outputStream); outputStream.flush(); outputStream.close(); final File finalFile = new File(finalFileName); if (!outputFile.renameTo(finalFile)) { throw new IOException("Can't move the file to its final name"); } wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT, QUERY_PARAMETER_SUCCESS); if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) { Log.e(TAG, "Could not have the dictionary pack delete a word list"); } BinaryDictionaryGetter.removeFilesWithIdExcept(context, id, finalFile); // Success! Close files (through the finally{} clause) and return. return AssetFileAddress.makeFromFileName(finalFileName); } catch (Exception e) { if (DEBUG) { Log.i(TAG, "Can't open word list in mode " + mode + " : " + e); } if (null != outputFile) { // This may or may not fail. The file may not have been created if the // exception was thrown before it could be. Hence, both failure and // success are expected outcomes, so we don't check the return value. outputFile.delete(); } // Try the next method. } finally { // Ignore exceptions while closing files. try { // inputStream.close() will close afd, we should not call afd.close(). if (null != inputStream) inputStream.close(); } catch (Exception e) { Log.e(TAG, "Exception while closing a cross-process file descriptor : " + e); } try { if (null != outputStream) outputStream.close(); } catch (Exception e) { Log.e(TAG, "Exception while closing a file : " + e); } } } // We could not copy the file at all. This is very unexpected. // I'd rather not print the word list ID to the log out of security concerns Log.e(TAG, "Could not copy a word list. Will not be able to use it."); // If we can't copy it we should warn the dictionary provider so that it can mark it // as invalid. wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT, QUERY_PARAMETER_FAILURE); if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) { Log.e(TAG, "In addition, we were unable to delete it."); } return null; }
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java b/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java index 2263205e9..a6bc2e109 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java @@ -1,1043 +1,1044 @@ // ======================================================================== // Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // You may elect to redistribute this code under either of these licenses. // ======================================================================== package org.eclipse.jetty.server; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import javax.servlet.ServletRequest; import org.eclipse.jetty.http.HttpBuffers; import org.eclipse.jetty.http.HttpFields; import org.eclipse.jetty.http.HttpHeaders; import org.eclipse.jetty.http.HttpSchemes; import org.eclipse.jetty.io.Buffer; import org.eclipse.jetty.io.ByteArrayBuffer; import org.eclipse.jetty.io.EndPoint; import org.eclipse.jetty.io.EofException; import org.eclipse.jetty.util.component.LifeCycle; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.thread.ThreadPool; /** Abstract Connector implementation. * This abstract implementation of the Connector interface provides:<ul> * <li>AbstractLifeCycle implementation</li> * <li>Implementations for connector getters and setters</li> * <li>Buffer management</li> * <li>Socket configuration</li> * <li>Base acceptor thread</li> * <li>Optional reverse proxy headers checking</li> * </ul> * * */ public abstract class AbstractConnector extends HttpBuffers implements Connector { private String _name; private Server _server; private ThreadPool _threadPool; private String _host; private int _port=0; private String _integralScheme=HttpSchemes.HTTPS; private int _integralPort=0; private String _confidentialScheme=HttpSchemes.HTTPS; private int _confidentialPort=0; private int _acceptQueueSize=0; private int _acceptors=1; private int _acceptorPriorityOffset=0; private boolean _useDNS; private boolean _forwarded; private String _hostHeader; private String _forwardedHostHeader = "X-Forwarded-Host"; // default to mod_proxy_http header private String _forwardedServerHeader = "X-Forwarded-Server"; // default to mod_proxy_http header private String _forwardedForHeader = "X-Forwarded-For"; // default to mod_proxy_http header private boolean _reuseAddress=true; protected int _maxIdleTime=200000; protected int _lowResourceMaxIdleTime=-1; protected int _soLingerTime=-1; private transient Thread[] _acceptorThread; final Object _statsLock = new Object(); transient long _statsStartedAt=-1; // TODO use concurrents for these! transient int _requests; transient int _connections; // total number of connections made to server transient int _connectionsOpen; // number of connections currently open transient int _connectionsOpenMin; // min number of connections open simultaneously transient int _connectionsOpenMax; // max number of connections open simultaneously transient long _connectionsDurationMin; // min duration of a connection transient long _connectionsDurationMax; // max duration of a connection transient long _connectionsDurationTotal; // total duration of all coneection transient int _connectionsRequestsMin; // min requests per connection transient int _connectionsRequestsMax; // max requests per connection /* ------------------------------------------------------------------------------- */ /** */ public AbstractConnector() { } /* ------------------------------------------------------------------------------- */ public final Buffer newBuffer(int size) { // TODO remove once no overrides established return null; } /* ------------------------------------------------------------------------------- */ public Buffer newRequestBuffer(int size) { return new ByteArrayBuffer(size); } /* ------------------------------------------------------------------------------- */ public Buffer newRequestHeader(int size) { return new ByteArrayBuffer(size); } /* ------------------------------------------------------------------------------- */ public Buffer newResponseBuffer(int size) { return new ByteArrayBuffer(size); } /* ------------------------------------------------------------------------------- */ public Buffer newResponseHeader(int size) { return new ByteArrayBuffer(size); } /* ------------------------------------------------------------------------------- */ protected boolean isRequestHeader(Buffer buffer) { return true; } /* ------------------------------------------------------------------------------- */ protected boolean isResponseHeader(Buffer buffer) { return true; } /* ------------------------------------------------------------------------------- */ /* */ public Server getServer() { return _server; } /* ------------------------------------------------------------------------------- */ public void setServer(Server server) { _server=server; } /* ------------------------------------------------------------------------------- */ /* * @see org.eclipse.jetty.http.HttpListener#getHttpServer() */ public ThreadPool getThreadPool() { return _threadPool; } /* ------------------------------------------------------------------------------- */ public void setThreadPool(ThreadPool pool) { _threadPool=pool; } /* ------------------------------------------------------------------------------- */ /** */ public void setHost(String host) { _host=host; } /* ------------------------------------------------------------------------------- */ /* */ public String getHost() { return _host; } /* ------------------------------------------------------------------------------- */ /* * @see org.eclipse.jetty.server.server.HttpListener#setPort(int) */ public void setPort(int port) { _port=port; } /* ------------------------------------------------------------------------------- */ /* * @see org.eclipse.jetty.server.server.HttpListener#getPort() */ public int getPort() { return _port; } /* ------------------------------------------------------------ */ /** * @return Returns the maxIdleTime. */ public int getMaxIdleTime() { return _maxIdleTime; } /* ------------------------------------------------------------ */ /** * Set the maximum Idle time for a connection, which roughly translates * to the {@link Socket#setSoTimeout(int)} call, although with NIO * implementations other mechanisms may be used to implement the timeout. * The max idle time is applied:<ul> * <li>When waiting for a new request to be received on a connection</li> * <li>When reading the headers and content of a request</li> * <li>When writing the headers and content of a response</li> * </ul> * Jetty interprets this value as the maximum time between some progress being * made on the connection. So if a single byte is read or written, then the * timeout (if implemented by jetty) is reset. However, in many instances, * the reading/writing is delegated to the JVM, and the semantic is more * strictly enforced as the maximum time a single read/write operation can * take. Note, that as Jetty supports writes of memory mapped file buffers, * then a write may take many 10s of seconds for large content written to a * slow device. * <p> * Previously, Jetty supported separate idle timeouts and IO operation timeouts, * however the expense of changing the value of soTimeout was significant, so * these timeouts were merged. With the advent of NIO, it may be possible to * again differentiate these values (if there is demand). * * @param maxIdleTime The maxIdleTime to set. */ public void setMaxIdleTime(int maxIdleTime) { _maxIdleTime = maxIdleTime; } /* ------------------------------------------------------------ */ /** * @return Returns the maxIdleTime. */ public int getLowResourceMaxIdleTime() { return _lowResourceMaxIdleTime; } /* ------------------------------------------------------------ */ /** * @param maxIdleTime The maxIdleTime to set. */ public void setLowResourceMaxIdleTime(int maxIdleTime) { _lowResourceMaxIdleTime = maxIdleTime; } /* ------------------------------------------------------------ */ /** * @return Returns the soLingerTime. */ public int getSoLingerTime() { return _soLingerTime; } /* ------------------------------------------------------------ */ /** * @return Returns the acceptQueueSize. */ public int getAcceptQueueSize() { return _acceptQueueSize; } /* ------------------------------------------------------------ */ /** * @param acceptQueueSize The acceptQueueSize to set. */ public void setAcceptQueueSize(int acceptQueueSize) { _acceptQueueSize = acceptQueueSize; } /* ------------------------------------------------------------ */ /** * @return Returns the number of acceptor threads. */ public int getAcceptors() { return _acceptors; } /* ------------------------------------------------------------ */ /** * @param acceptors The number of acceptor threads to set. */ public void setAcceptors(int acceptors) { _acceptors = acceptors; } /* ------------------------------------------------------------ */ /** * @param soLingerTime The soLingerTime to set or -1 to disable. */ public void setSoLingerTime(int soLingerTime) { _soLingerTime = soLingerTime; } /* ------------------------------------------------------------ */ protected void doStart() throws Exception { if (_server==null) throw new IllegalStateException("No server"); // open listener port open(); super.doStart(); if (_threadPool==null) _threadPool=_server.getThreadPool(); if (_threadPool!=_server.getThreadPool() && (_threadPool instanceof LifeCycle)) ((LifeCycle)_threadPool).start(); // Start selector thread synchronized(this) { _acceptorThread=new Thread[getAcceptors()]; for (int i=0;i<_acceptorThread.length;i++) { if (!_threadPool.dispatch(new Acceptor(i))) { Log.warn("insufficient maxThreads configured for {}",this); break; } } } Log.info("Started {}",this); } /* ------------------------------------------------------------ */ protected void doStop() throws Exception { try{close();} catch(IOException e) {Log.warn(e);} if (_threadPool==_server.getThreadPool()) _threadPool=null; else if (_threadPool instanceof LifeCycle) ((LifeCycle)_threadPool).stop(); super.doStop(); Thread[] acceptors=null; synchronized(this) { acceptors=_acceptorThread; _acceptorThread=null; } if (acceptors != null) { for (int i=0;i<acceptors.length;i++) { Thread thread=acceptors[i]; if (thread!=null) thread.interrupt(); } } } /* ------------------------------------------------------------ */ public void join() throws InterruptedException { Thread[] threads=_acceptorThread; if (threads!=null) for (int i=0;i<threads.length;i++) if (threads[i]!=null) threads[i].join(); } /* ------------------------------------------------------------ */ protected void configure(Socket socket) throws IOException { try { socket.setTcpNoDelay(true); if (_maxIdleTime >= 0) socket.setSoTimeout(_maxIdleTime); if (_soLingerTime >= 0) socket.setSoLinger(true, _soLingerTime/1000); else socket.setSoLinger(false, 0); } catch (Exception e) { Log.ignore(e); } } /* ------------------------------------------------------------ */ public void customize(EndPoint endpoint, Request request) throws IOException { if (isForwarded()) checkForwardedHeaders(endpoint, request); } /* ------------------------------------------------------------ */ protected void checkForwardedHeaders(EndPoint endpoint, Request request) throws IOException { HttpFields httpFields = request.getConnection().getRequestFields(); // Retrieving headers from the request String forwardedHost = getLeftMostValue(httpFields.getStringField(getForwardedHostHeader())); String forwardedServer = getLeftMostValue(httpFields.getStringField(getForwardedServerHeader())); String forwardedFor = getLeftMostValue(httpFields.getStringField(getForwardedForHeader())); if (_hostHeader!=null) { // Update host header httpFields.put(HttpHeaders.HOST_BUFFER, _hostHeader); request.setServerName(null); request.setServerPort(-1); request.getServerName(); } else if (forwardedHost != null) { // Update host header httpFields.put(HttpHeaders.HOST_BUFFER, forwardedHost); request.setServerName(null); request.setServerPort(-1); request.getServerName(); } else if (forwardedServer != null) { // Use provided server name request.setServerName(forwardedServer); } if (forwardedFor != null) { request.setRemoteAddr(forwardedFor); InetAddress inetAddress = null; if (_useDNS) { try { inetAddress = InetAddress.getByName(forwardedFor); } catch (UnknownHostException e) { Log.ignore(e); } } request.setRemoteHost(inetAddress==null?forwardedFor:inetAddress.getHostName()); } } /* ------------------------------------------------------------ */ protected String getLeftMostValue(String headerValue) { if (headerValue == null) return null; int commaIndex = headerValue.indexOf(','); if (commaIndex == -1) { // Single value return headerValue; } // The left-most value is the farthest downstream client return headerValue.substring(0, commaIndex); } /* ------------------------------------------------------------ */ public void persist(EndPoint endpoint) throws IOException { } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ /* * @see org.eclipse.jetty.server.Connector#getConfidentialPort() */ public int getConfidentialPort() { return _confidentialPort; } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ /* * @see org.eclipse.jetty.server.Connector#getConfidentialScheme() */ public String getConfidentialScheme() { return _confidentialScheme; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.jetty.server.Connector#isConfidential(org.eclipse.jetty.server.Request) */ public boolean isIntegral(Request request) { return false; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.jetty.server.Connector#getConfidentialPort() */ public int getIntegralPort() { return _integralPort; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.jetty.server.Connector#getIntegralScheme() */ public String getIntegralScheme() { return _integralScheme; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.jetty.server.Connector#isConfidential(org.eclipse.jetty.server.Request) */ public boolean isConfidential(Request request) { return false; } /* ------------------------------------------------------------ */ /** * @param confidentialPort The confidentialPort to set. */ public void setConfidentialPort(int confidentialPort) { _confidentialPort = confidentialPort; } /* ------------------------------------------------------------ */ /** * @param confidentialScheme The confidentialScheme to set. */ public void setConfidentialScheme(String confidentialScheme) { _confidentialScheme = confidentialScheme; } /* ------------------------------------------------------------ */ /** * @param integralPort The integralPort to set. */ public void setIntegralPort(int integralPort) { _integralPort = integralPort; } /* ------------------------------------------------------------ */ /** * @param integralScheme The integralScheme to set. */ public void setIntegralScheme(String integralScheme) { _integralScheme = integralScheme; } /* ------------------------------------------------------------ */ protected abstract void accept(int acceptorID) throws IOException, InterruptedException; /* ------------------------------------------------------------ */ public void stopAccept(int acceptorID) throws Exception { } /* ------------------------------------------------------------ */ public boolean getResolveNames() { return _useDNS; } /* ------------------------------------------------------------ */ public void setResolveNames(boolean resolve) { _useDNS=resolve; } /* ------------------------------------------------------------ */ /** * Is reverse proxy handling on? * @return true if this connector is checking the x-forwarded-for/host/server headers */ public boolean isForwarded() { return _forwarded; } /* ------------------------------------------------------------ */ /** * Set reverse proxy handling * @param check true if this connector is checking the x-forwarded-for/host/server headers */ public void setForwarded(boolean check) { if (check) Log.debug(this+" is forwarded"); _forwarded=check; } /* ------------------------------------------------------------ */ public String getHostHeader() { return _hostHeader; } /* ------------------------------------------------------------ */ /** * Set a forced valued for the host header to control what is returned * by {@link ServletRequest#getServerName()} and {@link ServletRequest#getServerPort()}. * This value is only used if {@link #isForwarded()} is true. * @param hostHeader The value of the host header to force. */ public void setHostHeader(String hostHeader) { _hostHeader=hostHeader; } /* ------------------------------------------------------------ */ public String getForwardedHostHeader() { return _forwardedHostHeader; } /* ------------------------------------------------------------ */ /** * @param forwardedHostHeader The header name for forwarded hosts (default x-forwarded-host) */ public void setForwardedHostHeader(String forwardedHostHeader) { _forwardedHostHeader=forwardedHostHeader; } /* ------------------------------------------------------------ */ public String getForwardedServerHeader() { return _forwardedServerHeader; } /* ------------------------------------------------------------ */ /** * @param forwardedHostHeader The header name for forwarded server (default x-forwarded-server) */ public void setForwardedServerHeader(String forwardedServerHeader) { _forwardedServerHeader=forwardedServerHeader; } /* ------------------------------------------------------------ */ public String getForwardedForHeader() { return _forwardedForHeader; } /* ------------------------------------------------------------ */ /** * @param forwardedHostHeader The header name for forwarded for (default x-forwarded-for) */ public void setForwardedForHeader(String forwardedRemoteAddressHeade) { _forwardedForHeader=forwardedRemoteAddressHeade; } /* ------------------------------------------------------------ */ public String toString() { String name = this.getClass().getName(); int dot = name.lastIndexOf('.'); if (dot>0) name=name.substring(dot+1); return name+"@"+(getHost()==null?"0.0.0.0":getHost())+":"+(getLocalPort()<=0?getPort():getLocalPort()); } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ private class Acceptor implements Runnable { int _acceptor=0; Acceptor(int id) { _acceptor=id; } /* ------------------------------------------------------------ */ public void run() { Thread current = Thread.currentThread(); + String name; synchronized(AbstractConnector.this) { if (_acceptorThread==null) return; _acceptorThread[_acceptor]=current; - String name =_acceptorThread[_acceptor].getName(); + name =_acceptorThread[_acceptor].getName(); current.setName(name+" - Acceptor"+_acceptor+" "+AbstractConnector.this); } int old_priority=current.getPriority(); try { current.setPriority(old_priority-_acceptorPriorityOffset); while (isRunning() && getConnection()!=null) { try { accept(_acceptor); } catch(EofException e) { Log.ignore(e); } catch(IOException e) { Log.ignore(e); } catch(ThreadDeath e) { Log.warn(e); throw e; } catch(Throwable e) { Log.warn(e); } } } finally { current.setPriority(old_priority); current.setName(name); try { if (_acceptor==0) close(); } catch (IOException e) { Log.warn(e); } synchronized(AbstractConnector.this) { if (_acceptorThread!=null) _acceptorThread[_acceptor]=null; } } } } /* ------------------------------------------------------------ */ public String getName() { if (_name==null) _name= (getHost()==null?"0.0.0.0":getHost())+":"+(getLocalPort()<=0?getPort():getLocalPort()); return _name; } /* ------------------------------------------------------------ */ public void setName(String name) { _name = name; } /* ------------------------------------------------------------ */ /** * @return Get the number of requests handled by this context * since last call of statsReset(). If setStatsOn(false) then this * is undefined. */ public int getRequests() {return _requests;} /* ------------------------------------------------------------ */ /** * @return Returns the connectionsDurationMin. */ public long getConnectionsDurationMin() { return _connectionsDurationMin; } /* ------------------------------------------------------------ */ /** * @return Returns the connectionsDurationTotal. */ public long getConnectionsDurationTotal() { return _connectionsDurationTotal; } /* ------------------------------------------------------------ */ /** * @return Returns the connectionsOpenMin. */ public int getConnectionsOpenMin() { return _connectionsOpenMin; } /* ------------------------------------------------------------ */ /** * @return Returns the connectionsRequestsMin. */ public int getConnectionsRequestsMin() { return _connectionsRequestsMin; } /* ------------------------------------------------------------ */ /** * @return Number of connections accepted by the server since * statsReset() called. Undefined if setStatsOn(false). */ public int getConnections() {return _connections;} /* ------------------------------------------------------------ */ /** * @return Number of connections currently open that were opened * since statsReset() called. Undefined if setStatsOn(false). */ public int getConnectionsOpen() {return _connectionsOpen;} /* ------------------------------------------------------------ */ /** * @return Maximum number of connections opened simultaneously * since statsReset() called. Undefined if setStatsOn(false). */ public int getConnectionsOpenMax() {return _connectionsOpenMax;} /* ------------------------------------------------------------ */ /** * @return Average duration in milliseconds of open connections * since statsReset() called. Undefined if setStatsOn(false). */ public long getConnectionsDurationAve() {return _connections==0?0:(_connectionsDurationTotal/_connections);} /* ------------------------------------------------------------ */ /** * @return Maximum duration in milliseconds of an open connection * since statsReset() called. Undefined if setStatsOn(false). */ public long getConnectionsDurationMax() {return _connectionsDurationMax;} /* ------------------------------------------------------------ */ /** * @return Average number of requests per connection * since statsReset() called. Undefined if setStatsOn(false). */ public int getConnectionsRequestsAve() {return _connections==0?0:(_requests/_connections);} /* ------------------------------------------------------------ */ /** * @return Maximum number of requests per connection * since statsReset() called. Undefined if setStatsOn(false). */ public int getConnectionsRequestsMax() {return _connectionsRequestsMax;} /* ------------------------------------------------------------ */ /** Reset statistics. */ public void statsReset() { _statsStartedAt=_statsStartedAt==-1?-1:System.currentTimeMillis(); _connections=0; _connectionsOpenMin=_connectionsOpen; _connectionsOpenMax=_connectionsOpen; _connectionsOpen=0; _connectionsDurationMin=0; _connectionsDurationMax=0; _connectionsDurationTotal=0; _requests=0; _connectionsRequestsMin=0; _connectionsRequestsMax=0; } /* ------------------------------------------------------------ */ public void setStatsOn(boolean on) { if (on && _statsStartedAt!=-1) return; Log.debug("Statistics on = "+on+" for "+this); statsReset(); _statsStartedAt=on?System.currentTimeMillis():-1; } /* ------------------------------------------------------------ */ /** * @return True if statistics collection is turned on. */ public boolean getStatsOn() { return _statsStartedAt!=-1; } /* ------------------------------------------------------------ */ /** * @return Timestamp stats were started at. */ public long getStatsOnMs() { return (_statsStartedAt!=-1)?(System.currentTimeMillis()-_statsStartedAt):0; } /* ------------------------------------------------------------ */ protected void connectionOpened(HttpConnection connection) { if (_statsStartedAt==-1) return; synchronized(_statsLock) { _connectionsOpen++; if (_connectionsOpen > _connectionsOpenMax) _connectionsOpenMax=_connectionsOpen; } } /* ------------------------------------------------------------ */ protected void connectionClosed(HttpConnection connection) { if (_statsStartedAt>=0) { long duration=System.currentTimeMillis()-connection.getTimeStamp(); int requests=connection.getRequests(); synchronized(_statsLock) { _requests+=requests; _connections++; _connectionsOpen--; _connectionsDurationTotal+=duration; if (_connectionsOpen<0) _connectionsOpen=0; if (_connectionsOpen<_connectionsOpenMin) _connectionsOpenMin=_connectionsOpen; if (_connectionsDurationMin==0 || duration<_connectionsDurationMin) _connectionsDurationMin=duration; if (duration>_connectionsDurationMax) _connectionsDurationMax=duration; if (_connectionsRequestsMin==0 || requests<_connectionsRequestsMin) _connectionsRequestsMin=requests; if (requests>_connectionsRequestsMax) _connectionsRequestsMax=requests; } } } /* ------------------------------------------------------------ */ /** * @return the acceptorPriority */ public int getAcceptorPriorityOffset() { return _acceptorPriorityOffset; } /* ------------------------------------------------------------ */ /** * Set the priority offset of the acceptor threads. The priority is adjusted by * this amount (default 0) to either favour the acceptance of new threads and newly active * connections or to favour the handling of already dispatched connections. * @param offset the amount to alter the priority of the acceptor threads. */ public void setAcceptorPriorityOffset(int offset) { _acceptorPriorityOffset=offset; } /* ------------------------------------------------------------ */ /** * @return True if the the server socket will be opened in SO_REUSEADDR mode. */ public boolean getReuseAddress() { return _reuseAddress; } /* ------------------------------------------------------------ */ /** * @param reuseAddress True if the the server socket will be opened in SO_REUSEADDR mode. */ public void setReuseAddress(boolean reuseAddress) { _reuseAddress=reuseAddress; } /* ------------------------------------------------------------ */ public boolean isLowResources() { if (_threadPool!=null) return _threadPool.isLowOnThreads(); return _server.getThreadPool().isLowOnThreads(); } }
false
true
public void run() { Thread current = Thread.currentThread(); synchronized(AbstractConnector.this) { if (_acceptorThread==null) return; _acceptorThread[_acceptor]=current; String name =_acceptorThread[_acceptor].getName(); current.setName(name+" - Acceptor"+_acceptor+" "+AbstractConnector.this); } int old_priority=current.getPriority(); try { current.setPriority(old_priority-_acceptorPriorityOffset); while (isRunning() && getConnection()!=null) { try { accept(_acceptor); } catch(EofException e) { Log.ignore(e); } catch(IOException e) { Log.ignore(e); } catch(ThreadDeath e) { Log.warn(e); throw e; } catch(Throwable e) { Log.warn(e); } } } finally { current.setPriority(old_priority); current.setName(name); try { if (_acceptor==0) close(); } catch (IOException e) { Log.warn(e); } synchronized(AbstractConnector.this) { if (_acceptorThread!=null) _acceptorThread[_acceptor]=null; } } }
public void run() { Thread current = Thread.currentThread(); String name; synchronized(AbstractConnector.this) { if (_acceptorThread==null) return; _acceptorThread[_acceptor]=current; name =_acceptorThread[_acceptor].getName(); current.setName(name+" - Acceptor"+_acceptor+" "+AbstractConnector.this); } int old_priority=current.getPriority(); try { current.setPriority(old_priority-_acceptorPriorityOffset); while (isRunning() && getConnection()!=null) { try { accept(_acceptor); } catch(EofException e) { Log.ignore(e); } catch(IOException e) { Log.ignore(e); } catch(ThreadDeath e) { Log.warn(e); throw e; } catch(Throwable e) { Log.warn(e); } } } finally { current.setPriority(old_priority); current.setName(name); try { if (_acceptor==0) close(); } catch (IOException e) { Log.warn(e); } synchronized(AbstractConnector.this) { if (_acceptorThread!=null) _acceptorThread[_acceptor]=null; } } }
diff --git a/src/com/android/launcher2/DragLayer.java b/src/com/android/launcher2/DragLayer.java index 2e72f622..eb539450 100644 --- a/src/com/android/launcher2/DragLayer.java +++ b/src/com/android/launcher2/DragLayer.java @@ -1,104 +1,106 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.launcher2; import com.android.launcher.R; import android.content.Context; import android.graphics.Bitmap; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; /** * A ViewGroup that coordinates dragging across its descendants */ public class DragLayer extends FrameLayout { private DragController mDragController; private int[] mTmpXY = new int[2]; /** * Used to create a new DragLayer from XML. * * @param context The application's context. * @param attrs The attributes set containing the Workspace's customization values. */ public DragLayer(Context context, AttributeSet attrs) { super(context, attrs); // Disable multitouch across the workspace/all apps/customize tray setMotionEventSplittingEnabled(false); } public void setDragController(DragController controller) { mDragController = controller; } @Override public boolean dispatchKeyEvent(KeyEvent event) { return mDragController.dispatchKeyEvent(event) || super.dispatchKeyEvent(event); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { // If the current CellLayoutChildren has a resize frame, we need to detect if any touch // event has occurred which doesn't result in resizing a widget. In this case, we // dismiss any visible resize frames. final Workspace w = (Workspace) findViewById(R.id.workspace); - final CellLayout currentPage = (CellLayout) w.getChildAt(w.getCurrentPage()); - final CellLayoutChildren childrenLayout = currentPage.getChildrenLayout(); + if (w != null) { + final CellLayout currentPage = (CellLayout) w.getChildAt(w.getCurrentPage()); + final CellLayoutChildren childrenLayout = currentPage.getChildrenLayout(); - if (childrenLayout.hasResizeFrames() && !childrenLayout.isWidgetBeingResized()) { - post(new Runnable() { - public void run() { - if (!childrenLayout.isWidgetBeingResized()) { - childrenLayout.clearAllResizeFrames(); + if (childrenLayout.hasResizeFrames() && !childrenLayout.isWidgetBeingResized()) { + post(new Runnable() { + public void run() { + if (!childrenLayout.isWidgetBeingResized()) { + childrenLayout.clearAllResizeFrames(); + } } - } - }); + }); + } } return mDragController.onInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent ev) { return mDragController.onTouchEvent(ev); } @Override public boolean dispatchUnhandledMove(View focused, int direction) { return mDragController.dispatchUnhandledMove(focused, direction); } public View createDragView(Bitmap b, int xPos, int yPos) { ImageView imageView = new ImageView(mContext); imageView.setImageBitmap(b); imageView.setX(xPos); imageView.setY(yPos); addView(imageView, b.getWidth(), b.getHeight()); return imageView; } public View createDragView(View v) { v.getLocationOnScreen(mTmpXY); return createDragView(mDragController.getViewBitmap(v), mTmpXY[0], mTmpXY[1]); } }
false
true
public boolean onInterceptTouchEvent(MotionEvent ev) { // If the current CellLayoutChildren has a resize frame, we need to detect if any touch // event has occurred which doesn't result in resizing a widget. In this case, we // dismiss any visible resize frames. final Workspace w = (Workspace) findViewById(R.id.workspace); final CellLayout currentPage = (CellLayout) w.getChildAt(w.getCurrentPage()); final CellLayoutChildren childrenLayout = currentPage.getChildrenLayout(); if (childrenLayout.hasResizeFrames() && !childrenLayout.isWidgetBeingResized()) { post(new Runnable() { public void run() { if (!childrenLayout.isWidgetBeingResized()) { childrenLayout.clearAllResizeFrames(); } } }); } return mDragController.onInterceptTouchEvent(ev); }
public boolean onInterceptTouchEvent(MotionEvent ev) { // If the current CellLayoutChildren has a resize frame, we need to detect if any touch // event has occurred which doesn't result in resizing a widget. In this case, we // dismiss any visible resize frames. final Workspace w = (Workspace) findViewById(R.id.workspace); if (w != null) { final CellLayout currentPage = (CellLayout) w.getChildAt(w.getCurrentPage()); final CellLayoutChildren childrenLayout = currentPage.getChildrenLayout(); if (childrenLayout.hasResizeFrames() && !childrenLayout.isWidgetBeingResized()) { post(new Runnable() { public void run() { if (!childrenLayout.isWidgetBeingResized()) { childrenLayout.clearAllResizeFrames(); } } }); } } return mDragController.onInterceptTouchEvent(ev); }
diff --git a/src/edu/umich/sbolt/language/EntityFactory.java b/src/edu/umich/sbolt/language/EntityFactory.java index eff327a..3aaef7d 100644 --- a/src/edu/umich/sbolt/language/EntityFactory.java +++ b/src/edu/umich/sbolt/language/EntityFactory.java @@ -1,36 +1,34 @@ package edu.umich.sbolt.language; import edu.umich.sbolt.language.Patterns.*; public class EntityFactory { public static LinguisticEntity createEntity(String entityType){ if(entityType.equals(GoalInfo.TYPE)){ return new GoalInfo(); } else if(entityType.equals(LingObject.TYPE)){ return new LingObject(); } else if(entityType.equals(ObjectRelation.TYPE)){ return new ObjectRelation(); - } else if(entityType.equals(SvsLabel.TYPE)){ - return new SvsLabel(); } else if(entityType.equals(ProposalInfo.TYPE)){ return new ProposalInfo(); } else if(entityType.equals(Sentence.TYPE)){ return new Sentence(); } else if(entityType.equals(VerbCommand.TYPE)){ return new VerbCommand(); } else if(entityType.equals(ObjectIdentification.TYPE)){ return new ObjectIdentification(); } else if(entityType.equals(BareAttributeResponse.TYPE)){ return new BareAttributeResponse(); } else if(entityType.equals(BareValueResponse.TYPE)){ return new BareValueResponse(); } else if(entityType.equals(RecognitionQuestion.TYPE)){ return new RecognitionQuestion(); } else if(entityType.equals(DescriptionRequest.TYPE)){ return new DescriptionRequest(); } else { return null; } } }
true
true
public static LinguisticEntity createEntity(String entityType){ if(entityType.equals(GoalInfo.TYPE)){ return new GoalInfo(); } else if(entityType.equals(LingObject.TYPE)){ return new LingObject(); } else if(entityType.equals(ObjectRelation.TYPE)){ return new ObjectRelation(); } else if(entityType.equals(SvsLabel.TYPE)){ return new SvsLabel(); } else if(entityType.equals(ProposalInfo.TYPE)){ return new ProposalInfo(); } else if(entityType.equals(Sentence.TYPE)){ return new Sentence(); } else if(entityType.equals(VerbCommand.TYPE)){ return new VerbCommand(); } else if(entityType.equals(ObjectIdentification.TYPE)){ return new ObjectIdentification(); } else if(entityType.equals(BareAttributeResponse.TYPE)){ return new BareAttributeResponse(); } else if(entityType.equals(BareValueResponse.TYPE)){ return new BareValueResponse(); } else if(entityType.equals(RecognitionQuestion.TYPE)){ return new RecognitionQuestion(); } else if(entityType.equals(DescriptionRequest.TYPE)){ return new DescriptionRequest(); } else { return null; } }
public static LinguisticEntity createEntity(String entityType){ if(entityType.equals(GoalInfo.TYPE)){ return new GoalInfo(); } else if(entityType.equals(LingObject.TYPE)){ return new LingObject(); } else if(entityType.equals(ObjectRelation.TYPE)){ return new ObjectRelation(); } else if(entityType.equals(ProposalInfo.TYPE)){ return new ProposalInfo(); } else if(entityType.equals(Sentence.TYPE)){ return new Sentence(); } else if(entityType.equals(VerbCommand.TYPE)){ return new VerbCommand(); } else if(entityType.equals(ObjectIdentification.TYPE)){ return new ObjectIdentification(); } else if(entityType.equals(BareAttributeResponse.TYPE)){ return new BareAttributeResponse(); } else if(entityType.equals(BareValueResponse.TYPE)){ return new BareValueResponse(); } else if(entityType.equals(RecognitionQuestion.TYPE)){ return new RecognitionQuestion(); } else if(entityType.equals(DescriptionRequest.TYPE)){ return new DescriptionRequest(); } else { return null; } }
diff --git a/dev/core/src/com/google/gwt/core/ext/linker/impl/StandardLinkerContext.java b/dev/core/src/com/google/gwt/core/ext/linker/impl/StandardLinkerContext.java index 424fb28d9..2100ce0a5 100644 --- a/dev/core/src/com/google/gwt/core/ext/linker/impl/StandardLinkerContext.java +++ b/dev/core/src/com/google/gwt/core/ext/linker/impl/StandardLinkerContext.java @@ -1,532 +1,538 @@ /* * Copyright 2008 Google Inc. * * 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.gwt.core.ext.linker.impl; import com.google.gwt.core.ext.Linker; import com.google.gwt.core.ext.LinkerContext; import com.google.gwt.core.ext.TreeLogger; import com.google.gwt.core.ext.UnableToCompleteException; import com.google.gwt.core.ext.linker.ArtifactSet; import com.google.gwt.core.ext.linker.ConfigurationProperty; import com.google.gwt.core.ext.linker.EmittedArtifact; import com.google.gwt.core.ext.linker.LinkerOrder; import com.google.gwt.core.ext.linker.PublicResource; import com.google.gwt.core.ext.linker.SelectionProperty; import com.google.gwt.core.ext.linker.LinkerOrder.Order; import com.google.gwt.dev.PermutationResult; import com.google.gwt.dev.cfg.BindingProperty; import com.google.gwt.dev.cfg.ModuleDef; import com.google.gwt.dev.cfg.Property; import com.google.gwt.dev.cfg.Script; import com.google.gwt.dev.jjs.InternalCompilerException; import com.google.gwt.dev.jjs.JJSOptions; import com.google.gwt.dev.jjs.SourceInfo; import com.google.gwt.dev.js.JsObfuscateNamer; import com.google.gwt.dev.js.JsParser; import com.google.gwt.dev.js.JsParserException; import com.google.gwt.dev.js.JsPrettyNamer; import com.google.gwt.dev.js.JsSourceGenerationVisitor; import com.google.gwt.dev.js.JsStringInterner; import com.google.gwt.dev.js.JsSymbolResolver; import com.google.gwt.dev.js.JsUnusedFunctionRemover; import com.google.gwt.dev.js.JsVerboseNamer; import com.google.gwt.dev.js.ast.JsContext; import com.google.gwt.dev.js.ast.JsExpression; import com.google.gwt.dev.js.ast.JsFunction; import com.google.gwt.dev.js.ast.JsModVisitor; import com.google.gwt.dev.js.ast.JsName; import com.google.gwt.dev.js.ast.JsProgram; import com.google.gwt.dev.js.ast.JsScope; import com.google.gwt.dev.util.DefaultTextOutput; import com.google.gwt.dev.util.FileBackedObject; import com.google.gwt.dev.util.Util; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; /** * An implementation of {@link LinkerContext} that is initialized from a * {@link ModuleDef}. */ public class StandardLinkerContext extends Linker implements LinkerContext { /** * Applies the {@link JsStringInterner} optimization to each top-level * function defined within a JsProgram. */ private static class TopFunctionStringInterner extends JsModVisitor { public static boolean exec(JsProgram program) { TopFunctionStringInterner v = new TopFunctionStringInterner(program); v.accept(program); return v.didChange(); } private final JsProgram program; public TopFunctionStringInterner(JsProgram program) { this.program = program; } @Override public boolean visit(JsFunction x, JsContext<JsExpression> ctx) { didChange |= JsStringInterner.exec(program, x.getBody(), x.getScope()); return false; } } static final Comparator<ConfigurationProperty> CONFIGURATION_PROPERTY_COMPARATOR = new Comparator<ConfigurationProperty>() { public int compare(ConfigurationProperty o1, ConfigurationProperty o2) { return o1.getName().compareTo(o2.getName()); } }; static final Comparator<SelectionProperty> SELECTION_PROPERTY_COMPARATOR = new Comparator<SelectionProperty>() { public int compare(SelectionProperty o1, SelectionProperty o2) { return o1.getName().compareTo(o2.getName()); } }; /** * A faster bulk version of {@link File#mkdirs()} that takes advantage of * cached state to avoid a lot of file system access. */ private static void mkdirs(File dir, Set<String> createdDirs) { if (dir == null) { return; } String path = dir.getPath(); if (createdDirs.contains(path)) { return; } if (!dir.exists()) { mkdirs(dir.getParentFile(), createdDirs); dir.mkdir(); } createdDirs.add(path); } private final ArtifactSet artifacts = new ArtifactSet(); private final SortedSet<ConfigurationProperty> configurationProperties; private final JJSOptions jjsOptions; private final Map<Class<? extends Linker>, String> linkerShortNames = new HashMap<Class<? extends Linker>, String>(); private final String moduleFunctionName; private final long moduleLastModified; private final String moduleName; private final Map<String, StandardSelectionProperty> propertiesByName = new HashMap<String, StandardSelectionProperty>(); private final Map<String, StandardCompilationResult> resultsByStrongName = new HashMap<String, StandardCompilationResult>(); private final SortedSet<SelectionProperty> selectionProperties; private final Linker[] linkers; public StandardLinkerContext(TreeLogger logger, ModuleDef module, JJSOptions jjsOptions) throws UnableToCompleteException { logger = logger.branch(TreeLogger.DEBUG, "Constructing StandardLinkerContext", null); this.jjsOptions = jjsOptions; this.moduleFunctionName = module.getFunctionName(); this.moduleName = module.getName(); this.moduleLastModified = module.lastModified(); // Sort the linkers into the order they should actually run. List<Class<? extends Linker>> sortedLinkers = new ArrayList<Class<? extends Linker>>(); // Get all the pre-linkers first. for (Class<? extends Linker> linkerClass : module.getActiveLinkers()) { Order order = linkerClass.getAnnotation(LinkerOrder.class).value(); assert (order != null); if (order == Order.PRE) { sortedLinkers.add(linkerClass); } } // Get the primary linker. - sortedLinkers.add(module.getActivePrimaryLinker()); + Class<? extends Linker> primary = module.getActivePrimaryLinker(); + if (primary == null) { + logger.log(logger.ERROR, "Primary linker is null. Does your module " + + "inherit from com.google.gwt.core.Core or com.google.gwt.user.User?"); + } else { + sortedLinkers.add(module.getActivePrimaryLinker()); + } // Get all the post-linkers IN REVERSE ORDER. { List<Class<? extends Linker>> postLinkerClasses = new ArrayList<Class<? extends Linker>>(); for (Class<? extends Linker> linkerClass : module.getActiveLinkers()) { Order order = linkerClass.getAnnotation(LinkerOrder.class).value(); assert (order != null); if (order == Order.POST) { postLinkerClasses.add(linkerClass); } } Collections.reverse(postLinkerClasses); sortedLinkers.addAll(postLinkerClasses); } linkers = new Linker[sortedLinkers.size()]; int i = 0; for (Class<? extends Linker> linkerClass : sortedLinkers) { try { linkers[i++] = linkerClass.newInstance(); } catch (InstantiationException e) { logger.log(TreeLogger.ERROR, "Unable to create Linker", e); throw new UnableToCompleteException(); } catch (IllegalAccessException e) { logger.log(TreeLogger.ERROR, "Unable to create Linker", e); throw new UnableToCompleteException(); } } for (Map.Entry<String, Class<? extends Linker>> entry : module.getLinkers().entrySet()) { linkerShortNames.put(entry.getValue(), entry.getKey()); } /* * This will make all private PublicResources and GeneratedResources appear * in the root of the module auxiliary directory. */ linkerShortNames.put(this.getClass(), ""); // Break ModuleDef properties out into LinkerContext interfaces { SortedSet<ConfigurationProperty> mutableConfigurationProperties = new TreeSet<ConfigurationProperty>( CONFIGURATION_PROPERTY_COMPARATOR); SortedSet<SelectionProperty> mutableSelectionProperties = new TreeSet<SelectionProperty>( SELECTION_PROPERTY_COMPARATOR); for (Property p : module.getProperties()) { // Create a new view if (p instanceof com.google.gwt.dev.cfg.ConfigurationProperty) { StandardConfigurationProperty newProp = new StandardConfigurationProperty( (com.google.gwt.dev.cfg.ConfigurationProperty) p); mutableConfigurationProperties.add(newProp); logger.log(TreeLogger.SPAM, "Added configuration property " + newProp, null); } else if (p instanceof BindingProperty) { StandardSelectionProperty newProp = new StandardSelectionProperty( (BindingProperty) p); mutableSelectionProperties.add(newProp); propertiesByName.put(newProp.getName(), newProp); logger.log(TreeLogger.SPAM, "Added selection property " + newProp, null); } else { logger.log(TreeLogger.ERROR, "Unknown property type " + p.getClass().getName()); } } selectionProperties = Collections.unmodifiableSortedSet(mutableSelectionProperties); configurationProperties = Collections.unmodifiableSortedSet(mutableConfigurationProperties); } { int index = 0; for (Script script : module.getScripts()) { artifacts.add(new StandardScriptReference(script.getSrc(), index++)); logger.log(TreeLogger.SPAM, "Added script " + script.getSrc(), null); } } { int index = 0; for (String style : module.getStyles()) { artifacts.add(new StandardStylesheetReference(style, index++)); logger.log(TreeLogger.SPAM, "Added style " + style, null); } } // Generated files should be passed in via addArtifacts() for (String path : module.getAllPublicFiles()) { String partialPath = path.replace(File.separatorChar, '/'); PublicResource resource = new StandardPublicResource(partialPath, module.findPublicFile(path)); artifacts.add(resource); logger.log(TreeLogger.SPAM, "Added public resource " + resource, null); } } /** * Adds or replaces Artifacts in the ArtifactSet that will be passed into the * Linkers invoked. */ public void addOrReplaceArtifacts(ArtifactSet artifacts) { this.artifacts.removeAll(artifacts); this.artifacts.addAll(artifacts); } /** * Returns the ArtifactSet that will passed into the invoke Linkers. */ public ArtifactSet getArtifacts() { return artifacts; } /** * Gets or creates a CompilationResult for the given JavaScript program. */ public StandardCompilationResult getCompilation(TreeLogger logger, FileBackedObject<PermutationResult> resultFile) throws UnableToCompleteException { PermutationResult permutationResult = resultFile.newInstance(logger); byte[][] js = permutationResult.getJs(); String strongName = Util.computeStrongName(js); StandardCompilationResult result = resultsByStrongName.get(strongName); if (result == null) { result = new StandardCompilationResult(strongName, js, permutationResult.getSerializedSymbolMap()); resultsByStrongName.put(result.getStrongName(), result); artifacts.add(result); // Add any other Permutations ArtifactSet otherArtifacts = permutationResult.getArtifacts(); if (otherArtifacts != null) { artifacts.addAll(otherArtifacts); } } return result; } public SortedSet<ConfigurationProperty> getConfigurationProperties() { return configurationProperties; } @Override public String getDescription() { return "Root Linker"; } public String getModuleFunctionName() { return moduleFunctionName; } public long getModuleLastModified() { return moduleLastModified; } public String getModuleName() { return moduleName; } public SortedSet<SelectionProperty> getProperties() { return selectionProperties; } public StandardSelectionProperty getProperty(String name) { return propertiesByName.get(name); } /** * Run the linker stack. */ public ArtifactSet invokeLink(TreeLogger logger) throws UnableToCompleteException { ArtifactSet workingArtifacts = new ArtifactSet(artifacts); for (Linker linker : linkers) { TreeLogger linkerLogger = logger.branch(TreeLogger.TRACE, "Invoking Linker " + linker.getDescription(), null); workingArtifacts.freeze(); try { workingArtifacts = linker.link(linkerLogger, this, workingArtifacts); } catch (Throwable e) { linkerLogger.log(TreeLogger.ERROR, "Failed to link", e); throw new UnableToCompleteException(); } } return workingArtifacts; } public ArtifactSet invokeRelink(TreeLogger logger, ArtifactSet newlyGeneratedArtifacts) throws UnableToCompleteException { ArtifactSet workingArtifacts = new ArtifactSet(newlyGeneratedArtifacts); for (Linker linker : linkers) { TreeLogger linkerLogger = logger.branch(TreeLogger.TRACE, "Invoking relink on Linker " + linker.getDescription(), null); workingArtifacts.freeze(); try { workingArtifacts = linker.relink(linkerLogger, this, workingArtifacts); } catch (Throwable e) { linkerLogger.log(TreeLogger.ERROR, "Failed to relink", e); throw new UnableToCompleteException(); } } return workingArtifacts; } public boolean isOutputCompact() { return jjsOptions.getOutput().shouldMinimize(); } @Override public ArtifactSet link(TreeLogger logger, LinkerContext context, ArtifactSet artifacts) throws UnableToCompleteException { throw new UnsupportedOperationException(); } public String optimizeJavaScript(TreeLogger logger, String program) throws UnableToCompleteException { logger = logger.branch(TreeLogger.DEBUG, "Attempting to optimize JS", null); Reader r = new StringReader(program); JsProgram jsProgram = new JsProgram(); JsScope topScope = jsProgram.getScope(); JsName funcName = topScope.declareName(getModuleFunctionName()); funcName.setObfuscatable(false); try { SourceInfo sourceInfo = jsProgram.createSourceInfoSynthetic( StandardLinkerContext.class, "Linker-derived JS"); JsParser.parseInto(sourceInfo, topScope, jsProgram.getGlobalBlock(), r); } catch (IOException e) { logger.log(TreeLogger.ERROR, "Unable to parse JavaScript", e); throw new UnableToCompleteException(); } catch (JsParserException e) { logger.log(TreeLogger.ERROR, "Unable to parse JavaScript", e); throw new UnableToCompleteException(); } JsSymbolResolver.exec(jsProgram); JsUnusedFunctionRemover.exec(jsProgram); switch (jjsOptions.getOutput()) { case OBFUSCATED: /* * We can't apply the regular JsStringInterner to the JsProgram that * we've just created. In the normal case, the JsStringInterner adds an * additional statement to the program's global JsBlock, however we * don't know exactly what the form and structure of our JsProgram are, * so we'll limit the scope of the modifications to each top-level * function within the program. */ TopFunctionStringInterner.exec(jsProgram); JsObfuscateNamer.exec(jsProgram); break; case PRETTY: // We don't intern strings in pretty mode to improve readability JsPrettyNamer.exec(jsProgram); break; case DETAILED: // As above with OBFUSCATED TopFunctionStringInterner.exec(jsProgram); JsVerboseNamer.exec(jsProgram); break; default: throw new InternalCompilerException("Unknown output mode"); } DefaultTextOutput out = new DefaultTextOutput( jjsOptions.getOutput().shouldMinimize()); JsSourceGenerationVisitor v = new JsSourceGenerationVisitor(out); v.accept(jsProgram); return out.toString(); } /** * Writes artifacts into output directories in the standard way. * * @param logger logs the operation * @param artifacts the set of artifacts to write * @param outputPath the output path for deployable artifacts * @param extraPath optional extra path for non-deployable artifacts * @throws UnableToCompleteException */ public void produceOutputDirectory(TreeLogger logger, ArtifactSet artifacts, File outputPath, File extraPath) throws UnableToCompleteException { outputPath = outputPath.getAbsoluteFile(); if (extraPath != null) { extraPath = extraPath.getAbsoluteFile(); } logger = logger.branch(TreeLogger.TRACE, "Linking compilation into " + outputPath.getPath(), null); Set<String> createdDirs = new HashSet<String>(); for (EmittedArtifact artifact : artifacts.find(EmittedArtifact.class)) { TreeLogger artifactLogger = logger.branch(TreeLogger.DEBUG, "Emitting resource " + artifact.getPartialPath(), null); File outFile; if (artifact.isPrivate()) { if (extraPath == null) { continue; } outFile = new File(getExtraPathForLinker(extraPath, artifact.getLinker()), artifact.getPartialPath()); } else { outFile = new File(outputPath, artifact.getPartialPath()); } if (!outFile.exists() || (outFile.lastModified() <= artifact.getLastModified())) { mkdirs(outFile.getParentFile(), createdDirs); try { RandomAccessFile raf = new RandomAccessFile(outFile, "rw"); byte[] bytes = artifact.getBytes(artifactLogger); raf.setLength(bytes.length); raf.write(bytes); raf.close(); } catch (IOException e) { logger.log(TreeLogger.ERROR, "Unable to create file '" + outFile.getAbsolutePath() + "'", e); throw new UnableToCompleteException(); } outFile.setLastModified(artifact.getLastModified()); } } for (StandardCompilationAnalysis soycFiles : artifacts.find(StandardCompilationAnalysis.class)) { TreeLogger artifactLogger = logger.branch(TreeLogger.DEBUG, "Emitting soyc resources.", null); File depFile = new File(extraPath + "/soycReport", soycFiles.getDepFile().getName()); Util.copy(artifactLogger, soycFiles.getDepFile(), depFile); File storiesFile = new File(extraPath + "/soycReport", soycFiles.getStoriesFile().getName()); Util.copy(artifactLogger, soycFiles.getStoriesFile(), storiesFile); File splitPointsFile = new File(extraPath + "/soycReport", soycFiles.getSplitPointsFile().getName()); Util.copy(artifactLogger, soycFiles.getSplitPointsFile(), splitPointsFile); } } /** * Creates a linker-specific subdirectory in the module's auxiliary output * directory. */ private File getExtraPathForLinker(File extraPath, Class<? extends Linker> linkerType) { assert linkerShortNames.containsKey(linkerType) : linkerType.getName() + " unknown"; File toReturn = new File(extraPath, linkerShortNames.get(linkerType)); if (!toReturn.exists()) { toReturn.mkdirs(); } return toReturn; } }
true
true
public StandardLinkerContext(TreeLogger logger, ModuleDef module, JJSOptions jjsOptions) throws UnableToCompleteException { logger = logger.branch(TreeLogger.DEBUG, "Constructing StandardLinkerContext", null); this.jjsOptions = jjsOptions; this.moduleFunctionName = module.getFunctionName(); this.moduleName = module.getName(); this.moduleLastModified = module.lastModified(); // Sort the linkers into the order they should actually run. List<Class<? extends Linker>> sortedLinkers = new ArrayList<Class<? extends Linker>>(); // Get all the pre-linkers first. for (Class<? extends Linker> linkerClass : module.getActiveLinkers()) { Order order = linkerClass.getAnnotation(LinkerOrder.class).value(); assert (order != null); if (order == Order.PRE) { sortedLinkers.add(linkerClass); } } // Get the primary linker. sortedLinkers.add(module.getActivePrimaryLinker()); // Get all the post-linkers IN REVERSE ORDER. { List<Class<? extends Linker>> postLinkerClasses = new ArrayList<Class<? extends Linker>>(); for (Class<? extends Linker> linkerClass : module.getActiveLinkers()) { Order order = linkerClass.getAnnotation(LinkerOrder.class).value(); assert (order != null); if (order == Order.POST) { postLinkerClasses.add(linkerClass); } } Collections.reverse(postLinkerClasses); sortedLinkers.addAll(postLinkerClasses); } linkers = new Linker[sortedLinkers.size()]; int i = 0; for (Class<? extends Linker> linkerClass : sortedLinkers) { try { linkers[i++] = linkerClass.newInstance(); } catch (InstantiationException e) { logger.log(TreeLogger.ERROR, "Unable to create Linker", e); throw new UnableToCompleteException(); } catch (IllegalAccessException e) { logger.log(TreeLogger.ERROR, "Unable to create Linker", e); throw new UnableToCompleteException(); } } for (Map.Entry<String, Class<? extends Linker>> entry : module.getLinkers().entrySet()) { linkerShortNames.put(entry.getValue(), entry.getKey()); } /* * This will make all private PublicResources and GeneratedResources appear * in the root of the module auxiliary directory. */ linkerShortNames.put(this.getClass(), ""); // Break ModuleDef properties out into LinkerContext interfaces { SortedSet<ConfigurationProperty> mutableConfigurationProperties = new TreeSet<ConfigurationProperty>( CONFIGURATION_PROPERTY_COMPARATOR); SortedSet<SelectionProperty> mutableSelectionProperties = new TreeSet<SelectionProperty>( SELECTION_PROPERTY_COMPARATOR); for (Property p : module.getProperties()) { // Create a new view if (p instanceof com.google.gwt.dev.cfg.ConfigurationProperty) { StandardConfigurationProperty newProp = new StandardConfigurationProperty( (com.google.gwt.dev.cfg.ConfigurationProperty) p); mutableConfigurationProperties.add(newProp); logger.log(TreeLogger.SPAM, "Added configuration property " + newProp, null); } else if (p instanceof BindingProperty) { StandardSelectionProperty newProp = new StandardSelectionProperty( (BindingProperty) p); mutableSelectionProperties.add(newProp); propertiesByName.put(newProp.getName(), newProp); logger.log(TreeLogger.SPAM, "Added selection property " + newProp, null); } else { logger.log(TreeLogger.ERROR, "Unknown property type " + p.getClass().getName()); } } selectionProperties = Collections.unmodifiableSortedSet(mutableSelectionProperties); configurationProperties = Collections.unmodifiableSortedSet(mutableConfigurationProperties); } { int index = 0; for (Script script : module.getScripts()) { artifacts.add(new StandardScriptReference(script.getSrc(), index++)); logger.log(TreeLogger.SPAM, "Added script " + script.getSrc(), null); } } { int index = 0; for (String style : module.getStyles()) { artifacts.add(new StandardStylesheetReference(style, index++)); logger.log(TreeLogger.SPAM, "Added style " + style, null); } } // Generated files should be passed in via addArtifacts() for (String path : module.getAllPublicFiles()) { String partialPath = path.replace(File.separatorChar, '/'); PublicResource resource = new StandardPublicResource(partialPath, module.findPublicFile(path)); artifacts.add(resource); logger.log(TreeLogger.SPAM, "Added public resource " + resource, null); } }
public StandardLinkerContext(TreeLogger logger, ModuleDef module, JJSOptions jjsOptions) throws UnableToCompleteException { logger = logger.branch(TreeLogger.DEBUG, "Constructing StandardLinkerContext", null); this.jjsOptions = jjsOptions; this.moduleFunctionName = module.getFunctionName(); this.moduleName = module.getName(); this.moduleLastModified = module.lastModified(); // Sort the linkers into the order they should actually run. List<Class<? extends Linker>> sortedLinkers = new ArrayList<Class<? extends Linker>>(); // Get all the pre-linkers first. for (Class<? extends Linker> linkerClass : module.getActiveLinkers()) { Order order = linkerClass.getAnnotation(LinkerOrder.class).value(); assert (order != null); if (order == Order.PRE) { sortedLinkers.add(linkerClass); } } // Get the primary linker. Class<? extends Linker> primary = module.getActivePrimaryLinker(); if (primary == null) { logger.log(logger.ERROR, "Primary linker is null. Does your module " + "inherit from com.google.gwt.core.Core or com.google.gwt.user.User?"); } else { sortedLinkers.add(module.getActivePrimaryLinker()); } // Get all the post-linkers IN REVERSE ORDER. { List<Class<? extends Linker>> postLinkerClasses = new ArrayList<Class<? extends Linker>>(); for (Class<? extends Linker> linkerClass : module.getActiveLinkers()) { Order order = linkerClass.getAnnotation(LinkerOrder.class).value(); assert (order != null); if (order == Order.POST) { postLinkerClasses.add(linkerClass); } } Collections.reverse(postLinkerClasses); sortedLinkers.addAll(postLinkerClasses); } linkers = new Linker[sortedLinkers.size()]; int i = 0; for (Class<? extends Linker> linkerClass : sortedLinkers) { try { linkers[i++] = linkerClass.newInstance(); } catch (InstantiationException e) { logger.log(TreeLogger.ERROR, "Unable to create Linker", e); throw new UnableToCompleteException(); } catch (IllegalAccessException e) { logger.log(TreeLogger.ERROR, "Unable to create Linker", e); throw new UnableToCompleteException(); } } for (Map.Entry<String, Class<? extends Linker>> entry : module.getLinkers().entrySet()) { linkerShortNames.put(entry.getValue(), entry.getKey()); } /* * This will make all private PublicResources and GeneratedResources appear * in the root of the module auxiliary directory. */ linkerShortNames.put(this.getClass(), ""); // Break ModuleDef properties out into LinkerContext interfaces { SortedSet<ConfigurationProperty> mutableConfigurationProperties = new TreeSet<ConfigurationProperty>( CONFIGURATION_PROPERTY_COMPARATOR); SortedSet<SelectionProperty> mutableSelectionProperties = new TreeSet<SelectionProperty>( SELECTION_PROPERTY_COMPARATOR); for (Property p : module.getProperties()) { // Create a new view if (p instanceof com.google.gwt.dev.cfg.ConfigurationProperty) { StandardConfigurationProperty newProp = new StandardConfigurationProperty( (com.google.gwt.dev.cfg.ConfigurationProperty) p); mutableConfigurationProperties.add(newProp); logger.log(TreeLogger.SPAM, "Added configuration property " + newProp, null); } else if (p instanceof BindingProperty) { StandardSelectionProperty newProp = new StandardSelectionProperty( (BindingProperty) p); mutableSelectionProperties.add(newProp); propertiesByName.put(newProp.getName(), newProp); logger.log(TreeLogger.SPAM, "Added selection property " + newProp, null); } else { logger.log(TreeLogger.ERROR, "Unknown property type " + p.getClass().getName()); } } selectionProperties = Collections.unmodifiableSortedSet(mutableSelectionProperties); configurationProperties = Collections.unmodifiableSortedSet(mutableConfigurationProperties); } { int index = 0; for (Script script : module.getScripts()) { artifacts.add(new StandardScriptReference(script.getSrc(), index++)); logger.log(TreeLogger.SPAM, "Added script " + script.getSrc(), null); } } { int index = 0; for (String style : module.getStyles()) { artifacts.add(new StandardStylesheetReference(style, index++)); logger.log(TreeLogger.SPAM, "Added style " + style, null); } } // Generated files should be passed in via addArtifacts() for (String path : module.getAllPublicFiles()) { String partialPath = path.replace(File.separatorChar, '/'); PublicResource resource = new StandardPublicResource(partialPath, module.findPublicFile(path)); artifacts.add(resource); logger.log(TreeLogger.SPAM, "Added public resource " + resource, null); } }
diff --git a/collectImages.java b/collectImages.java index af4af12..fb2b77b 100644 --- a/collectImages.java +++ b/collectImages.java @@ -1,29 +1,29 @@ /** * This program takes a website URL and Directory, prints all the image URLs from the web page, and * saves all the images to the specified Directory. * @author Andrew Knapp * @version 1.0 */ public class collectImages { public static void main(String[] args) { - if (args.length != 2) - { + if (args.length != 2) + { System.err.println(" Incorrect number of arguments"); System.err.println(" Usage: "); System.err. println("\tjava collectImages <String URL> <output directory>"); System.exit(1); - } + } String downloadSite = args[0]; String fileDirectory = args[1]; imageCollector page = new imageCollector(downloadSite, fileDirectory); page.fetchWebsite(downloadSite); page.downloadImages(); page.printImageURLs(); } }
false
true
public static void main(String[] args) { if (args.length != 2) { System.err.println(" Incorrect number of arguments"); System.err.println(" Usage: "); System.err. println("\tjava collectImages <String URL> <output directory>"); System.exit(1); } String downloadSite = args[0]; String fileDirectory = args[1]; imageCollector page = new imageCollector(downloadSite, fileDirectory); page.fetchWebsite(downloadSite); page.downloadImages(); page.printImageURLs(); }
public static void main(String[] args) { if (args.length != 2) { System.err.println(" Incorrect number of arguments"); System.err.println(" Usage: "); System.err. println("\tjava collectImages <String URL> <output directory>"); System.exit(1); } String downloadSite = args[0]; String fileDirectory = args[1]; imageCollector page = new imageCollector(downloadSite, fileDirectory); page.fetchWebsite(downloadSite); page.downloadImages(); page.printImageURLs(); }
diff --git a/src/main/java/com/ctb/pilot/common/filter/login/LoginCheckFilter.java b/src/main/java/com/ctb/pilot/common/filter/login/LoginCheckFilter.java index 47fe440..4c479d3 100644 --- a/src/main/java/com/ctb/pilot/common/filter/login/LoginCheckFilter.java +++ b/src/main/java/com/ctb/pilot/common/filter/login/LoginCheckFilter.java @@ -1,53 +1,52 @@ package com.ctb.pilot.common.filter.login; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.ctb.pilot.chat.dao.UserDao; import com.ctb.pilot.chat.dao.jdbc.JdbcUserDao; import com.ctb.pilot.chat.model.User; import com.ctb.pilot.common.util.HttpUtils; public class LoginCheckFilter implements Filter { private UserDao userDao = new JdbcUserDao(); @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; HttpSession session = httpRequest.getSession(); - Object sequence = session.getAttribute("seq"); - if (sequence == null) { + User user = (User) session.getAttribute("user"); + if (user == null) { String sequenceInCookie = HttpUtils.getCookie(httpRequest, "seq"); if (sequenceInCookie == null) { httpResponse.sendRedirect("/pilot/login/login.html"); return; } Integer userSequence = Integer.valueOf(sequenceInCookie); - User user = userDao.getUserBySequence(userSequence); - System.out.println("user: " + user); + user = userDao.getUserBySequence(userSequence); session.setAttribute("user", user); } chain.doFilter(request, response); } @Override public void destroy() { } }
false
true
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; HttpSession session = httpRequest.getSession(); Object sequence = session.getAttribute("seq"); if (sequence == null) { String sequenceInCookie = HttpUtils.getCookie(httpRequest, "seq"); if (sequenceInCookie == null) { httpResponse.sendRedirect("/pilot/login/login.html"); return; } Integer userSequence = Integer.valueOf(sequenceInCookie); User user = userDao.getUserBySequence(userSequence); System.out.println("user: " + user); session.setAttribute("user", user); } chain.doFilter(request, response); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; HttpSession session = httpRequest.getSession(); User user = (User) session.getAttribute("user"); if (user == null) { String sequenceInCookie = HttpUtils.getCookie(httpRequest, "seq"); if (sequenceInCookie == null) { httpResponse.sendRedirect("/pilot/login/login.html"); return; } Integer userSequence = Integer.valueOf(sequenceInCookie); user = userDao.getUserBySequence(userSequence); session.setAttribute("user", user); } chain.doFilter(request, response); }
diff --git a/src/com/android/contacts/ViewContactActivity.java b/src/com/android/contacts/ViewContactActivity.java index 3d5ac859c..e6dd623e9 100644 --- a/src/com/android/contacts/ViewContactActivity.java +++ b/src/com/android/contacts/ViewContactActivity.java @@ -1,1248 +1,1247 @@ /* * Copyright (C) 2007 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.android.contacts; import com.android.contacts.Collapser.Collapsible; import com.android.contacts.model.ContactsSource; import com.android.contacts.model.Sources; import com.android.contacts.model.ContactsSource.DataKind; import com.android.contacts.ui.EditContactActivity; import com.android.contacts.util.Constants; import com.android.contacts.util.DataStatus; import com.android.contacts.util.NotifyingAsyncQueryHandler; import com.android.internal.telephony.ITelephony; import com.android.internal.widget.ContactHeaderWidget; import com.google.android.collect.Lists; import com.google.android.collect.Maps; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Entity; import android.content.EntityIterator; import android.content.Intent; import android.content.Entity.NamedContentValues; import android.content.res.Resources; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.os.ServiceManager; import android.provider.ContactsContract; import android.provider.ContactsContract.AggregationExceptions; import android.provider.ContactsContract.CommonDataKinds; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.StatusUpdates; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Im; import android.provider.ContactsContract.CommonDataKinds.Nickname; import android.provider.ContactsContract.CommonDataKinds.Note; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.telephony.PhoneNumberUtils; import android.text.TextUtils; import android.util.Log; import android.view.ContextMenu; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.ContextMenu.ContextMenuInfo; import android.widget.AdapterView; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; /** * Displays the details of a specific contact. */ public class ViewContactActivity extends Activity implements View.OnCreateContextMenuListener, DialogInterface.OnClickListener, AdapterView.OnItemClickListener, NotifyingAsyncQueryHandler.AsyncQueryListener { private static final String TAG = "ViewContact"; private static final boolean SHOW_SEPARATORS = false; private static final int DIALOG_CONFIRM_DELETE = 1; private static final int DIALOG_CONFIRM_READONLY_DELETE = 2; private static final int DIALOG_CONFIRM_MULTIPLE_DELETE = 3; private static final int DIALOG_CONFIRM_READONLY_HIDE = 4; private static final int REQUEST_JOIN_CONTACT = 1; private static final int REQUEST_EDIT_CONTACT = 2; public static final int MENU_ITEM_MAKE_DEFAULT = 3; protected Uri mLookupUri; private ContentResolver mResolver; private ViewAdapter mAdapter; private int mNumPhoneNumbers = 0; /** * A list of distinct contact IDs included in the current contact. */ private ArrayList<Long> mRawContactIds = new ArrayList<Long>(); /* package */ ArrayList<ViewEntry> mPhoneEntries = new ArrayList<ViewEntry>(); /* package */ ArrayList<ViewEntry> mSmsEntries = new ArrayList<ViewEntry>(); /* package */ ArrayList<ViewEntry> mEmailEntries = new ArrayList<ViewEntry>(); /* package */ ArrayList<ViewEntry> mPostalEntries = new ArrayList<ViewEntry>(); /* package */ ArrayList<ViewEntry> mImEntries = new ArrayList<ViewEntry>(); /* package */ ArrayList<ViewEntry> mOrganizationEntries = new ArrayList<ViewEntry>(); /* package */ ArrayList<ViewEntry> mGroupEntries = new ArrayList<ViewEntry>(); /* package */ ArrayList<ViewEntry> mOtherEntries = new ArrayList<ViewEntry>(); /* package */ ArrayList<ArrayList<ViewEntry>> mSections = new ArrayList<ArrayList<ViewEntry>>(); private Cursor mCursor; protected ContactHeaderWidget mContactHeaderWidget; private NotifyingAsyncQueryHandler mHandler; protected LayoutInflater mInflater; protected int mReadOnlySourcesCnt; protected int mWritableSourcesCnt; protected ArrayList<Long> mWritableRawContactIds = new ArrayList<Long>(); private static final int TOKEN_ENTITIES = 0; private static final int TOKEN_STATUSES = 1; private boolean mHasEntities = false; private boolean mHasStatuses = false; private ArrayList<Entity> mEntities = Lists.newArrayList(); private HashMap<Long, DataStatus> mStatuses = Maps.newHashMap(); private ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public boolean deliverSelfNotifications() { return true; } @Override public void onChange(boolean selfChange) { if (mCursor != null && !mCursor.isClosed()) { startEntityQuery(); } } }; public void onClick(DialogInterface dialog, int which) { closeCursor(); getContentResolver().delete(mLookupUri, null, null); finish(); } private FrameLayout mTabContentLayout; private ListView mListView; private boolean mShowSmsLinksForAllPhones; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); final Intent intent = getIntent(); Uri data = intent.getData(); String authority = data.getAuthority(); if (ContactsContract.AUTHORITY.equals(authority)) { mLookupUri = data; } else if (android.provider.Contacts.AUTHORITY.equals(authority)) { final long rawContactId = ContentUris.parseId(data); mLookupUri = RawContacts.getContactLookupUri(getContentResolver(), ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId)); } mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.contact_card_layout); mContactHeaderWidget = (ContactHeaderWidget) findViewById(R.id.contact_header_widget); mContactHeaderWidget.showStar(true); mContactHeaderWidget.setExcludeMimes(new String[] { Contacts.CONTENT_ITEM_TYPE }); mHandler = new NotifyingAsyncQueryHandler(this, this); mListView = new ListView(this); mListView.setOnCreateContextMenuListener(this); mListView.setScrollBarStyle(ListView.SCROLLBARS_OUTSIDE_OVERLAY); mListView.setOnItemClickListener(this); mTabContentLayout = (FrameLayout) findViewById(android.R.id.tabcontent); mTabContentLayout.addView(mListView); mResolver = getContentResolver(); // Build the list of sections. The order they're added to mSections dictates the // order they are displayed in the list. mSections.add(mPhoneEntries); mSections.add(mSmsEntries); mSections.add(mEmailEntries); mSections.add(mImEntries); mSections.add(mPostalEntries); mSections.add(mOrganizationEntries); mSections.add(mGroupEntries); mSections.add(mOtherEntries); //TODO Read this value from a preference mShowSmsLinksForAllPhones = true; } @Override protected void onResume() { super.onResume(); startEntityQuery(); } @Override protected void onPause() { super.onPause(); closeCursor(); } @Override protected void onDestroy() { super.onDestroy(); closeCursor(); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_CONFIRM_DELETE: return new AlertDialog.Builder(this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.deleteConfirmation) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, this) .setCancelable(false) .create(); case DIALOG_CONFIRM_READONLY_DELETE: return new AlertDialog.Builder(this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.readOnlyContactDeleteConfirmation) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, this) .setCancelable(false) .create(); case DIALOG_CONFIRM_MULTIPLE_DELETE: return new AlertDialog.Builder(this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.multipleContactDeleteConfirmation) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, this) .setCancelable(false) .create(); case DIALOG_CONFIRM_READONLY_HIDE: { return new AlertDialog.Builder(this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.readOnlyContactWarning) .setPositiveButton(android.R.string.ok, this) .create(); } } return null; } // QUERY CODE // /** {@inheritDoc} */ public void onQueryEntitiesComplete(int token, Object cookie, EntityIterator iterator) { try { // Read incoming entities and consider binding readEntities(iterator); considerBindData(); } finally { if (iterator != null) { iterator.close(); } } } /** {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { try { // Read available social rows and consider binding readStatuses(cursor); considerBindData(); } finally { if (cursor != null) { cursor.close(); } } } private long getRefreshedContactId() { Uri freshContactUri = Contacts.lookupContact(getContentResolver(), mLookupUri); if (freshContactUri != null) { return ContentUris.parseId(freshContactUri); } return -1; } /** * Read from the given {@link EntityIterator} to build internal set of * {@link #mEntities} for data display. */ private synchronized void readEntities(EntityIterator iterator) { mEntities.clear(); try { while (iterator.hasNext()) { mEntities.add(iterator.next()); } mHasEntities = true; } catch (RemoteException e) { Log.w(TAG, "Problem reading contact data: " + e.toString()); } } /** * Read from the given {@link Cursor} and build a set of {@link DataStatus} * objects to match any valid statuses found. */ private synchronized void readStatuses(Cursor cursor) { mStatuses.clear(); // Walk found statuses, creating internal row for each while (cursor.moveToNext()) { final DataStatus status = new DataStatus(cursor); final long dataId = cursor.getLong(StatusQuery._ID); mStatuses.put(dataId, status); } mHasStatuses = true; } private synchronized void startEntityQuery() { closeCursor(); Uri uri = null; if (mLookupUri != null) { mLookupUri = Contacts.getLookupUri(getContentResolver(), mLookupUri); if (mLookupUri != null) { uri = Contacts.lookupContact(getContentResolver(), mLookupUri); } } if (uri == null) { // TODO either figure out a way to prevent a flash of black background or // use some other UI than a toast Toast.makeText(this, R.string.invalidContactMessage, Toast.LENGTH_SHORT).show(); Log.e(TAG, "invalid contact uri: " + mLookupUri); finish(); return; } final Uri dataUri = Uri.withAppendedPath(uri, Contacts.Data.CONTENT_DIRECTORY); // Keep stub cursor open on side to watch for change events mCursor = mResolver.query(dataUri, new String[] {Contacts.DISPLAY_NAME}, null, null, null); mCursor.registerContentObserver(mObserver); final long contactId = ContentUris.parseId(uri); // Clear flags and start queries to data and status mHasEntities = false; mHasStatuses = false; mHandler.startQueryEntities(TOKEN_ENTITIES, null, RawContacts.CONTENT_URI, RawContacts.CONTACT_ID + "=" + contactId, null, null); mHandler.startQuery(TOKEN_STATUSES, null, dataUri, StatusQuery.PROJECTION, StatusUpdates.PRESENCE + " IS NOT NULL OR " + StatusUpdates.STATUS + " IS NOT NULL", null, null); mContactHeaderWidget.bindFromContactLookupUri(mLookupUri); } private void closeCursor() { if (mCursor != null) { mCursor.unregisterContentObserver(mObserver); mCursor.close(); mCursor = null; } } /** * Consider binding views after any of several background queries has * completed. We check internal flags and only bind when all data has * arrived. */ private void considerBindData() { if (mHasEntities && mHasStatuses) { bindData(); } } private void bindData() { // Build up the contact entries buildEntries(); // Collapse similar data items in select sections. Collapser.collapseList(mPhoneEntries); Collapser.collapseList(mSmsEntries); Collapser.collapseList(mEmailEntries); Collapser.collapseList(mPostalEntries); Collapser.collapseList(mImEntries); if (mAdapter == null) { mAdapter = new ViewAdapter(this, mSections); mListView.setAdapter(mAdapter); } else { mAdapter.setSections(mSections, SHOW_SEPARATORS); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); final MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.view, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); // Only allow edit when we have at least one raw_contact id final boolean hasRawContact = (mRawContactIds.size() > 0); menu.findItem(R.id.menu_edit).setEnabled(hasRawContact); return true; } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) menuInfo; } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return; } // This can be null sometimes, don't crash... if (info == null) { Log.e(TAG, "bad menuInfo"); return; } ViewEntry entry = ContactEntryAdapter.getEntry(mSections, info.position, SHOW_SEPARATORS); menu.setHeaderTitle(R.string.contactOptionsTitle); if (entry.mimetype.equals(CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) { menu.add(0, 0, 0, R.string.menu_call).setIntent(entry.intent); menu.add(0, 0, 0, R.string.menu_sendSMS).setIntent(entry.secondaryIntent); if (!entry.isPrimary) { menu.add(0, MENU_ITEM_MAKE_DEFAULT, 0, R.string.menu_makeDefaultNumber); } } else if (entry.mimetype.equals(CommonDataKinds.Email.CONTENT_ITEM_TYPE)) { menu.add(0, 0, 0, R.string.menu_sendEmail).setIntent(entry.intent); if (!entry.isPrimary) { menu.add(0, MENU_ITEM_MAKE_DEFAULT, 0, R.string.menu_makeDefaultEmail); } } else if (entry.mimetype.equals(CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)) { menu.add(0, 0, 0, R.string.menu_viewAddress).setIntent(entry.intent); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_edit: { Long rawContactIdToEdit = null; if (mRawContactIds.size() > 0) { rawContactIdToEdit = mRawContactIds.get(0); } else { // There is no rawContact to edit. break; } Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactIdToEdit); startActivityForResult(new Intent(Intent.ACTION_EDIT, rawContactUri), REQUEST_EDIT_CONTACT); break; } case R.id.menu_delete: { // Get confirmation if (mReadOnlySourcesCnt > 0 & mWritableSourcesCnt > 0) { showDialog(DIALOG_CONFIRM_READONLY_DELETE); } else if (mReadOnlySourcesCnt > 0 && mWritableSourcesCnt == 0) { showDialog(DIALOG_CONFIRM_READONLY_HIDE); } else if (mReadOnlySourcesCnt == 0 && mWritableSourcesCnt > 1) { showDialog(DIALOG_CONFIRM_MULTIPLE_DELETE); } else { showDialog(DIALOG_CONFIRM_DELETE); } return true; } case R.id.menu_join: { showJoinAggregateActivity(); return true; } case R.id.menu_options: { showOptionsActivity(); return true; } case R.id.menu_share: { // TODO: Keep around actual LOOKUP_KEY, or formalize method of extracting final String lookupKey = mLookupUri.getPathSegments().get(2); final Uri shareUri = Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey); final Intent intent = new Intent(Intent.ACTION_SEND); intent.setType(Contacts.CONTENT_VCARD_TYPE); intent.putExtra(Intent.EXTRA_STREAM, shareUri); // Launch chooser to share contact via final CharSequence chooseTitle = getText(R.string.share_via); final Intent chooseIntent = Intent.createChooser(intent, chooseTitle); try { startActivity(chooseIntent); } catch (ActivityNotFoundException ex) { Toast.makeText(this, R.string.share_error, Toast.LENGTH_SHORT).show(); } return true; } } return super.onOptionsItemSelected(item); } @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_ITEM_MAKE_DEFAULT: { if (makeItemDefault(item)) { return true; } break; } } return super.onContextItemSelected(item); } private boolean makeItemDefault(MenuItem item) { ViewEntry entry = getViewEntryForMenuItem(item); if (entry == null) { return false; } // Update the primary values in the data record. ContentValues values = new ContentValues(1); values.put(Data.IS_SUPER_PRIMARY, 1); getContentResolver().update(ContentUris.withAppendedId(Data.CONTENT_URI, entry.id), values, null, null); startEntityQuery(); return true; } /** * Shows a list of aggregates that can be joined into the currently viewed aggregate. */ public void showJoinAggregateActivity() { long freshId = getRefreshedContactId(); if (freshId > 0) { String displayName = null; if (mCursor.moveToFirst()) { displayName = mCursor.getString(0); } Intent intent = new Intent(ContactsListActivity.JOIN_AGGREGATE); intent.putExtra(ContactsListActivity.EXTRA_AGGREGATE_ID, freshId); if (displayName != null) { intent.putExtra(ContactsListActivity.EXTRA_AGGREGATE_NAME, displayName); } startActivityForResult(intent, REQUEST_JOIN_CONTACT); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == REQUEST_JOIN_CONTACT) { if (resultCode == RESULT_OK && intent != null) { final long contactId = ContentUris.parseId(intent.getData()); joinAggregate(contactId); } } else if (requestCode == REQUEST_EDIT_CONTACT) { if (resultCode == EditContactActivity.RESULT_CLOSE_VIEW_ACTIVITY) { finish(); } else if (resultCode == Activity.RESULT_OK) { mLookupUri = intent.getData(); if (mLookupUri == null) { finish(); } } } } private void splitContact(long rawContactId) { setAggregationException(rawContactId, AggregationExceptions.TYPE_KEEP_SEPARATE); // The split operation may have removed the original aggregate contact, so we need // to requery everything Toast.makeText(this, R.string.contactsSplitMessage, Toast.LENGTH_LONG).show(); startEntityQuery(); } private void joinAggregate(final long contactId) { Cursor c = mResolver.query(RawContacts.CONTENT_URI, new String[] {RawContacts._ID}, RawContacts.CONTACT_ID + "=" + contactId, null, null); try { while(c.moveToNext()) { long rawContactId = c.getLong(0); setAggregationException(rawContactId, AggregationExceptions.TYPE_KEEP_TOGETHER); } } finally { c.close(); } Toast.makeText(this, R.string.contactsJoinedMessage, Toast.LENGTH_LONG).show(); startEntityQuery(); } /** * Given a contact ID sets an aggregation exception to either join the contact with the * current aggregate or split off. */ protected void setAggregationException(long rawContactId, int exceptionType) { ContentValues values = new ContentValues(3); for (long aRawContactId : mRawContactIds) { if (aRawContactId != rawContactId) { values.put(AggregationExceptions.RAW_CONTACT_ID1, aRawContactId); values.put(AggregationExceptions.RAW_CONTACT_ID2, rawContactId); values.put(AggregationExceptions.TYPE, exceptionType); mResolver.update(AggregationExceptions.CONTENT_URI, values, null, null); } } } private void showOptionsActivity() { final Intent intent = new Intent(this, ContactOptionsActivity.class); intent.setData(mLookupUri); startActivity(intent); } private ViewEntry getViewEntryForMenuItem(MenuItem item) { AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return null; } return ContactEntryAdapter.getEntry(mSections, info.position, SHOW_SEPARATORS); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_CALL: { try { ITelephony phone = ITelephony.Stub.asInterface( ServiceManager.checkService("phone")); if (phone != null && !phone.isIdle()) { // Skip out and let the key be handled at a higher level break; } } catch (RemoteException re) { // Fall through and try to call the contact } int index = mListView.getSelectedItemPosition(); if (index != -1) { ViewEntry entry = ViewAdapter.getEntry(mSections, index, SHOW_SEPARATORS); if (entry.intent.getAction() == Intent.ACTION_CALL_PRIVILEGED) { startActivity(entry.intent); } } else if (mNumPhoneNumbers != 0) { // There isn't anything selected, call the default number long freshContactId = getRefreshedContactId(); if (freshContactId > 0) { Uri hardContacUri = ContentUris.withAppendedId( Contacts.CONTENT_URI, freshContactId); Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED, hardContacUri); startActivity(intent); } } return true; } case KeyEvent.KEYCODE_DEL: { if (mReadOnlySourcesCnt > 0 & mWritableSourcesCnt > 0) { showDialog(DIALOG_CONFIRM_READONLY_DELETE); } else if (mReadOnlySourcesCnt > 0 && mWritableSourcesCnt == 0) { showDialog(DIALOG_CONFIRM_READONLY_HIDE); } else if (mReadOnlySourcesCnt == 0 && mWritableSourcesCnt > 1) { showDialog(DIALOG_CONFIRM_MULTIPLE_DELETE); } else { showDialog(DIALOG_CONFIRM_DELETE); } return true; } } return super.onKeyDown(keyCode, event); } public void onItemClick(AdapterView parent, View v, int position, long id) { ViewEntry entry = ViewAdapter.getEntry(mSections, position, SHOW_SEPARATORS); if (entry != null) { Intent intent = entry.intent; if (intent != null) { try { startActivity(intent); } catch (ActivityNotFoundException e) { Log.e(TAG, "No activity found for intent: " + intent); signalError(); } } else { signalError(); } } else { signalError(); } } /** * Signal an error to the user via a beep, or some other method. */ private void signalError() { //TODO: implement this when we have the sonification APIs } /** * Build up the entries to display on the screen. * * @param personCursor the URI for the contact being displayed */ private final void buildEntries() { // Clear out the old entries final int numSections = mSections.size(); for (int i = 0; i < numSections; i++) { mSections.get(i).clear(); } mRawContactIds.clear(); mReadOnlySourcesCnt = 0; mWritableSourcesCnt = 0; mWritableRawContactIds.clear(); final Context context = this; final Sources sources = Sources.getInstance(context); // Build up method entries if (mLookupUri != null) { for (Entity entity: mEntities) { final ContentValues entValues = entity.getEntityValues(); final String accountType = entValues.getAsString(RawContacts.ACCOUNT_TYPE); final long rawContactId = entValues.getAsLong(RawContacts._ID); if (!mRawContactIds.contains(rawContactId)) { mRawContactIds.add(rawContactId); } ContactsSource contactsSource = sources.getInflatedSource(accountType, ContactsSource.LEVEL_SUMMARY); if (contactsSource != null && contactsSource.readOnly) { mReadOnlySourcesCnt += 1; } else { mWritableSourcesCnt += 1; mWritableRawContactIds.add(rawContactId); } for (NamedContentValues subValue : entity.getSubValues()) { final ContentValues entryValues = subValue.values; entryValues.put(Data.RAW_CONTACT_ID, rawContactId); final long dataId = entryValues.getAsLong(Data._ID); final String mimeType = entryValues.getAsString(Data.MIMETYPE); if (mimeType == null) continue; final DataKind kind = sources.getKindOrFallback(accountType, mimeType, this, ContactsSource.LEVEL_MIMETYPES); if (kind == null) continue; final ViewEntry entry = ViewEntry.fromValues(context, mimeType, kind, rawContactId, dataId, entryValues); final boolean hasData = !TextUtils.isEmpty(entry.data); final boolean isSuperPrimary = entryValues.getAsInteger( Data.IS_SUPER_PRIMARY) != 0; if (Phone.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) { // Build phone entries mNumPhoneNumbers++; entry.intent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts(Constants.SCHEME_TEL, entry.data, null)); entry.secondaryIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(Constants.SCHEME_SMSTO, entry.data, null)); - entry.data = PhoneNumberUtils.stripSeparators(entry.data); entry.isPrimary = isSuperPrimary; mPhoneEntries.add(entry); if (entry.type == CommonDataKinds.Phone.TYPE_MOBILE || mShowSmsLinksForAllPhones) { // Add an SMS entry if (kind.iconAltRes > 0) { entry.secondaryActionIcon = kind.iconAltRes; } } } else if (Email.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) { // Build email entries entry.intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(Constants.SCHEME_MAILTO, entry.data, null)); entry.isPrimary = isSuperPrimary; mEmailEntries.add(entry); // When Email rows have status, create additional Im row final DataStatus status = mStatuses.get(entry.id); if (status != null) { final String imMime = Im.CONTENT_ITEM_TYPE; final DataKind imKind = sources.getKindOrFallback(accountType, imMime, this, ContactsSource.LEVEL_MIMETYPES); final ViewEntry imEntry = ViewEntry.fromValues(context, imMime, imKind, rawContactId, dataId, entryValues); imEntry.intent = ContactsUtils.buildImIntent(entryValues); imEntry.applyStatus(status, false); mImEntries.add(imEntry); } } else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) { // Build postal entries entry.maxLines = 4; entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri); mPostalEntries.add(entry); } else if (Im.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) { // Build IM entries entry.intent = ContactsUtils.buildImIntent(entryValues); if (TextUtils.isEmpty(entry.label)) { entry.label = getString(R.string.chat).toLowerCase(); } // Apply presence and status details when available final DataStatus status = mStatuses.get(entry.id); if (status != null) { entry.applyStatus(status, false); } mImEntries.add(entry); } else if ((Organization.CONTENT_ITEM_TYPE.equals(mimeType) || Nickname.CONTENT_ITEM_TYPE.equals(mimeType)) && hasData) { // Build organization and note entries entry.uri = null; mOrganizationEntries.add(entry); } else if (Note.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) { // Build note entries entry.uri = null; entry.maxLines = 10; mOtherEntries.add(entry); } else { // Handle showing custom rows entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri); // Use social summary when requested by external source final DataStatus status = mStatuses.get(entry.id); final boolean hasSocial = kind.actionBodySocial && status != null; if (hasSocial) { entry.applyStatus(status, true); } if (hasSocial || hasData) { mOtherEntries.add(entry); } } } } } } static String buildActionString(DataKind kind, ContentValues values, boolean lowerCase, Context context) { if (kind.actionHeader == null) { return null; } CharSequence actionHeader = kind.actionHeader.inflateUsing(context, values); if (actionHeader == null) { return null; } return lowerCase ? actionHeader.toString().toLowerCase() : actionHeader.toString(); } static String buildDataString(DataKind kind, ContentValues values, Context context) { if (kind.actionBody == null) { return null; } CharSequence actionBody = kind.actionBody.inflateUsing(context, values); return actionBody == null ? null : actionBody.toString(); } /** * A basic structure with the data for a contact entry in the list. */ static class ViewEntry extends ContactEntryAdapter.Entry implements Collapsible<ViewEntry> { public Context context = null; public String resPackageName = null; public int actionIcon = -1; public boolean isPrimary = false; public int secondaryActionIcon = -1; public Intent intent; public Intent secondaryIntent = null; public int maxLabelLines = 1; public ArrayList<Long> ids = new ArrayList<Long>(); public int collapseCount = 0; public int presence = -1; public int presenceIcon = -1; public CharSequence footerLine = null; private ViewEntry() { } /** * Build new {@link ViewEntry} and populate from the given values. */ public static ViewEntry fromValues(Context context, String mimeType, DataKind kind, long rawContactId, long dataId, ContentValues values) { final ViewEntry entry = new ViewEntry(); entry.context = context; entry.contactId = rawContactId; entry.id = dataId; entry.uri = ContentUris.withAppendedId(Data.CONTENT_URI, entry.id); entry.mimetype = mimeType; entry.label = buildActionString(kind, values, false, context); entry.data = buildDataString(kind, values, context); if (kind.typeColumn != null && values.containsKey(kind.typeColumn)) { entry.type = values.getAsInteger(kind.typeColumn); } if (kind.iconRes > 0) { entry.resPackageName = kind.resPackageName; entry.actionIcon = kind.iconRes; } return entry; } /** * Apply given {@link DataStatus} values over this {@link ViewEntry} * * @param fillData When true, the given status replaces {@link #data} * and {@link #footerLine}. Otherwise only {@link #presence} * is updated. */ public ViewEntry applyStatus(DataStatus status, boolean fillData) { presence = status.getPresence(); presenceIcon = (presence == -1) ? -1 : StatusUpdates.getPresenceIconResourceId(this.presence); if (fillData && status.isValid()) { this.data = status.getStatus().toString(); this.footerLine = status.getTimestampLabel(context); } return this; } public boolean collapseWith(ViewEntry entry) { // assert equal collapse keys if (!shouldCollapseWith(entry)) { return false; } // Choose the label associated with the highest type precedence. if (TypePrecedence.getTypePrecedence(mimetype, type) > TypePrecedence.getTypePrecedence(entry.mimetype, entry.type)) { type = entry.type; label = entry.label; } // Choose the max of the maxLines and maxLabelLines values. maxLines = Math.max(maxLines, entry.maxLines); maxLabelLines = Math.max(maxLabelLines, entry.maxLabelLines); // Choose the presence with the highest precedence. if (StatusUpdates.getPresencePrecedence(presence) < StatusUpdates.getPresencePrecedence(entry.presence)) { presence = entry.presence; } // If any of the collapsed entries are primary make the whole thing primary. isPrimary = entry.isPrimary ? true : isPrimary; // uri, and contactdId, shouldn't make a difference. Just keep the original. // Keep track of all the ids that have been collapsed with this one. ids.add(entry.id); collapseCount++; return true; } public boolean shouldCollapseWith(ViewEntry entry) { if (entry == null) { return false; } if (Phone.CONTENT_ITEM_TYPE.equals(mimetype) && Phone.CONTENT_ITEM_TYPE.equals(entry.mimetype)) { if (!PhoneNumberUtils.compare(this.context, data, entry.data)) { return false; } } else { if (!equals(data, entry.data)) { return false; } } if (!equals(mimetype, entry.mimetype) || !intentCollapsible(intent, entry.intent) || !intentCollapsible(secondaryIntent, entry.secondaryIntent) || actionIcon != entry.actionIcon) { return false; } return true; } private boolean equals(Object a, Object b) { return a==b || (a != null && a.equals(b)); } private boolean intentCollapsible(Intent a, Intent b) { if (a == b) { return true; } else if ((a != null && b != null) && equals(a.getAction(), b.getAction())) { return true; } return false; } } /** Cache of the children views of a row */ static class ViewCache { public TextView label; public TextView data; public TextView footer; public ImageView actionIcon; public ImageView presenceIcon; public ImageView primaryIcon; public ImageView secondaryActionButton; public View secondaryActionDivider; // Need to keep track of this too ViewEntry entry; } private final class ViewAdapter extends ContactEntryAdapter<ViewEntry> implements View.OnClickListener { ViewAdapter(Context context, ArrayList<ArrayList<ViewEntry>> sections) { super(context, sections, SHOW_SEPARATORS); } public void onClick(View v) { Intent intent = (Intent) v.getTag(); startActivity(intent); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewEntry entry = getEntry(mSections, position, false); View v; ViewCache views; // Check to see if we can reuse convertView if (convertView != null) { v = convertView; views = (ViewCache) v.getTag(); } else { // Create a new view if needed v = mInflater.inflate(R.layout.list_item_text_icons, parent, false); // Cache the children views = new ViewCache(); views.label = (TextView) v.findViewById(android.R.id.text1); views.data = (TextView) v.findViewById(android.R.id.text2); views.footer = (TextView) v.findViewById(R.id.footer); views.actionIcon = (ImageView) v.findViewById(R.id.action_icon); views.primaryIcon = (ImageView) v.findViewById(R.id.primary_icon); views.presenceIcon = (ImageView) v.findViewById(R.id.presence_icon); views.secondaryActionButton = (ImageView) v.findViewById( R.id.secondary_action_button); views.secondaryActionButton.setOnClickListener(this); views.secondaryActionDivider = v.findViewById(R.id.divider); v.setTag(views); } // Update the entry in the view cache views.entry = entry; // Bind the data to the view bindView(v, entry); return v; } @Override protected View newView(int position, ViewGroup parent) { // getView() handles this throw new UnsupportedOperationException(); } @Override protected void bindView(View view, ViewEntry entry) { final Resources resources = mContext.getResources(); ViewCache views = (ViewCache) view.getTag(); // Set the label TextView label = views.label; setMaxLines(label, entry.maxLabelLines); label.setText(entry.label); // Set the data TextView data = views.data; if (data != null) { if (entry.mimetype.equals(Phone.CONTENT_ITEM_TYPE) || entry.mimetype.equals(Constants.MIME_SMS_ADDRESS)) { data.setText(PhoneNumberUtils.formatNumber(entry.data)); } else { data.setText(entry.data); } setMaxLines(data, entry.maxLines); } // Set the footer if (!TextUtils.isEmpty(entry.footerLine)) { views.footer.setText(entry.footerLine); views.footer.setVisibility(View.VISIBLE); } else { views.footer.setVisibility(View.GONE); } // Set the primary icon views.primaryIcon.setVisibility(entry.isPrimary ? View.VISIBLE : View.GONE); // Set the action icon ImageView action = views.actionIcon; if (entry.actionIcon != -1) { Drawable actionIcon; if (entry.resPackageName != null) { // Load external resources through PackageManager actionIcon = mContext.getPackageManager().getDrawable(entry.resPackageName, entry.actionIcon, null); } else { actionIcon = resources.getDrawable(entry.actionIcon); } action.setImageDrawable(actionIcon); action.setVisibility(View.VISIBLE); } else { // Things should still line up as if there was an icon, so make it invisible action.setVisibility(View.INVISIBLE); } // Set the presence icon Drawable presenceIcon = null; if (entry.presenceIcon != -1) { presenceIcon = resources.getDrawable(entry.presenceIcon); } else if (entry.presence != -1) { presenceIcon = resources.getDrawable( StatusUpdates.getPresenceIconResourceId(entry.presence)); } ImageView presenceIconView = views.presenceIcon; if (presenceIcon != null) { presenceIconView.setImageDrawable(presenceIcon); presenceIconView.setVisibility(View.VISIBLE); } else { presenceIconView.setVisibility(View.GONE); } // Set the secondary action button ImageView secondaryActionView = views.secondaryActionButton; Drawable secondaryActionIcon = null; if (entry.secondaryActionIcon != -1) { secondaryActionIcon = resources.getDrawable(entry.secondaryActionIcon); } if (entry.secondaryIntent != null && secondaryActionIcon != null) { secondaryActionView.setImageDrawable(secondaryActionIcon); secondaryActionView.setTag(entry.secondaryIntent); secondaryActionView.setVisibility(View.VISIBLE); views.secondaryActionDivider.setVisibility(View.VISIBLE); } else { secondaryActionView.setVisibility(View.GONE); views.secondaryActionDivider.setVisibility(View.GONE); } } private void setMaxLines(TextView textView, int maxLines) { if (maxLines == 1) { textView.setSingleLine(true); textView.setEllipsize(TextUtils.TruncateAt.END); } else { textView.setSingleLine(false); textView.setMaxLines(maxLines); textView.setEllipsize(null); } } } private interface StatusQuery { final String[] PROJECTION = new String[] { Data._ID, Data.STATUS, Data.STATUS_RES_PACKAGE, Data.STATUS_ICON, Data.STATUS_LABEL, Data.STATUS_TIMESTAMP, Data.PRESENCE, }; final int _ID = 0; } }
true
true
private final void buildEntries() { // Clear out the old entries final int numSections = mSections.size(); for (int i = 0; i < numSections; i++) { mSections.get(i).clear(); } mRawContactIds.clear(); mReadOnlySourcesCnt = 0; mWritableSourcesCnt = 0; mWritableRawContactIds.clear(); final Context context = this; final Sources sources = Sources.getInstance(context); // Build up method entries if (mLookupUri != null) { for (Entity entity: mEntities) { final ContentValues entValues = entity.getEntityValues(); final String accountType = entValues.getAsString(RawContacts.ACCOUNT_TYPE); final long rawContactId = entValues.getAsLong(RawContacts._ID); if (!mRawContactIds.contains(rawContactId)) { mRawContactIds.add(rawContactId); } ContactsSource contactsSource = sources.getInflatedSource(accountType, ContactsSource.LEVEL_SUMMARY); if (contactsSource != null && contactsSource.readOnly) { mReadOnlySourcesCnt += 1; } else { mWritableSourcesCnt += 1; mWritableRawContactIds.add(rawContactId); } for (NamedContentValues subValue : entity.getSubValues()) { final ContentValues entryValues = subValue.values; entryValues.put(Data.RAW_CONTACT_ID, rawContactId); final long dataId = entryValues.getAsLong(Data._ID); final String mimeType = entryValues.getAsString(Data.MIMETYPE); if (mimeType == null) continue; final DataKind kind = sources.getKindOrFallback(accountType, mimeType, this, ContactsSource.LEVEL_MIMETYPES); if (kind == null) continue; final ViewEntry entry = ViewEntry.fromValues(context, mimeType, kind, rawContactId, dataId, entryValues); final boolean hasData = !TextUtils.isEmpty(entry.data); final boolean isSuperPrimary = entryValues.getAsInteger( Data.IS_SUPER_PRIMARY) != 0; if (Phone.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) { // Build phone entries mNumPhoneNumbers++; entry.intent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts(Constants.SCHEME_TEL, entry.data, null)); entry.secondaryIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(Constants.SCHEME_SMSTO, entry.data, null)); entry.data = PhoneNumberUtils.stripSeparators(entry.data); entry.isPrimary = isSuperPrimary; mPhoneEntries.add(entry); if (entry.type == CommonDataKinds.Phone.TYPE_MOBILE || mShowSmsLinksForAllPhones) { // Add an SMS entry if (kind.iconAltRes > 0) { entry.secondaryActionIcon = kind.iconAltRes; } } } else if (Email.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) { // Build email entries entry.intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(Constants.SCHEME_MAILTO, entry.data, null)); entry.isPrimary = isSuperPrimary; mEmailEntries.add(entry); // When Email rows have status, create additional Im row final DataStatus status = mStatuses.get(entry.id); if (status != null) { final String imMime = Im.CONTENT_ITEM_TYPE; final DataKind imKind = sources.getKindOrFallback(accountType, imMime, this, ContactsSource.LEVEL_MIMETYPES); final ViewEntry imEntry = ViewEntry.fromValues(context, imMime, imKind, rawContactId, dataId, entryValues); imEntry.intent = ContactsUtils.buildImIntent(entryValues); imEntry.applyStatus(status, false); mImEntries.add(imEntry); } } else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) { // Build postal entries entry.maxLines = 4; entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri); mPostalEntries.add(entry); } else if (Im.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) { // Build IM entries entry.intent = ContactsUtils.buildImIntent(entryValues); if (TextUtils.isEmpty(entry.label)) { entry.label = getString(R.string.chat).toLowerCase(); } // Apply presence and status details when available final DataStatus status = mStatuses.get(entry.id); if (status != null) { entry.applyStatus(status, false); } mImEntries.add(entry); } else if ((Organization.CONTENT_ITEM_TYPE.equals(mimeType) || Nickname.CONTENT_ITEM_TYPE.equals(mimeType)) && hasData) { // Build organization and note entries entry.uri = null; mOrganizationEntries.add(entry); } else if (Note.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) { // Build note entries entry.uri = null; entry.maxLines = 10; mOtherEntries.add(entry); } else { // Handle showing custom rows entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri); // Use social summary when requested by external source final DataStatus status = mStatuses.get(entry.id); final boolean hasSocial = kind.actionBodySocial && status != null; if (hasSocial) { entry.applyStatus(status, true); } if (hasSocial || hasData) { mOtherEntries.add(entry); } } } } } }
private final void buildEntries() { // Clear out the old entries final int numSections = mSections.size(); for (int i = 0; i < numSections; i++) { mSections.get(i).clear(); } mRawContactIds.clear(); mReadOnlySourcesCnt = 0; mWritableSourcesCnt = 0; mWritableRawContactIds.clear(); final Context context = this; final Sources sources = Sources.getInstance(context); // Build up method entries if (mLookupUri != null) { for (Entity entity: mEntities) { final ContentValues entValues = entity.getEntityValues(); final String accountType = entValues.getAsString(RawContacts.ACCOUNT_TYPE); final long rawContactId = entValues.getAsLong(RawContacts._ID); if (!mRawContactIds.contains(rawContactId)) { mRawContactIds.add(rawContactId); } ContactsSource contactsSource = sources.getInflatedSource(accountType, ContactsSource.LEVEL_SUMMARY); if (contactsSource != null && contactsSource.readOnly) { mReadOnlySourcesCnt += 1; } else { mWritableSourcesCnt += 1; mWritableRawContactIds.add(rawContactId); } for (NamedContentValues subValue : entity.getSubValues()) { final ContentValues entryValues = subValue.values; entryValues.put(Data.RAW_CONTACT_ID, rawContactId); final long dataId = entryValues.getAsLong(Data._ID); final String mimeType = entryValues.getAsString(Data.MIMETYPE); if (mimeType == null) continue; final DataKind kind = sources.getKindOrFallback(accountType, mimeType, this, ContactsSource.LEVEL_MIMETYPES); if (kind == null) continue; final ViewEntry entry = ViewEntry.fromValues(context, mimeType, kind, rawContactId, dataId, entryValues); final boolean hasData = !TextUtils.isEmpty(entry.data); final boolean isSuperPrimary = entryValues.getAsInteger( Data.IS_SUPER_PRIMARY) != 0; if (Phone.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) { // Build phone entries mNumPhoneNumbers++; entry.intent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts(Constants.SCHEME_TEL, entry.data, null)); entry.secondaryIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(Constants.SCHEME_SMSTO, entry.data, null)); entry.isPrimary = isSuperPrimary; mPhoneEntries.add(entry); if (entry.type == CommonDataKinds.Phone.TYPE_MOBILE || mShowSmsLinksForAllPhones) { // Add an SMS entry if (kind.iconAltRes > 0) { entry.secondaryActionIcon = kind.iconAltRes; } } } else if (Email.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) { // Build email entries entry.intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(Constants.SCHEME_MAILTO, entry.data, null)); entry.isPrimary = isSuperPrimary; mEmailEntries.add(entry); // When Email rows have status, create additional Im row final DataStatus status = mStatuses.get(entry.id); if (status != null) { final String imMime = Im.CONTENT_ITEM_TYPE; final DataKind imKind = sources.getKindOrFallback(accountType, imMime, this, ContactsSource.LEVEL_MIMETYPES); final ViewEntry imEntry = ViewEntry.fromValues(context, imMime, imKind, rawContactId, dataId, entryValues); imEntry.intent = ContactsUtils.buildImIntent(entryValues); imEntry.applyStatus(status, false); mImEntries.add(imEntry); } } else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) { // Build postal entries entry.maxLines = 4; entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri); mPostalEntries.add(entry); } else if (Im.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) { // Build IM entries entry.intent = ContactsUtils.buildImIntent(entryValues); if (TextUtils.isEmpty(entry.label)) { entry.label = getString(R.string.chat).toLowerCase(); } // Apply presence and status details when available final DataStatus status = mStatuses.get(entry.id); if (status != null) { entry.applyStatus(status, false); } mImEntries.add(entry); } else if ((Organization.CONTENT_ITEM_TYPE.equals(mimeType) || Nickname.CONTENT_ITEM_TYPE.equals(mimeType)) && hasData) { // Build organization and note entries entry.uri = null; mOrganizationEntries.add(entry); } else if (Note.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) { // Build note entries entry.uri = null; entry.maxLines = 10; mOtherEntries.add(entry); } else { // Handle showing custom rows entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri); // Use social summary when requested by external source final DataStatus status = mStatuses.get(entry.id); final boolean hasSocial = kind.actionBodySocial && status != null; if (hasSocial) { entry.applyStatus(status, true); } if (hasSocial || hasData) { mOtherEntries.add(entry); } } } } } }
diff --git a/src/com/mebigfatguy/polycasso/URLFetcher.java b/src/com/mebigfatguy/polycasso/URLFetcher.java index 8befee0..41248bb 100644 --- a/src/com/mebigfatguy/polycasso/URLFetcher.java +++ b/src/com/mebigfatguy/polycasso/URLFetcher.java @@ -1,91 +1,91 @@ /* * polycasso - Cubism Artwork generator * Copyright 2009-2011 MeBigFatGuy.com * Copyright 2009-2011 Dave Brosius * Inspired by work by Roger Alsing * * 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.mebigfatguy.polycasso; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.Proxy.Type; import java.net.URL; import org.apache.commons.io.IOUtils; /** * manages downloading data from a url */ public class URLFetcher { /** * private to avoid construction of this static access only class */ private URLFetcher() { } /** * retrieve arbitrary data found at a specific url * - either http or file urls * for http requests, sets the user-agent to mozilla to avoid * sites being cranky about a java sniffer * * @param url the url to retrieve * @param proxyHost the host to use for the proxy * @param proxyPort the port to use for the proxy * @return a byte array of the content * * @throws IOException the site fails to respond */ public static byte[] fetchURLData(String url, String proxyHost, int proxyPort) throws IOException { HttpURLConnection con = null; InputStream is = null; try { URL u = new URL(url); if (url.startsWith("file://")) { is = new BufferedInputStream(u.openStream()); } else { Proxy proxy; if (proxyHost != null) { proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); } else { - proxy = new Proxy(Type.DIRECT, null); + proxy = Proxy.NO_PROXY; } con = (HttpURLConnection)u.openConnection(proxy); con.addRequestProperty("User-Agent", "Mozilla/4.76"); con.setDoInput(true); con.setDoOutput(false); con.connect(); is = new BufferedInputStream(con.getInputStream()); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); return baos.toByteArray(); } finally { IOUtils.closeQuietly(is); if (con != null) { con.disconnect(); } } } }
true
true
public static byte[] fetchURLData(String url, String proxyHost, int proxyPort) throws IOException { HttpURLConnection con = null; InputStream is = null; try { URL u = new URL(url); if (url.startsWith("file://")) { is = new BufferedInputStream(u.openStream()); } else { Proxy proxy; if (proxyHost != null) { proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); } else { proxy = new Proxy(Type.DIRECT, null); } con = (HttpURLConnection)u.openConnection(proxy); con.addRequestProperty("User-Agent", "Mozilla/4.76"); con.setDoInput(true); con.setDoOutput(false); con.connect(); is = new BufferedInputStream(con.getInputStream()); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); return baos.toByteArray(); } finally { IOUtils.closeQuietly(is); if (con != null) { con.disconnect(); } } }
public static byte[] fetchURLData(String url, String proxyHost, int proxyPort) throws IOException { HttpURLConnection con = null; InputStream is = null; try { URL u = new URL(url); if (url.startsWith("file://")) { is = new BufferedInputStream(u.openStream()); } else { Proxy proxy; if (proxyHost != null) { proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); } else { proxy = Proxy.NO_PROXY; } con = (HttpURLConnection)u.openConnection(proxy); con.addRequestProperty("User-Agent", "Mozilla/4.76"); con.setDoInput(true); con.setDoOutput(false); con.connect(); is = new BufferedInputStream(con.getInputStream()); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); return baos.toByteArray(); } finally { IOUtils.closeQuietly(is); if (con != null) { con.disconnect(); } } }
diff --git a/search-impl/src/main/java/org/cytoscape/search/internal/EnhancedSearchIndex.java b/search-impl/src/main/java/org/cytoscape/search/internal/EnhancedSearchIndex.java index e37ee1e6e..2028135b7 100644 --- a/search-impl/src/main/java/org/cytoscape/search/internal/EnhancedSearchIndex.java +++ b/search-impl/src/main/java/org/cytoscape/search/internal/EnhancedSearchIndex.java @@ -1,165 +1,167 @@ /* Copyright (c) 2006, 2007, 2010, 2011, The Cytoscape Consortium (www.cytoscape.org) 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. The software and documentation provided hereunder is on an "as is" basis, and the Institute for Systems Biology and the Whitehead Institute have no obligations to provide maintenance, support, updates, enhancements or modifications. In no event shall the Institute for Systems Biology and the Whitehead Institute be liable to any party for direct, indirect, special, incidental or consequential damages, including lost profits, arising out of the use of this software and its documentation, even if the Institute for Systems Biology and the Whitehead Institute have been advised of the possibility of such damage. 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 org.cytoscape.search.internal; import java.io.IOException; import java.util.List; import java.util.Set; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.NumericField; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.util.Version; import org.cytoscape.model.CyEdge; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyNode; import org.cytoscape.model.CyRow; import org.cytoscape.model.CyTable; import org.cytoscape.model.CyTableEntry; import org.cytoscape.model.CyTableUtil; import org.cytoscape.search.internal.util.EnhancedSearchUtils; public class EnhancedSearchIndex { RAMDirectory idx; // Index the given network public EnhancedSearchIndex(final CyNetwork network) { if(network == null) throw new NullPointerException("Network is null."); // Construct a RAMDirectory to hold the in-memory representation of the index. idx = new RAMDirectory(); BuildIndex(idx, network); } private void BuildIndex(RAMDirectory idx, CyNetwork network) { try { // Make a writer to create the index IndexWriter writer = new IndexWriter(idx, new StandardAnalyzer(Version.LUCENE_30), IndexWriter.MaxFieldLength.UNLIMITED); // Add a document for each graph object - node and edge List<CyNode> nodeList = network.getNodeList(); for (CyNode cyNode : nodeList) { writer.addDocument(createDocument(network, cyNode, EnhancedSearch.NODE_TYPE, cyNode.getIndex())); } List<CyEdge> edgeList = network.getEdgeList(); for (CyEdge cyEdge : edgeList) { writer.addDocument(createDocument(network, cyEdge, EnhancedSearch.EDGE_TYPE, cyEdge.getIndex())); } // Optimize and close the writer to finish building the index writer.optimize(); writer.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } /** * Make a Document object with an un-indexed identifier field and indexed * attribute fields */ private static Document createDocument(CyNetwork network, CyTableEntry graphObject, String graphObjectType, int index) { Document doc = new Document(); String identifier = Integer.toString(index); doc.add(new Field(EnhancedSearch.INDEX_FIELD, identifier, Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field(EnhancedSearch.TYPE_FIELD, graphObjectType, Field.Store.YES, Field.Index.ANALYZED)); CyRow cyRow = network.getRow(graphObject); CyTable cyDataTable = cyRow.getTable(); Set<String> attributeNames = CyTableUtil.getColumnNames(cyDataTable); for (final String attrName : attributeNames) { // Handle whitespace characters and case in attribute names String attrIndexingName = EnhancedSearchUtils.replaceWhitespace(attrName); attrIndexingName = attrIndexingName.toLowerCase(); // Determine type Class<?> valueType = cyDataTable.getColumn(attrName).getType(); if (valueType == String.class) { String attrValue = network.getRow(graphObject).get(attrName, String.class); if (attrValue == null){ continue; } doc.add(new Field(attrIndexingName, attrValue, Field.Store.YES, Field.Index.ANALYZED)); } else if (valueType == Integer.class) { if (network.getRow(graphObject).get(attrName, Integer.class) == null){ continue; } int attrValue = network.getRow(graphObject).get(attrName, Integer.class); NumericField field = new NumericField(attrIndexingName); field.setIntValue(attrValue); doc.add(field); } else if (valueType == Double.class) { if (network.getRow(graphObject).get(attrName, Double.class) == null){ continue; } double attrValue = network.getRow(graphObject).get(attrName, Double.class); NumericField field = new NumericField(attrIndexingName); field.setDoubleValue(attrValue); doc.add(field); } else if (valueType == Boolean.class) { - String attrValue = network.getRow(graphObject).get(attrName, Boolean.class).toString(); - doc.add(new Field(attrIndexingName, attrValue, Field.Store.YES, Field.Index.ANALYZED)); + if (network.getRow(graphObject).get(attrName, Boolean.class) != null){ + String attrValue = network.getRow(graphObject).get(attrName, Boolean.class).toString(); + doc.add(new Field(attrIndexingName, attrValue, Field.Store.YES, Field.Index.ANALYZED)); + } } else if (valueType == List.class) { List attrValueList = network.getRow(graphObject).get(attrName, List.class); if (attrValueList != null) { for (int j = 0; j < attrValueList.size(); j++) { String attrValue = attrValueList.get(j).toString(); doc.add(new Field(attrIndexingName, attrValue, Field.Store.YES, Field.Index.ANALYZED)); } } } } return doc; } public RAMDirectory getIndex() { return idx; } }
true
true
private static Document createDocument(CyNetwork network, CyTableEntry graphObject, String graphObjectType, int index) { Document doc = new Document(); String identifier = Integer.toString(index); doc.add(new Field(EnhancedSearch.INDEX_FIELD, identifier, Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field(EnhancedSearch.TYPE_FIELD, graphObjectType, Field.Store.YES, Field.Index.ANALYZED)); CyRow cyRow = network.getRow(graphObject); CyTable cyDataTable = cyRow.getTable(); Set<String> attributeNames = CyTableUtil.getColumnNames(cyDataTable); for (final String attrName : attributeNames) { // Handle whitespace characters and case in attribute names String attrIndexingName = EnhancedSearchUtils.replaceWhitespace(attrName); attrIndexingName = attrIndexingName.toLowerCase(); // Determine type Class<?> valueType = cyDataTable.getColumn(attrName).getType(); if (valueType == String.class) { String attrValue = network.getRow(graphObject).get(attrName, String.class); if (attrValue == null){ continue; } doc.add(new Field(attrIndexingName, attrValue, Field.Store.YES, Field.Index.ANALYZED)); } else if (valueType == Integer.class) { if (network.getRow(graphObject).get(attrName, Integer.class) == null){ continue; } int attrValue = network.getRow(graphObject).get(attrName, Integer.class); NumericField field = new NumericField(attrIndexingName); field.setIntValue(attrValue); doc.add(field); } else if (valueType == Double.class) { if (network.getRow(graphObject).get(attrName, Double.class) == null){ continue; } double attrValue = network.getRow(graphObject).get(attrName, Double.class); NumericField field = new NumericField(attrIndexingName); field.setDoubleValue(attrValue); doc.add(field); } else if (valueType == Boolean.class) { String attrValue = network.getRow(graphObject).get(attrName, Boolean.class).toString(); doc.add(new Field(attrIndexingName, attrValue, Field.Store.YES, Field.Index.ANALYZED)); } else if (valueType == List.class) { List attrValueList = network.getRow(graphObject).get(attrName, List.class); if (attrValueList != null) { for (int j = 0; j < attrValueList.size(); j++) { String attrValue = attrValueList.get(j).toString(); doc.add(new Field(attrIndexingName, attrValue, Field.Store.YES, Field.Index.ANALYZED)); } } } } return doc; }
private static Document createDocument(CyNetwork network, CyTableEntry graphObject, String graphObjectType, int index) { Document doc = new Document(); String identifier = Integer.toString(index); doc.add(new Field(EnhancedSearch.INDEX_FIELD, identifier, Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field(EnhancedSearch.TYPE_FIELD, graphObjectType, Field.Store.YES, Field.Index.ANALYZED)); CyRow cyRow = network.getRow(graphObject); CyTable cyDataTable = cyRow.getTable(); Set<String> attributeNames = CyTableUtil.getColumnNames(cyDataTable); for (final String attrName : attributeNames) { // Handle whitespace characters and case in attribute names String attrIndexingName = EnhancedSearchUtils.replaceWhitespace(attrName); attrIndexingName = attrIndexingName.toLowerCase(); // Determine type Class<?> valueType = cyDataTable.getColumn(attrName).getType(); if (valueType == String.class) { String attrValue = network.getRow(graphObject).get(attrName, String.class); if (attrValue == null){ continue; } doc.add(new Field(attrIndexingName, attrValue, Field.Store.YES, Field.Index.ANALYZED)); } else if (valueType == Integer.class) { if (network.getRow(graphObject).get(attrName, Integer.class) == null){ continue; } int attrValue = network.getRow(graphObject).get(attrName, Integer.class); NumericField field = new NumericField(attrIndexingName); field.setIntValue(attrValue); doc.add(field); } else if (valueType == Double.class) { if (network.getRow(graphObject).get(attrName, Double.class) == null){ continue; } double attrValue = network.getRow(graphObject).get(attrName, Double.class); NumericField field = new NumericField(attrIndexingName); field.setDoubleValue(attrValue); doc.add(field); } else if (valueType == Boolean.class) { if (network.getRow(graphObject).get(attrName, Boolean.class) != null){ String attrValue = network.getRow(graphObject).get(attrName, Boolean.class).toString(); doc.add(new Field(attrIndexingName, attrValue, Field.Store.YES, Field.Index.ANALYZED)); } } else if (valueType == List.class) { List attrValueList = network.getRow(graphObject).get(attrName, List.class); if (attrValueList != null) { for (int j = 0; j < attrValueList.size(); j++) { String attrValue = attrValueList.get(j).toString(); doc.add(new Field(attrIndexingName, attrValue, Field.Store.YES, Field.Index.ANALYZED)); } } } } return doc; }
diff --git a/src/org/intellij/plugins/ceylon/ide/annotator/TypeCheckerProvider.java b/src/org/intellij/plugins/ceylon/ide/annotator/TypeCheckerProvider.java index 57556064..882aab87 100644 --- a/src/org/intellij/plugins/ceylon/ide/annotator/TypeCheckerProvider.java +++ b/src/org/intellij/plugins/ceylon/ide/annotator/TypeCheckerProvider.java @@ -1,162 +1,163 @@ package org.intellij.plugins.ceylon.ide.annotator; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.facet.FacetManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleComponent; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.vfs.VirtualFile; import com.redhat.ceylon.cmr.api.RepositoryManager; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleSourceMapper; import com.redhat.ceylon.compiler.typechecker.context.Context; import com.redhat.ceylon.compiler.typechecker.util.ModuleManagerFactory; import com.redhat.ceylon.ide.common.CeylonProject; import com.redhat.ceylon.ide.common.CeylonProjectConfig; import com.redhat.ceylon.model.loader.model.LazyModule; import com.redhat.ceylon.model.typechecker.model.ModuleImport; import com.redhat.ceylon.model.typechecker.util.ModuleManager; import org.intellij.plugins.ceylon.ide.IdePluginCeylonStartup; import org.intellij.plugins.ceylon.ide.ceylonCode.model.IdeaCeylonProjects; import org.intellij.plugins.ceylon.ide.facet.CeylonFacet; import org.jetbrains.annotations.NotNull; import java.io.File; import static com.redhat.ceylon.cmr.ceylon.CeylonUtils.repoManager; /** * */ public class TypeCheckerProvider implements ModuleComponent { private final Module module; private TypeChecker typeChecker; public TypeCheckerProvider(Module module) { this.module = module; } public void initComponent() { } public TypeChecker getTypeChecker() { return typeChecker; } public void disposeComponent() { } @NotNull public String getComponentName() { return "TypeCheckerProvider"; } public void projectOpened() { if (FacetManager.getInstance(module).getFacetByType(CeylonFacet.ID) == null) { return; } // If the project was just created, module files (*.iml) do not yet exist. Since we need them, we defer // the type checker creation after the project has been loaded StartupManager.getInstance(module.getProject()).registerPostStartupActivity(new Runnable() { @Override public void run() { typecheck(); } }); } public void typecheck() { if (typeChecker == null) { typeChecker = createTypeChecker(); } DaemonCodeAnalyzer.getInstance(module.getProject()).restart(); } public void projectClosed() { // called when project is being closed typeChecker = null; } @Override public void moduleAdded() { System.out.println("TypeCheckerprovider.moduleAdded()"); } public TypeChecker createTypeChecker() { IdeaCeylonProjects ceylonModel = module.getProject().getComponent(IdeaCeylonProjects.class); CeylonProject<Module> ceylonProject = ceylonModel.getProject(module); CeylonProjectConfig<Module> ceylonConfig = ceylonProject.getConfiguration(); TypeCheckerBuilder builder = new TypeCheckerBuilder() .verbose(false) .usageWarnings(true); String systemRepo = IdePluginCeylonStartup.getEmbeddedCeylonRepository().getAbsolutePath(); if (systemRepo == null) { - systemRepo = ceylonConfig.getProjectRepositories().getSystemRepoDir().getAbsolutePath(); + // FIXME retrieve CeylonFacetState.systemRepository and interpolate variables +// systemRepo = ceylonConfig.getProjectRepositories().getSystemRepoDir().getAbsolutePath(); } boolean offline = ceylonConfig.getOffline(); File cwd = ceylonConfig.getProject().getRootDirectory(); RepositoryManager repositoryManager = repoManager() .offline(offline) .cwd(cwd) .systemRepo(systemRepo) // .extraUserRepos(getReferencedProjectsOutputRepositories(project)) // .logger(new EclipseLogger()) .isJDKIncluded(true) .buildManager(); builder.setRepositoryManager(repositoryManager); builder.moduleManagerFactory(new ModuleManagerFactory() { @Override public ModuleManager createModuleManager(final Context context) { // FIXME use a real LazyModuleManager to remove this hack return new ModuleManager() { @Override public void addImplicitImports() { com.redhat.ceylon.model.typechecker.model.Module languageModule = getModules().getLanguageModule(); for (com.redhat.ceylon.model.typechecker.model.Module m : getModules().getListOfModules()) { // Java modules don't depend on ceylon.language if ((!(m instanceof LazyModule) || !m.isJava()) && !m.equals(languageModule)) { // add ceylon.language if required ModuleImport moduleImport = findImport(m, languageModule); if (moduleImport == null) { moduleImport = new ModuleImport(languageModule, false, true); m.addImport(moduleImport); } } } } }; } @Override public ModuleSourceMapper createModuleManagerUtil(Context context, ModuleManager moduleManager) { return new ModuleSourceMapper(context, moduleManager); } }); for (VirtualFile sourceRoot : ModuleRootManager.getInstance(module).getSourceRoots()) { builder.addSrcDirectory(VFileAdapter.createInstance(sourceRoot)); } long startTime = System.currentTimeMillis(); System.out.println("Getting type checker"); TypeChecker checker = builder.getTypeChecker(); System.out.println("Got type checker in " + (System.currentTimeMillis() - startTime) + "ms"); startTime = System.currentTimeMillis(); checker.process(); System.out.println("Type checker process()ed in " + (System.currentTimeMillis() - startTime) + "ms"); return checker; } }
true
true
public TypeChecker createTypeChecker() { IdeaCeylonProjects ceylonModel = module.getProject().getComponent(IdeaCeylonProjects.class); CeylonProject<Module> ceylonProject = ceylonModel.getProject(module); CeylonProjectConfig<Module> ceylonConfig = ceylonProject.getConfiguration(); TypeCheckerBuilder builder = new TypeCheckerBuilder() .verbose(false) .usageWarnings(true); String systemRepo = IdePluginCeylonStartup.getEmbeddedCeylonRepository().getAbsolutePath(); if (systemRepo == null) { systemRepo = ceylonConfig.getProjectRepositories().getSystemRepoDir().getAbsolutePath(); } boolean offline = ceylonConfig.getOffline(); File cwd = ceylonConfig.getProject().getRootDirectory(); RepositoryManager repositoryManager = repoManager() .offline(offline) .cwd(cwd) .systemRepo(systemRepo) // .extraUserRepos(getReferencedProjectsOutputRepositories(project)) // .logger(new EclipseLogger()) .isJDKIncluded(true) .buildManager(); builder.setRepositoryManager(repositoryManager); builder.moduleManagerFactory(new ModuleManagerFactory() { @Override public ModuleManager createModuleManager(final Context context) { // FIXME use a real LazyModuleManager to remove this hack return new ModuleManager() { @Override public void addImplicitImports() { com.redhat.ceylon.model.typechecker.model.Module languageModule = getModules().getLanguageModule(); for (com.redhat.ceylon.model.typechecker.model.Module m : getModules().getListOfModules()) { // Java modules don't depend on ceylon.language if ((!(m instanceof LazyModule) || !m.isJava()) && !m.equals(languageModule)) { // add ceylon.language if required ModuleImport moduleImport = findImport(m, languageModule); if (moduleImport == null) { moduleImport = new ModuleImport(languageModule, false, true); m.addImport(moduleImport); } } } } }; } @Override public ModuleSourceMapper createModuleManagerUtil(Context context, ModuleManager moduleManager) { return new ModuleSourceMapper(context, moduleManager); } }); for (VirtualFile sourceRoot : ModuleRootManager.getInstance(module).getSourceRoots()) { builder.addSrcDirectory(VFileAdapter.createInstance(sourceRoot)); } long startTime = System.currentTimeMillis(); System.out.println("Getting type checker"); TypeChecker checker = builder.getTypeChecker(); System.out.println("Got type checker in " + (System.currentTimeMillis() - startTime) + "ms"); startTime = System.currentTimeMillis(); checker.process(); System.out.println("Type checker process()ed in " + (System.currentTimeMillis() - startTime) + "ms"); return checker; }
public TypeChecker createTypeChecker() { IdeaCeylonProjects ceylonModel = module.getProject().getComponent(IdeaCeylonProjects.class); CeylonProject<Module> ceylonProject = ceylonModel.getProject(module); CeylonProjectConfig<Module> ceylonConfig = ceylonProject.getConfiguration(); TypeCheckerBuilder builder = new TypeCheckerBuilder() .verbose(false) .usageWarnings(true); String systemRepo = IdePluginCeylonStartup.getEmbeddedCeylonRepository().getAbsolutePath(); if (systemRepo == null) { // FIXME retrieve CeylonFacetState.systemRepository and interpolate variables // systemRepo = ceylonConfig.getProjectRepositories().getSystemRepoDir().getAbsolutePath(); } boolean offline = ceylonConfig.getOffline(); File cwd = ceylonConfig.getProject().getRootDirectory(); RepositoryManager repositoryManager = repoManager() .offline(offline) .cwd(cwd) .systemRepo(systemRepo) // .extraUserRepos(getReferencedProjectsOutputRepositories(project)) // .logger(new EclipseLogger()) .isJDKIncluded(true) .buildManager(); builder.setRepositoryManager(repositoryManager); builder.moduleManagerFactory(new ModuleManagerFactory() { @Override public ModuleManager createModuleManager(final Context context) { // FIXME use a real LazyModuleManager to remove this hack return new ModuleManager() { @Override public void addImplicitImports() { com.redhat.ceylon.model.typechecker.model.Module languageModule = getModules().getLanguageModule(); for (com.redhat.ceylon.model.typechecker.model.Module m : getModules().getListOfModules()) { // Java modules don't depend on ceylon.language if ((!(m instanceof LazyModule) || !m.isJava()) && !m.equals(languageModule)) { // add ceylon.language if required ModuleImport moduleImport = findImport(m, languageModule); if (moduleImport == null) { moduleImport = new ModuleImport(languageModule, false, true); m.addImport(moduleImport); } } } } }; } @Override public ModuleSourceMapper createModuleManagerUtil(Context context, ModuleManager moduleManager) { return new ModuleSourceMapper(context, moduleManager); } }); for (VirtualFile sourceRoot : ModuleRootManager.getInstance(module).getSourceRoots()) { builder.addSrcDirectory(VFileAdapter.createInstance(sourceRoot)); } long startTime = System.currentTimeMillis(); System.out.println("Getting type checker"); TypeChecker checker = builder.getTypeChecker(); System.out.println("Got type checker in " + (System.currentTimeMillis() - startTime) + "ms"); startTime = System.currentTimeMillis(); checker.process(); System.out.println("Type checker process()ed in " + (System.currentTimeMillis() - startTime) + "ms"); return checker; }
diff --git a/src/share/classes/com/sun/javafx/runtime/util/StringLocalization.java b/src/share/classes/com/sun/javafx/runtime/util/StringLocalization.java index a24ef8da0..3468543d7 100644 --- a/src/share/classes/com/sun/javafx/runtime/util/StringLocalization.java +++ b/src/share/classes/com/sun/javafx/runtime/util/StringLocalization.java @@ -1,117 +1,118 @@ /* * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.javafx.runtime.util; import java.util.Collections; import java.util.Map; import java.util.Locale; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import com.sun.javafx.runtime.util.backport.ResourceBundle; public class StringLocalization { private static final Map<ThreadGroup, Map<String, String>> map = Collections.synchronizedMap( new WeakHashMap<ThreadGroup, Map<String, String>>()); public static String getLocalizedString(String scriptName, String explicitKey, String literal, Object... embeddedExpr) { return getLocalizedString( getPropertiesName(scriptName.replaceAll("/", "\\.")), explicitKey, literal, Locale.getDefault(), embeddedExpr); } public static String getLocalizedString(String propertiesName, String explicitKey, String literal, Locale locale, Object... embeddedExpr) { String localization = literal; try { ResourceBundle rb = ResourceBundle.getBundle(propertiesName, locale, FXPropertyResourceBundle.FXPropertiesControl.INSTANCE); if (explicitKey.length() != 0) { localization = rb.getString(explicitKey); - if (explicitKey.equals(localization)) { + if (explicitKey.equals(localization) && + !rb.keySet().contains(explicitKey)) { localization = literal; } } else { localization = rb.getString(literal.replaceAll("\r\n|\r|\n", "\n")); } if (embeddedExpr.length != 0) { localization = String.format(localization, embeddedExpr); } } catch (Exception e) { e.printStackTrace(); } return localization; } public static void associate(String source, String properties) { Map<String, String> assoc = getAssociation(); if (properties != null) { assoc.put(source, properties); } else { assoc.remove(source); } } public static String getPropertiesName(String scriptName) { String propertiesName = scriptName; Map<String, String> assoc = getAssociation(); while (true) { if (assoc.containsKey(scriptName)) { propertiesName = assoc.get(scriptName); break; } else { int lastDot = scriptName.lastIndexOf('.'); if (lastDot != -1) { scriptName = scriptName.substring(0, lastDot); } else { break; } } } return propertiesName; } private static Map<String, String> getAssociation() { ThreadGroup tg = Thread.currentThread().getThreadGroup(); Map<String, String> assoc = map.get(tg); if (assoc == null) { assoc = new ConcurrentHashMap<String, String>(); map.put(tg, assoc); } return assoc; } }
true
true
public static String getLocalizedString(String propertiesName, String explicitKey, String literal, Locale locale, Object... embeddedExpr) { String localization = literal; try { ResourceBundle rb = ResourceBundle.getBundle(propertiesName, locale, FXPropertyResourceBundle.FXPropertiesControl.INSTANCE); if (explicitKey.length() != 0) { localization = rb.getString(explicitKey); if (explicitKey.equals(localization)) { localization = literal; } } else { localization = rb.getString(literal.replaceAll("\r\n|\r|\n", "\n")); } if (embeddedExpr.length != 0) { localization = String.format(localization, embeddedExpr); } } catch (Exception e) { e.printStackTrace(); } return localization; }
public static String getLocalizedString(String propertiesName, String explicitKey, String literal, Locale locale, Object... embeddedExpr) { String localization = literal; try { ResourceBundle rb = ResourceBundle.getBundle(propertiesName, locale, FXPropertyResourceBundle.FXPropertiesControl.INSTANCE); if (explicitKey.length() != 0) { localization = rb.getString(explicitKey); if (explicitKey.equals(localization) && !rb.keySet().contains(explicitKey)) { localization = literal; } } else { localization = rb.getString(literal.replaceAll("\r\n|\r|\n", "\n")); } if (embeddedExpr.length != 0) { localization = String.format(localization, embeddedExpr); } } catch (Exception e) { e.printStackTrace(); } return localization; }
diff --git a/search/src/java/cz/incad/Kramerius/views/inc/MenuButtonsViewObject.java b/search/src/java/cz/incad/Kramerius/views/inc/MenuButtonsViewObject.java index 984bcfcb8..5404d6e24 100644 --- a/search/src/java/cz/incad/Kramerius/views/inc/MenuButtonsViewObject.java +++ b/search/src/java/cz/incad/Kramerius/views/inc/MenuButtonsViewObject.java @@ -1,119 +1,119 @@ /* * Copyright (C) 2010 Pavel Stastny * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cz.incad.Kramerius.views.inc; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import javax.servlet.http.HttpServletRequest; import com.google.inject.Inject; import com.google.inject.Provider; import cz.incad.kramerius.shib.utils.ShibbolethUtils; import cz.incad.kramerius.utils.ApplicationURL; import cz.incad.kramerius.utils.conf.KConfiguration; public class MenuButtonsViewObject { @Inject Provider<HttpServletRequest> requestProvider; @Inject KConfiguration kConfiguration; String[] getConfigredItems() { String[] langs = kConfiguration.getPropertyList("interface.languages"); return langs; } public String getQueryString() { HttpServletRequest request = this.requestProvider.get(); if (request.getQueryString() != null) return request.getQueryString(); else return ""; } public String getShibbLogout() { HttpServletRequest req = this.requestProvider.get(); if (ShibbolethUtils.isUnderShibbolethSession(req)) { String property = KConfiguration.getInstance().getProperty("security.shib.logout"); return property; } return null; } public List<LanguageItem> getLanguageItems() { String[] items = getConfigredItems(); List<LanguageItem> links = new ArrayList<LanguageItem>(); StringBuffer buffer = new StringBuffer(); String queryString = getQueryString(); StringTokenizer tokenizer = new StringTokenizer(queryString,"&"); while(tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (!token.trim().startsWith("language")) { if (buffer.length() > 0) { buffer.append("&"); } buffer.append(token); } } for (int i = 0; i < items.length; i++) { String name = items[i]; - String link = "" + "?language="+ items[++i] + "&" + buffer.toString() ; + String link = "?language="+ items[++i] + "&" + buffer.toString() ; LanguageItem itm = new LanguageItem(link, name, items[i]); links.add(itm); } return links; } public static class LanguageItem { private String link; private String name; private String key; private LanguageItem(String link, String name, String key) { super(); this.link = link; this.name = name; this.key = key; } public String getLink() { return link; } public String getName() { return name; } public String getKey(){ return this.key; } } }
true
true
public List<LanguageItem> getLanguageItems() { String[] items = getConfigredItems(); List<LanguageItem> links = new ArrayList<LanguageItem>(); StringBuffer buffer = new StringBuffer(); String queryString = getQueryString(); StringTokenizer tokenizer = new StringTokenizer(queryString,"&"); while(tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (!token.trim().startsWith("language")) { if (buffer.length() > 0) { buffer.append("&"); } buffer.append(token); } } for (int i = 0; i < items.length; i++) { String name = items[i]; String link = "" + "?language="+ items[++i] + "&" + buffer.toString() ; LanguageItem itm = new LanguageItem(link, name, items[i]); links.add(itm); } return links; }
public List<LanguageItem> getLanguageItems() { String[] items = getConfigredItems(); List<LanguageItem> links = new ArrayList<LanguageItem>(); StringBuffer buffer = new StringBuffer(); String queryString = getQueryString(); StringTokenizer tokenizer = new StringTokenizer(queryString,"&"); while(tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (!token.trim().startsWith("language")) { if (buffer.length() > 0) { buffer.append("&"); } buffer.append(token); } } for (int i = 0; i < items.length; i++) { String name = items[i]; String link = "?language="+ items[++i] + "&" + buffer.toString() ; LanguageItem itm = new LanguageItem(link, name, items[i]); links.add(itm); } return links; }
diff --git a/src/main/java/org/diyefi/openlogviewer/graphing/EntireGraphingPanel.java b/src/main/java/org/diyefi/openlogviewer/graphing/EntireGraphingPanel.java index 1f44312..952c2c7 100644 --- a/src/main/java/org/diyefi/openlogviewer/graphing/EntireGraphingPanel.java +++ b/src/main/java/org/diyefi/openlogviewer/graphing/EntireGraphingPanel.java @@ -1,877 +1,878 @@ /* OpenLogViewer * * Copyright 2011 * * This file is part of the OpenLogViewer project. * * OpenLogViewer software 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. * * OpenLogViewer 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with any OpenLogViewer software. If not, see http://www.gnu.org/licenses/ * * I ask that if you make any changes to this file you fork the code on github.com! * */ package org.diyefi.openlogviewer.graphing; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.event.WindowEvent; import javax.swing.JPanel; import javax.swing.Timer; import org.diyefi.openlogviewer.OpenLogViewer; import org.diyefi.openlogviewer.genericlog.GenericLog; public class EntireGraphingPanel extends JPanel implements ActionListener, MouseMotionListener, MouseListener, MouseWheelListener, KeyListener, ComponentListener { private static final long serialVersionUID = 1L; private static final int BASE_PLAY_SPEED = 10; private static final double COARSE_MOVEMENT_PERCENTAGE = 0.50; public static final int LEFT_OFFSCREEN_POINTS_ZOOMED_IN = 0; public static final int RIGHT_OFFSCREEN_POINTS_ZOOMED_IN = 3; public static final int LEFT_OFFSCREEN_POINTS_ZOOMED_OUT = 2; public static final int RIGHT_OFFSCREEN_POINTS_ZOOMED_OUT = 2; private final MultiGraphLayeredPane multiGraph; private final GraphPositionPanel graphPositionPanel; private double graphPosition; private int graphSize; private boolean playing; private boolean wasPlaying; private final Timer playTimer; private final Timer flingTimer; private boolean dragging; private boolean flinging; private long thePastMouseDragged; private long thePastLeftArrow; private long thePastRightArrow; private int scrollAcceleration; private int prevDragXCoord; private int flingInertia; private int zoom; private boolean zoomedOutBeyondOneToOne; private int oldComponentWidth; public EntireGraphingPanel() { setName("graphinPanel"); setLayout(new BorderLayout()); multiGraph = new MultiGraphLayeredPane(); multiGraph.setPreferredSize(new Dimension(600, 400)); add(multiGraph, BorderLayout.CENTER); graphPositionPanel = new GraphPositionPanel(); graphPositionPanel.setPreferredSize(new Dimension(600, 20)); add(graphPositionPanel, BorderLayout.SOUTH); zoom = 1; zoomedOutBeyondOneToOne = false; oldComponentWidth = this.getWidth(); resetGraphPosition(); setGraphSize(0); playing = false; wasPlaying = false; playTimer = new Timer(BASE_PLAY_SPEED, this); playTimer.setInitialDelay(0); flingTimer = new Timer(10, this); flingTimer.setInitialDelay(0); addMouseListener(this); addMouseMotionListener(this); addMouseWheelListener(this); addMouseListener(multiGraph.getInfoPanel()); addMouseMotionListener(multiGraph.getInfoPanel()); stopDragging(); stopFlinging(); thePastMouseDragged = System.currentTimeMillis(); thePastLeftArrow = System.currentTimeMillis(); thePastRightArrow = System.currentTimeMillis(); scrollAcceleration = 0; } public final void actionPerformed(final ActionEvent e) { //Play timer event fires if (e.getSource().equals(playTimer)) { if (playing) { if(graphPosition < getGraphPositionMax()){ if (zoomedOutBeyondOneToOne) { moveGraphPosition(zoom); } else { moveGraphPosition(1); } } else { pause(); } } } //Fling timer event fires if (e.getSource().equals(flingTimer)) { if ((flinging && graphPosition < getGraphPositionMax()) && (graphPosition > getGraphPositionMin())) { if (flingInertia == 0) { stopFlinging(); } else { moveEntireGraphingPanel(flingInertia); if (flingInertia > 0) { flingInertia--; } else if (flingInertia < 0) { flingInertia++; } else { stopFlinging(); } } } else { stopFlinging(); } } } public final MultiGraphLayeredPane getMultiGraphLayeredPane() { return multiGraph; } public final GraphPositionPanel getGraphPositionPanel() { return graphPositionPanel; } public final void setLog(final GenericLog genLog) { pause(); multiGraph.setLog(genLog); graphPositionPanel.setLog(genLog); } /** * The tightest the user should be allowed to zoom in. */ private int getTightestZoom() { return this.getWidth() - 1; } /** * The widest the user should be allowed to zoom out. */ private int getWidestZoom() { return ((graphSize + 1) / 2); } /** * Zoom in using steps larger the further away from 1:1 you are. * This assumes you are zooming in on the data centered in the screen. * If you need to zoom in on a different location then you must use * zoomIn() repeatedly coupled with a move each time. */ public final void zoomInCoarse() { final int zoomAmount = (int) Math.sqrt(zoom); for (int i = 0; i < zoomAmount; i++) { zoomIn(); } } /** * Zoom in by one. This control zooms finer than the coarse zoom control. * This assumes you are zooming in on the data centered in the screen. * If you need to zoom in on a different location then you must move * the graph accordingly. */ public final void zoomIn() { final double graphWidth = this.getWidth(); double move = 0; if (zoomedOutBeyondOneToOne) { if (zoom == 2) { zoomedOutBeyondOneToOne = false; } zoom--; move = graphWidth / (double) (zoom * 2); } else if (zoom < getTightestZoom()) { move = graphWidth / (double) (zoom * 2); zoom++; } moveEntireGraphingPanel(move); } /** * Zoom the graph to a 1:1 pixel-to-data-point ratio. */ public final void zoomResetRatio(){ if (zoomedOutBeyondOneToOne) { for (int i = zoom; i > 1; i--) { zoomIn(); } } else { for (int i = zoom; i > 1; i--) { zoomOut(); } } } /** * Zoom the graph so that if it is centered, then the * entire graph will fit within the display. Usually * this will result in ultimately zooming out, but if the * graph is small enough and/or the display is large enough * then zooming in will be more appropriate. * * If the graph will fit perfectly inside the display * then it will be sized down one more time so that * there is always at least 4 pixels of blank space to * the left and right of the graph so the user will * know they are seeing the entire graph trace. */ public void zoomGraphToFit(final int dataPointsToFit) { final int graphWindowWidth = this.getWidth() - 8; //Remove 4 pixels per side. int dataPointsThatFitInDisplay = 0; if (zoomedOutBeyondOneToOne) { dataPointsThatFitInDisplay = graphWindowWidth * zoom; } else { dataPointsThatFitInDisplay = graphWindowWidth / zoom; } // Zoom in until the data no longer fits in the display. while (dataPointsToFit < dataPointsThatFitInDisplay && zoom != getTightestZoom()) { zoomIn(); if (zoomedOutBeyondOneToOne) { dataPointsThatFitInDisplay = graphWindowWidth * zoom; } else { dataPointsThatFitInDisplay = graphWindowWidth / zoom; } } // Zoom out one or more times until the data just fits in the display. while (dataPointsToFit > dataPointsThatFitInDisplay && zoom != getWidestZoom()) { zoomOut(); if (zoomedOutBeyondOneToOne) { dataPointsThatFitInDisplay = graphWindowWidth * zoom; } else { dataPointsThatFitInDisplay = graphWindowWidth / zoom; } } } /** * Used by external sources that don't know or care about the size of the graph. */ public void zoomGraphToFit() { zoomGraphToFit(graphSize); } /** * Zoom out by one. This control zooms finer than the coarse zoom control. * This assumes you are zooming out from the data centered in the screen. * If you need to zoom out from a different location then you must move * the graph accordingly. */ public final void zoomOut() { final double graphWidth = this.getWidth(); double move = 0; if (!zoomedOutBeyondOneToOne) { if (zoom == 1) { zoomedOutBeyondOneToOne = true; zoom = 2; move = graphWidth / (double) (zoom * 2); } else { move = graphWidth / (double) (zoom * 2); zoom--; } } else if (zoom < getWidestZoom()) { zoom++; move = graphWidth / (double) (zoom * 2); } moveEntireGraphingPanel(-move); } /** * Zoom out using steps larger the further away from 1:1 you are. * This assumes you are zooming out with the data centered in the screen. * If you need to zoom out on a different location then you must use * zoomOut() repeatedly coupled with a move each time. */ public final void zoomOutCoarse() { final int zoomAmount = (int) Math.sqrt(zoom); for (int i = 0; i < zoomAmount; i++) { zoomOut(); } } public final boolean isZoomedOutBeyondOneToOne() { return zoomedOutBeyondOneToOne; } /** * Slows the speed of playback (exponentially) */ public final void slowDown() { final int currentDelay = playTimer.getDelay(); int newDelay = currentDelay + (currentDelay/6) + 1; if(newDelay > Integer.MAX_VALUE){ newDelay = Integer.MAX_VALUE; } playTimer.setDelay(newDelay); } /** * Resets the speed of playback to the original speed */ public final void resetPlaySpeed() { playTimer.setDelay(BASE_PLAY_SPEED); } public final void play() { if (playing) { pause(); } else { playing = true; playTimer.start(); } OpenLogViewer.getInstance().getNavBarPanel().updatePausePlayButton(); } public final void pause() { playing = false; playTimer.stop(); OpenLogViewer.getInstance().getNavBarPanel().updatePausePlayButton(); } /** * Increases the speed of the graph exponentially until the delay is zero, at which speed cannot be advanced any further and will essentially update as fast as possible. */ public final void speedUp() { final int currentDelay = playTimer.getDelay(); int newDelay = currentDelay - (currentDelay/6) - 1; if(newDelay < 0){ newDelay = 0; } playTimer.setDelay(newDelay); } public final void fling() { flinging = true; flingTimer.start(); } private double getGraphPositionMin() { double min = 0.0; if (zoomedOutBeyondOneToOne) { min = -((this.getWidth() - 1) * zoom); } else { min = -(((double) this.getWidth() - 1.0) / (double) zoom); } return min; } public final double getGraphPosition() { return graphPosition; } private int getGraphPositionMax() { if (zoom == getWidestZoom()) { int size = graphSize - (LEFT_OFFSCREEN_POINTS_ZOOMED_OUT * zoom); if (size < 0) { size = 0; } return size; } return graphSize; } public final void setGraphPosition(final double newPos) { graphPosition = newPos; repaint(); } /** * How many available data records we are dealing with. */ public final void setGraphSize(final int newGraphSize) { graphSize = newGraphSize; if (graphSize > 0) { zoomGraphToFit(graphSize); centerGraphPosition(0, graphSize); } } /** * Move the graph to the right so that only one valid * data point shows on the right-most part of the display. */ private void resetGraphPosition() { setGraphPosition(getGraphPositionMin()); } /** * Move the graph to the beginning with the first data point centered. */ public void moveToBeginning() { resetGraphPosition(); moveForwardPercentage(0.50); } /** * Move the graph backward a small amount (with acceleration). */ public void moveBackward(){ int localZoom = zoom; if (zoomedOutBeyondOneToOne) { localZoom = 1; } final long now = System.currentTimeMillis(); final long delay = now - thePastLeftArrow; if (delay < 50) { scrollAcceleration++; moveEntireGraphingPanel(-localZoom - (scrollAcceleration * localZoom)); } else { scrollAcceleration = 0; moveEntireGraphingPanel(-localZoom); } thePastLeftArrow = System.currentTimeMillis(); } /** * Move the graph backward a large amount. */ public void moveBackwardCoarse(){ moveBackwardPercentage(COARSE_MOVEMENT_PERCENTAGE); } /** * Move the graph backward by a percentage (amount) of the screen width. * Percentages are expected in decimal form. For example, 0.50 for 50%. */ public void moveBackwardPercentage(double amount){ moveEntireGraphingPanel(-(this.getWidth() * amount)); } /** * Move the graph to the center of the two provided graph positions * so that there are equal data points to the left and to the right. * * Right now the method is expecting to get integer data points as * it should be impossible to select fractions of a data point. */ private void centerGraphPosition(final int beginPosition, final int endPosition) { final int halfScreen = this.getWidth() / 2; double pointsThatFitInHalfScreen = 0; if (zoomedOutBeyondOneToOne) { pointsThatFitInHalfScreen = halfScreen * zoom; } else { pointsThatFitInHalfScreen = halfScreen / (double)zoom; } final int distanceBetweenPositions = endPosition - beginPosition; final double halfwayBetweenTwoPositions = distanceBetweenPositions / 2d; final double centerPosition = (beginPosition + halfwayBetweenTwoPositions) - pointsThatFitInHalfScreen; setGraphPosition(centerPosition); } /** * Used by external sources that don't know or care about the size of the graph. */ public void centerGraphPosition(){ centerGraphPosition(0, graphSize); } /** * Move the graph forward a small amount (with acceleration). */ public void moveForward(){ int localZoom = zoom; if (zoomedOutBeyondOneToOne) { localZoom = 1; } final long now = System.currentTimeMillis(); final long delay = now - thePastRightArrow; if (delay < 50) { scrollAcceleration++; moveEntireGraphingPanel(localZoom + (scrollAcceleration * localZoom)); } else { scrollAcceleration = 0; moveEntireGraphingPanel(localZoom); } thePastRightArrow = System.currentTimeMillis(); } /** * Move the graph forward by a percentage (amount) of the screen width. * Percentages are expected in decimal form. For example, 0.50 for 50%. */ private void moveForwardPercentage(double amount){ moveEntireGraphingPanel(this.getWidth() * amount); } /** * Move the graph forward a large amount. */ public void moveForwardCoarse(){ moveForwardPercentage(COARSE_MOVEMENT_PERCENTAGE); } /** * Move the graph to the end with the last data point centered. */ public void moveToEnd() { goToLastGraphPosition(); moveBackwardPercentage(0.50); } /** * Move the graph to the left so that only one valid * data point shows on the left-most part of the display. */ private void goToLastGraphPosition() { setGraphPosition(getGraphPositionMax()); } public final boolean isPlaying() { return playing; } public final int getZoom() { return zoom; } /** * When the windows is resized, the graph needs to move to maintain the centering. */ public void moveGraphDueToResize() { final int newWidth = this.getWidth(); if (newWidth != oldComponentWidth) { double move = 0.0; final int amount = newWidth - oldComponentWidth; if (zoomedOutBeyondOneToOne) { move = -(amount * zoom); } else { move = -((double) amount / (double) zoom); } move /= 2.0; oldComponentWidth = newWidth; moveGraphPosition(move); } } /** * Take the current graph position and move amount positions forward. */ private void moveGraphPosition(final double amount) { final double newPos = graphPosition + amount; if (newPos > getGraphPositionMax()) { goToLastGraphPosition(); } else if (newPos < getGraphPositionMin()) { resetGraphPosition(); } else { setGraphPosition(newPos); } } /** * Move the graph position to newPosition where newPosition is dictated by * an x screen coordinate. */ private void moveEntireGraphingPanel(final double newPosition) { double move = -1.0; if (zoomedOutBeyondOneToOne) { move = newPosition * zoom; } else { move = newPosition / zoom; } if (graphPosition + move < getGraphPositionMax()) { if (graphPosition + move < getGraphPositionMin()) { resetGraphPosition(); } else { moveGraphPosition(move); } } else { goToLastGraphPosition(); } } private void stopDragging() { dragging = false; prevDragXCoord = -1; } private void stopFlinging() { flinging = false; flingInertia = 0; flingTimer.stop(); } // Mouse listener functionality @Override public final void mouseClicked(final MouseEvent e) { if (!dragging) { final int half = this.getWidth() / 2; moveEntireGraphingPanel(e.getX() - half); } else { stopDragging(); stopFlinging(); } } @Override public final void mouseDragged(final MouseEvent e) { dragging = true; final int xMouseCoord = e.getX(); if ((prevDragXCoord > 0) && (prevDragXCoord != xMouseCoord)) { moveEntireGraphingPanel(prevDragXCoord - xMouseCoord); flingInertia = ((prevDragXCoord - xMouseCoord) * 2); thePastMouseDragged = System.currentTimeMillis(); } prevDragXCoord = xMouseCoord; } @Override public final void mouseMoved(final MouseEvent e) { // What should be here? // Ben says eventually there might be stuff here, and it is required implementation for the MouseMovementListener interface. // Fred says thanks! :-) } @Override public final void mouseEntered(final MouseEvent e) { // What should be here? // Ben says eventually there might be stuff here, and it is required implementation for the MouseMovementListener interface. // Fred says thanks! :-) } @Override public final void mouseExited(final MouseEvent e) { // What should be here? // Ben says eventually there might be stuff here, and it is required implementation for the MouseMovementListener interface. // Fred says thanks! :-) } @Override public final void mousePressed(final MouseEvent e) { wasPlaying = playing; if (playing) { pause(); } stopDragging(); stopFlinging(); } @Override public final void mouseReleased(final MouseEvent e) { stopDragging(); final long now = System.currentTimeMillis(); if ((now - thePastMouseDragged) > 50) { stopFlinging(); // If over 50 milliseconds since dragging then don't fling } if (flingInertia != 0) { fling(); } if (wasPlaying) { play(); } } @Override public final void mouseWheelMoved(final MouseWheelEvent e) { final int xMouseCoord = e.getX(); final double center = this.getWidth() / 2.0; final int notches = e.getWheelRotation(); double move = 0; final int zoomAmount = (int) Math.sqrt(zoom); if (notches < 0) { for (int i = 0; i < zoomAmount; i++) { if (zoomedOutBeyondOneToOne) { move = (xMouseCoord - center) / (zoom - 1.0); } else { move = (xMouseCoord - center) / zoom; } if (!(!zoomedOutBeyondOneToOne && zoom == getTightestZoom())) { zoomIn(); moveEntireGraphingPanel(move); } } } else { for (int i = 0; i < zoomAmount; i++) { if (zoomedOutBeyondOneToOne || zoom == 1) { move = -(xMouseCoord - center) / (zoom + 1.0); } else { move = -(xMouseCoord - center) / zoom; } if (!(zoomedOutBeyondOneToOne && zoom == getWidestZoom())) { zoomOut(); moveEntireGraphingPanel(move); } } } } // Key listener functionality @Override public final void keyPressed(final KeyEvent e) { switch (e.getKeyCode()) { //Close entire application key binding case KeyEvent.VK_Q: { if (e.isControlDown()){ final WindowEvent wev = new WindowEvent(OpenLogViewer.getInstance(), WindowEvent.WINDOW_CLOSING); Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev); } + break; } // Play key binding case KeyEvent.VK_SPACE: { play(); break; } // Enter full screen key binding case KeyEvent.VK_ENTER: { if (e.isAltDown() && e.getKeyLocation() == KeyEvent.KEY_LOCATION_STANDARD) { OpenLogViewer.getInstance().enterFullScreen(); } break; } // Exit full screen key binding case KeyEvent.VK_ESCAPE: { OpenLogViewer.getInstance().exitFullScreen(); break; } // Toggle full screen key binding case KeyEvent.VK_F11: { OpenLogViewer.getInstance().toggleFullScreen(); break; } // Home key binding case KeyEvent.VK_HOME: { moveToBeginning(); break; } // End key binding case KeyEvent.VK_END: { moveToEnd(); break; } // Scroll left key bindings case KeyEvent.VK_PAGE_UP: { moveBackwardCoarse(); break; } case KeyEvent.VK_LEFT: case KeyEvent.VK_KP_LEFT: { if (e.isControlDown()) { moveBackwardCoarse(); } else { moveBackward(); } break; } // Scroll right key bindings case KeyEvent.VK_PAGE_DOWN: { moveForwardCoarse(); break; } case KeyEvent.VK_RIGHT: case KeyEvent.VK_KP_RIGHT: { if (e.isControlDown()) { moveForwardCoarse(); } else { moveForward(); } break; } // Zoom in key bindings case KeyEvent.VK_UP: case KeyEvent.VK_KP_UP: { zoomInCoarse(); break; } case KeyEvent.VK_ADD: { if (e.isControlDown()) { zoomInCoarse(); } break; } // Zoom out key bindings case KeyEvent.VK_DOWN: case KeyEvent.VK_KP_DOWN: { zoomOutCoarse(); break; } case KeyEvent.VK_SUBTRACT: { if (e.isControlDown()) { zoomOutCoarse(); } break; } } } @Override public final void keyReleased(final KeyEvent e) { // What should be here? // Ben says eventually there might be stuff here, and it is required implementation for the KeyListener interface. // Fred says thanks! :-) } @Override public final void keyTyped(final KeyEvent e) { // What should be here? // Ben says eventually there might be stuff here, and it is required implementation for the KeyListener interface. // Fred says thanks! :-) } @Override public void componentHidden(final ComponentEvent e) { // Ben says eventually there might be stuff here, and it is required implementation for the ComponentListener interface. // Fred says thanks! :-) } // Call resize event handler because the Mac sort of treats resizing as a move @Override public final void componentMoved(final ComponentEvent e) { moveGraphDueToResize(); } @Override public final void componentResized(final ComponentEvent e) { moveGraphDueToResize(); } @Override public void componentShown(final ComponentEvent e) { // Ben says eventually there might be stuff here, and it is required implementation for the ComponentListener interface. // Fred says thanks! :-) } }
true
true
public final void keyPressed(final KeyEvent e) { switch (e.getKeyCode()) { //Close entire application key binding case KeyEvent.VK_Q: { if (e.isControlDown()){ final WindowEvent wev = new WindowEvent(OpenLogViewer.getInstance(), WindowEvent.WINDOW_CLOSING); Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev); } } // Play key binding case KeyEvent.VK_SPACE: { play(); break; } // Enter full screen key binding case KeyEvent.VK_ENTER: { if (e.isAltDown() && e.getKeyLocation() == KeyEvent.KEY_LOCATION_STANDARD) { OpenLogViewer.getInstance().enterFullScreen(); } break; } // Exit full screen key binding case KeyEvent.VK_ESCAPE: { OpenLogViewer.getInstance().exitFullScreen(); break; } // Toggle full screen key binding case KeyEvent.VK_F11: { OpenLogViewer.getInstance().toggleFullScreen(); break; } // Home key binding case KeyEvent.VK_HOME: { moveToBeginning(); break; } // End key binding case KeyEvent.VK_END: { moveToEnd(); break; } // Scroll left key bindings case KeyEvent.VK_PAGE_UP: { moveBackwardCoarse(); break; } case KeyEvent.VK_LEFT: case KeyEvent.VK_KP_LEFT: { if (e.isControlDown()) { moveBackwardCoarse(); } else { moveBackward(); } break; } // Scroll right key bindings case KeyEvent.VK_PAGE_DOWN: { moveForwardCoarse(); break; } case KeyEvent.VK_RIGHT: case KeyEvent.VK_KP_RIGHT: { if (e.isControlDown()) { moveForwardCoarse(); } else { moveForward(); } break; } // Zoom in key bindings case KeyEvent.VK_UP: case KeyEvent.VK_KP_UP: { zoomInCoarse(); break; } case KeyEvent.VK_ADD: { if (e.isControlDown()) { zoomInCoarse(); } break; } // Zoom out key bindings case KeyEvent.VK_DOWN: case KeyEvent.VK_KP_DOWN: { zoomOutCoarse(); break; } case KeyEvent.VK_SUBTRACT: { if (e.isControlDown()) { zoomOutCoarse(); } break; } } }
public final void keyPressed(final KeyEvent e) { switch (e.getKeyCode()) { //Close entire application key binding case KeyEvent.VK_Q: { if (e.isControlDown()){ final WindowEvent wev = new WindowEvent(OpenLogViewer.getInstance(), WindowEvent.WINDOW_CLOSING); Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev); } break; } // Play key binding case KeyEvent.VK_SPACE: { play(); break; } // Enter full screen key binding case KeyEvent.VK_ENTER: { if (e.isAltDown() && e.getKeyLocation() == KeyEvent.KEY_LOCATION_STANDARD) { OpenLogViewer.getInstance().enterFullScreen(); } break; } // Exit full screen key binding case KeyEvent.VK_ESCAPE: { OpenLogViewer.getInstance().exitFullScreen(); break; } // Toggle full screen key binding case KeyEvent.VK_F11: { OpenLogViewer.getInstance().toggleFullScreen(); break; } // Home key binding case KeyEvent.VK_HOME: { moveToBeginning(); break; } // End key binding case KeyEvent.VK_END: { moveToEnd(); break; } // Scroll left key bindings case KeyEvent.VK_PAGE_UP: { moveBackwardCoarse(); break; } case KeyEvent.VK_LEFT: case KeyEvent.VK_KP_LEFT: { if (e.isControlDown()) { moveBackwardCoarse(); } else { moveBackward(); } break; } // Scroll right key bindings case KeyEvent.VK_PAGE_DOWN: { moveForwardCoarse(); break; } case KeyEvent.VK_RIGHT: case KeyEvent.VK_KP_RIGHT: { if (e.isControlDown()) { moveForwardCoarse(); } else { moveForward(); } break; } // Zoom in key bindings case KeyEvent.VK_UP: case KeyEvent.VK_KP_UP: { zoomInCoarse(); break; } case KeyEvent.VK_ADD: { if (e.isControlDown()) { zoomInCoarse(); } break; } // Zoom out key bindings case KeyEvent.VK_DOWN: case KeyEvent.VK_KP_DOWN: { zoomOutCoarse(); break; } case KeyEvent.VK_SUBTRACT: { if (e.isControlDown()) { zoomOutCoarse(); } break; } } }
diff --git a/src/robot/Check.java b/src/robot/Check.java index 24eb094..cd0b75d 100644 --- a/src/robot/Check.java +++ b/src/robot/Check.java @@ -1,165 +1,165 @@ /**********************************************************************/ /* Copyright 2013 KRV */ /* */ /* 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 robot; // Libraries import exception.*; import stackable.*; import parameters.*; import arena.Terrain; import stackable.item.*; /** * <b>Assembly functions - class Check</b><br> * Provides the funcions for checking * terrains and neighborhoods content. * * @author Karina Awoki * @author Renato Cordeiro Ferreira * @author Vinícius Silva * @see arena.Terrain * @see stackable.Around */ final public class Check { // No instances of this class allowed private Check() {} /** * Assembly funcion ITEM. <br> * Takes out the top of the main stack, * checks if it's a terrain. If it has * an item, pushes it. In the other case, * pushes 0 in the top of the stack. * * @param rvm Virtual Machine */ static void ITEM(RVM rvm) throws StackUnderflowException, WrongTypeException { Stackable stk; try { stk = rvm.DATA.pop(); } catch (Exception e) { throw new StackUnderflowException(); } if(!(stk instanceof Terrain)) throw new WrongTypeException("Terrain"); // Get terrain's item Terrain t = (Terrain) stk; stackable.item.Item item = t.getItem(); // Debug String itm = (item != null) ? item.toString() : "NONE"; Debugger.say(" [ITEM] ", itm); // Return Num(0) if no item is avaiable. if(item == null) rvm.DATA.push(new Num(0)); else rvm.DATA.push(item); } /** * Assembly funcion SEEK. <br> * Process an 'Around' stackable for * serching if there is an item avaiable. * The item to be searched and the around * are taken from the top of the stack. * (First the item, secondly, around). * The answer is put in the top of the * main stack. * * @param rvm Virtual Machine */ static void SEEK(RVM rvm) throws StackUnderflowException, - WrongTypeException, - InvalidOperationException + WrongTypeException, + InvalidOperationException { Stackable ar; Stackable stk; int cont = 0; // Takes the argument and the neighborhood // from the top of the stack. try { stk = rvm.DATA.pop(); } catch (Exception e) { throw new StackUnderflowException(); } try { ar = rvm.DATA.pop(); } catch (Exception e) { throw new StackUnderflowException(); } // Checks if ar is of type around. if(!(ar instanceof Around)) throw new WrongTypeException("Around"); Around a = (Around) ar; String s; int index; // Checks if stk is a text or an item. if(stk instanceof Text) { s = ((Text)stk).getText(); index = 0; } else if(stk instanceof stackable.item.Item) { s = stk.getClass().getName(); index = 1; } else throw new WrongTypeException("Text or Item"); // Put in the Stack of the RVM the // direction and the confirmation // of the finded object for(int i = a.matrix[0].length - 1; i >= 0; i--) { if(a.matrix[index][i] != null && s.equals(a.matrix[index][i]) ) { if(i < 7) { rvm.DATA.push(new Direction(0, i)); rvm.DATA.push(new Num(1)); } else { rvm.DATA.push(new Direction(1, i)); rvm.DATA.push(new Direction(0, i)); rvm.DATA.push(new Num(2)); } cont++; } } rvm.DATA.push(new Num(cont)); // Debug String arnd = (a != null) ? "Pop the around correctly: " : "NONE"; String stack = (a != null) ? stk.toString() : "NONE"; Debugger.say(" [SEEK] ", arnd, stack); } }
true
true
static void SEEK(RVM rvm) throws StackUnderflowException, WrongTypeException, InvalidOperationException { Stackable ar; Stackable stk; int cont = 0; // Takes the argument and the neighborhood // from the top of the stack. try { stk = rvm.DATA.pop(); } catch (Exception e) { throw new StackUnderflowException(); } try { ar = rvm.DATA.pop(); } catch (Exception e) { throw new StackUnderflowException(); } // Checks if ar is of type around. if(!(ar instanceof Around)) throw new WrongTypeException("Around"); Around a = (Around) ar; String s; int index; // Checks if stk is a text or an item. if(stk instanceof Text) { s = ((Text)stk).getText(); index = 0; } else if(stk instanceof stackable.item.Item) { s = stk.getClass().getName(); index = 1; } else throw new WrongTypeException("Text or Item"); // Put in the Stack of the RVM the // direction and the confirmation // of the finded object for(int i = a.matrix[0].length - 1; i >= 0; i--) { if(a.matrix[index][i] != null && s.equals(a.matrix[index][i]) ) { if(i < 7) { rvm.DATA.push(new Direction(0, i)); rvm.DATA.push(new Num(1)); } else { rvm.DATA.push(new Direction(1, i)); rvm.DATA.push(new Direction(0, i)); rvm.DATA.push(new Num(2)); } cont++; } } rvm.DATA.push(new Num(cont)); // Debug String arnd = (a != null) ? "Pop the around correctly: " : "NONE"; String stack = (a != null) ? stk.toString() : "NONE"; Debugger.say(" [SEEK] ", arnd, stack); }
static void SEEK(RVM rvm) throws StackUnderflowException, WrongTypeException, InvalidOperationException { Stackable ar; Stackable stk; int cont = 0; // Takes the argument and the neighborhood // from the top of the stack. try { stk = rvm.DATA.pop(); } catch (Exception e) { throw new StackUnderflowException(); } try { ar = rvm.DATA.pop(); } catch (Exception e) { throw new StackUnderflowException(); } // Checks if ar is of type around. if(!(ar instanceof Around)) throw new WrongTypeException("Around"); Around a = (Around) ar; String s; int index; // Checks if stk is a text or an item. if(stk instanceof Text) { s = ((Text)stk).getText(); index = 0; } else if(stk instanceof stackable.item.Item) { s = stk.getClass().getName(); index = 1; } else throw new WrongTypeException("Text or Item"); // Put in the Stack of the RVM the // direction and the confirmation // of the finded object for(int i = a.matrix[0].length - 1; i >= 0; i--) { if(a.matrix[index][i] != null && s.equals(a.matrix[index][i]) ) { if(i < 7) { rvm.DATA.push(new Direction(0, i)); rvm.DATA.push(new Num(1)); } else { rvm.DATA.push(new Direction(1, i)); rvm.DATA.push(new Direction(0, i)); rvm.DATA.push(new Num(2)); } cont++; } } rvm.DATA.push(new Num(cont)); // Debug String arnd = (a != null) ? "Pop the around correctly: " : "NONE"; String stack = (a != null) ? stk.toString() : "NONE"; Debugger.say(" [SEEK] ", arnd, stack); }
diff --git a/src/main/java/com/mast3rplan/alphachest/acChestManager.java b/src/main/java/com/mast3rplan/alphachest/acChestManager.java index 69c7da1..b625107 100644 --- a/src/main/java/com/mast3rplan/alphachest/acChestManager.java +++ b/src/main/java/com/mast3rplan/alphachest/acChestManager.java @@ -1,153 +1,152 @@ package com.mast3rplan.alphachest; import com.mast3rplan.alphachest.acChest; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.HashMap; import java.util.logging.Logger; import net.minecraft.server.InventoryLargeChest; import net.minecraft.server.ItemStack; public class acChestManager { private static Logger log = Logger.getLogger("Minecraft"); private HashMap<String, InventoryLargeChest> chests = new HashMap<String, InventoryLargeChest>(); private File dataFolder; public acChestManager(File dataFolder) { this.dataFolder = dataFolder; } public InventoryLargeChest getChest(String playerName) { InventoryLargeChest chest = null; chest = (InventoryLargeChest) chests.get(playerName.toLowerCase()); if (chest == null) { chest = this.addChest(playerName); } return chest; } public void removeChest(String playerName) { chests.remove(playerName.toLowerCase()); } public InventoryLargeChest addChest(String playerName) { InventoryLargeChest chest = new InventoryLargeChest(playerName + "\'s Virtual Chest", new acChest(), new acChest()); chests.put(playerName.toLowerCase(), chest); return chest; } public void load() { chests = new HashMap<String, InventoryLargeChest>(); int loadedChests = 0; File chestsFolder = new File(this.dataFolder, "chests"); if (!chestsFolder.exists()) { chestsFolder.mkdir(); } File[] chestFiles; int chestCount = (chestFiles = chestsFolder.listFiles()).length; for (int i = 0; i < chestCount; ++i) { File chestFile = chestFiles[i]; if (chestFile.getName().endsWith(".chest")) { try { InventoryLargeChest e = new InventoryLargeChest("Large chest", new acChest(), new acChest()); String playerName = chestFile.getName().substring(0, chestFile.getName().length() - 6); FileInputStream fstream = new FileInputStream(chestFile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int p = 0; String strLine; while ((strLine = br.readLine()) != null) { if (strLine != "") { String[] parts = strLine.split(":"); int type = Integer.parseInt(parts[0]); int amount = Integer.parseInt(parts[1]); short damage = Short.parseShort(parts[2]); if (type != 0) { - // FIXME: broken! - e.a(p, new ItemStack(type, amount, damage)); + e.setItem(p, new ItemStack(type, amount, damage)); } ++p; } } in.close(); chests.put(playerName.toLowerCase(), e); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } ++loadedChests; } } log.info("[Alpha Chest] loaded " + loadedChests + " chests"); } public void save() { int savedChests = 0; File chestsFolder = new File(this.dataFolder, "chests"); if (!chestsFolder.exists()) { chestsFolder.mkdir(); } for (String playerName : chests.keySet()) { InventoryLargeChest chest = (InventoryLargeChest) chests.get(playerName); try { File chestFile = new File(chestsFolder, playerName + ".chest"); if (chestFile.exists()) chestFile.delete(); chestFile.createNewFile(); DataOutputStream out = new DataOutputStream(new FileOutputStream(chestFile)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); ItemStack[] itemStacks = chest.getContents(); for (int i = 0; i < itemStacks.length; ++i) { ItemStack stack = itemStacks[i]; int type = 0; int amount = 0; int damage = -1; type = stack.id; amount = stack.count; damage = stack.damage; bw.write(type + ":" + amount + ":" + damage + "\r\n"); } bw.flush(); out.close(); savedChests++; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } log.info("[Alpha Chest] saved " + savedChests + " chests"); } }
true
true
public void load() { chests = new HashMap<String, InventoryLargeChest>(); int loadedChests = 0; File chestsFolder = new File(this.dataFolder, "chests"); if (!chestsFolder.exists()) { chestsFolder.mkdir(); } File[] chestFiles; int chestCount = (chestFiles = chestsFolder.listFiles()).length; for (int i = 0; i < chestCount; ++i) { File chestFile = chestFiles[i]; if (chestFile.getName().endsWith(".chest")) { try { InventoryLargeChest e = new InventoryLargeChest("Large chest", new acChest(), new acChest()); String playerName = chestFile.getName().substring(0, chestFile.getName().length() - 6); FileInputStream fstream = new FileInputStream(chestFile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int p = 0; String strLine; while ((strLine = br.readLine()) != null) { if (strLine != "") { String[] parts = strLine.split(":"); int type = Integer.parseInt(parts[0]); int amount = Integer.parseInt(parts[1]); short damage = Short.parseShort(parts[2]); if (type != 0) { // FIXME: broken! e.a(p, new ItemStack(type, amount, damage)); } ++p; } } in.close(); chests.put(playerName.toLowerCase(), e); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } ++loadedChests; } } log.info("[Alpha Chest] loaded " + loadedChests + " chests"); }
public void load() { chests = new HashMap<String, InventoryLargeChest>(); int loadedChests = 0; File chestsFolder = new File(this.dataFolder, "chests"); if (!chestsFolder.exists()) { chestsFolder.mkdir(); } File[] chestFiles; int chestCount = (chestFiles = chestsFolder.listFiles()).length; for (int i = 0; i < chestCount; ++i) { File chestFile = chestFiles[i]; if (chestFile.getName().endsWith(".chest")) { try { InventoryLargeChest e = new InventoryLargeChest("Large chest", new acChest(), new acChest()); String playerName = chestFile.getName().substring(0, chestFile.getName().length() - 6); FileInputStream fstream = new FileInputStream(chestFile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int p = 0; String strLine; while ((strLine = br.readLine()) != null) { if (strLine != "") { String[] parts = strLine.split(":"); int type = Integer.parseInt(parts[0]); int amount = Integer.parseInt(parts[1]); short damage = Short.parseShort(parts[2]); if (type != 0) { e.setItem(p, new ItemStack(type, amount, damage)); } ++p; } } in.close(); chests.put(playerName.toLowerCase(), e); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } ++loadedChests; } } log.info("[Alpha Chest] loaded " + loadedChests + " chests"); }
diff --git a/src/Developer.java b/src/Developer.java index 339ff4b..6d8ba07 100644 --- a/src/Developer.java +++ b/src/Developer.java @@ -1,91 +1,97 @@ import java.util.Calendar; import java.util.Random; /** * This model describes the Developer. It extends Programmer. * * @author Yin * @author Shawn * @author Peter */ public class Developer extends Employee { /** * The Developer's Team Leader. */ private TeamLeader leader; /** * Default Constructor. * * @param leader * - Assigned Team Leader */ public Developer(Calendar time, String name) { currentTime = Calendar.getInstance(); currentTime.set(Calendar.YEAR, Calendar.MONTH, Calendar.DATE, 8, 0); this.startTime = time; this.arrived = false; this.name=name; } /** * Ask Team Leader or Project Manager question. Question will first go to * Team Leader if he/she is available; otherwise, it will go to the Project * Manager. */ public void askQuestion() { leader.answerQuestion(); } /** * Set the leader. */ public void setLeader(TeamLeader leader) { this.leader = leader; } /** * Override for the run method in the Thread class. */ @Override public void run() { Random ran = new Random(); Boolean hasGoneToLunch=false; + Boolean hasGoneToMeeting=false; try{ leader.notifyArrival(this); }catch(InterruptedException e){} - while(true){ + long begin = System.currentTimeMillis(); + while(System.currentTimeMillis()-begin< 4800 && hasGoneToMeeting){ // Ask team leader a question. int askQuestion=ran.nextInt(100); if (askQuestion<=10){ System.out.println("Developer"+name+" has asked leader a question"); leader.answerQuestion(); } // Lunch if(!hasGoneToLunch){ int goToLunch=ran.nextInt(100); if(goToLunch<=50){ System.out.println("Developer"+name+" has gone to lunch"); int lunchTime=ran.nextInt(300)+300; try { sleep(lunchTime); } catch (InterruptedException e) {} + finally{ + hasGoneToLunch=true; + } } } // Project Status meeting if(getTime().get(Calendar.HOUR_OF_DAY)==4){ try{ - System.out.println("Developer"+name+" going to project status meeting"); + System.out.println("Developer"+name+" is going to project status meeting"); Calendar fourThirty = Calendar.getInstance(); fourThirty.set(Calendar.YEAR, Calendar.MONTH, Calendar.DATE, 16, 30); long sleepTime=fourThirty.getTimeInMillis()-getTime().getTimeInMillis(); sleep(sleepTime); + hasGoneToMeeting=true; }catch(InterruptedException e){} } } } }
false
true
public void run() { Random ran = new Random(); Boolean hasGoneToLunch=false; try{ leader.notifyArrival(this); }catch(InterruptedException e){} while(true){ // Ask team leader a question. int askQuestion=ran.nextInt(100); if (askQuestion<=10){ System.out.println("Developer"+name+" has asked leader a question"); leader.answerQuestion(); } // Lunch if(!hasGoneToLunch){ int goToLunch=ran.nextInt(100); if(goToLunch<=50){ System.out.println("Developer"+name+" has gone to lunch"); int lunchTime=ran.nextInt(300)+300; try { sleep(lunchTime); } catch (InterruptedException e) {} } } // Project Status meeting if(getTime().get(Calendar.HOUR_OF_DAY)==4){ try{ System.out.println("Developer"+name+" going to project status meeting"); Calendar fourThirty = Calendar.getInstance(); fourThirty.set(Calendar.YEAR, Calendar.MONTH, Calendar.DATE, 16, 30); long sleepTime=fourThirty.getTimeInMillis()-getTime().getTimeInMillis(); sleep(sleepTime); }catch(InterruptedException e){} } } }
public void run() { Random ran = new Random(); Boolean hasGoneToLunch=false; Boolean hasGoneToMeeting=false; try{ leader.notifyArrival(this); }catch(InterruptedException e){} long begin = System.currentTimeMillis(); while(System.currentTimeMillis()-begin< 4800 && hasGoneToMeeting){ // Ask team leader a question. int askQuestion=ran.nextInt(100); if (askQuestion<=10){ System.out.println("Developer"+name+" has asked leader a question"); leader.answerQuestion(); } // Lunch if(!hasGoneToLunch){ int goToLunch=ran.nextInt(100); if(goToLunch<=50){ System.out.println("Developer"+name+" has gone to lunch"); int lunchTime=ran.nextInt(300)+300; try { sleep(lunchTime); } catch (InterruptedException e) {} finally{ hasGoneToLunch=true; } } } // Project Status meeting if(getTime().get(Calendar.HOUR_OF_DAY)==4){ try{ System.out.println("Developer"+name+" is going to project status meeting"); Calendar fourThirty = Calendar.getInstance(); fourThirty.set(Calendar.YEAR, Calendar.MONTH, Calendar.DATE, 16, 30); long sleepTime=fourThirty.getTimeInMillis()-getTime().getTimeInMillis(); sleep(sleepTime); hasGoneToMeeting=true; }catch(InterruptedException e){} } } }
diff --git a/src/java/org/jivesoftware/spark/ui/conferences/GroupChatParticipantList.java b/src/java/org/jivesoftware/spark/ui/conferences/GroupChatParticipantList.java index 297a6a79..1d511f71 100644 --- a/src/java/org/jivesoftware/spark/ui/conferences/GroupChatParticipantList.java +++ b/src/java/org/jivesoftware/spark/ui/conferences/GroupChatParticipantList.java @@ -1,939 +1,943 @@ /** * $RCSfile: ,v $ * $Revision: $ * $Date: $ * * Copyright (C) 2004-2010 Jive Software. All rights reserved. * * 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.jivesoftware.spark.ui.conferences; import org.jdesktop.swingx.JXList; import org.jivesoftware.resource.Res; import org.jivesoftware.resource.SparkRes; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.packet.XMPPError; import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smackx.ServiceDiscoveryManager; import org.jivesoftware.smackx.muc.Affiliate; import org.jivesoftware.smackx.muc.InvitationRejectionListener; import org.jivesoftware.smackx.muc.MultiUserChat; import org.jivesoftware.smackx.muc.Occupant; import org.jivesoftware.smackx.muc.UserStatusListener; import org.jivesoftware.smackx.packet.DiscoverInfo; import org.jivesoftware.spark.ChatManager; import org.jivesoftware.spark.PresenceManager; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.UserManager; import org.jivesoftware.spark.component.ImageTitlePanel; import org.jivesoftware.spark.ui.ChatRoom; import org.jivesoftware.spark.ui.ChatRoomListener; import org.jivesoftware.spark.ui.ChatRoomNotFoundException; import org.jivesoftware.spark.ui.rooms.ChatRoomImpl; import org.jivesoftware.spark.ui.rooms.GroupChatRoom; import org.jivesoftware.spark.util.ModelUtil; import org.jivesoftware.spark.util.log.Log; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.DefaultListModel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import javax.swing.SwingUtilities; /** * The <code>RoomInfo</code> class is used to display all room information, such * as agents and room information. */ public final class GroupChatParticipantList extends JPanel implements ChatRoomListener { private static final long serialVersionUID = 3809155443119207342L; private GroupChatRoom groupChatRoom; private final ImageTitlePanel agentInfoPanel; private ChatManager chatManager; private MultiUserChat chat; private final Map<String, String> userMap = new HashMap<String, String>(); private UserManager userManager = SparkManager.getUserManager(); private DefaultListModel model = new DefaultListModel(); private JXList participantsList; private PacketListener listener = null; private Map<String, String> invitees = new HashMap<String, String>(); private boolean allowNicknameChange = true; private DiscoverInfo roomInformation; private List<JLabel> users = new ArrayList<JLabel>(); /** * Creates a new RoomInfo instance using the specified ChatRoom. The * RoomInfo component is responsible for monitoring all activity in the * ChatRoom. */ public GroupChatParticipantList() { setLayout(new GridBagLayout()); chatManager = SparkManager.getChatManager(); agentInfoPanel = new ImageTitlePanel(Res .getString("message.participants.in.room")); participantsList = new JXList(model); participantsList.setCellRenderer(new ParticipantRenderer()); // Set the room to track this.setOpaque(false); this.setBackground(Color.white); // Respond to Double-Click in Agent List to start a chat participantsList.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { String selectedUser = getSelectedUser(); startChat(groupChatRoom, userMap.get(selectedUser)); } } public void mouseReleased(final MouseEvent evt) { if (evt.isPopupTrigger()) { checkPopup(evt); } } public void mousePressed(final MouseEvent evt) { if (evt.isPopupTrigger()) { checkPopup(evt); } } }); JScrollPane scroller = new JScrollPane(participantsList); // Speed up scrolling. It was way too slow. scroller.getVerticalScrollBar().setBlockIncrement(50); scroller.getVerticalScrollBar().setUnitIncrement(20); scroller.setBackground(Color.white); scroller.getViewport().setBackground(Color.white); add(scroller, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets( 0, 0, 0, 0), 0, 0)); } public void setChatRoom(final ChatRoom chatRoom) { this.groupChatRoom = (GroupChatRoom) chatRoom; chatManager.addChatRoomListener(this); chat = groupChatRoom.getMultiUserChat(); chat.addInvitationRejectionListener(new InvitationRejectionListener() { public void invitationDeclined(String jid, String message) { String nickname = userManager.getUserNicknameFromJID(jid); userHasLeft(chatRoom, nickname); chatRoom.getTranscriptWindow().insertNotificationMessage( nickname + " has rejected the invitation.", ChatManager.NOTIFICATION_COLOR); } }); listener = new PacketListener() { public void processPacket(final Packet packet) { SwingUtilities.invokeLater(new Runnable() { public void run() { Presence p = (Presence) packet; if (p.getError() != null) { if (p.getError().getCondition().equals( XMPPError.Condition.conflict.toString())) { return; } } final String userid = p.getFrom(); String displayName = StringUtils.parseResource(userid); userMap.put(displayName, userid); if (p.getType() == Presence.Type.available) { addParticipant(userid, p); agentInfoPanel.setVisible(true); } else { removeUser(displayName); } } }); } }; chat.addParticipantListener(listener); ServiceDiscoveryManager disco = ServiceDiscoveryManager .getInstanceFor(SparkManager.getConnection()); try { roomInformation = disco.discoverInfo(chat.getRoom()); } catch (XMPPException e) { Log.debug("Unable to retrieve room informatino for " + chat.getRoom()); } } public void chatRoomOpened(ChatRoom room) { if (room != groupChatRoom) { return; } chat.addUserStatusListener(new UserStatusListener() { public void kicked(String actor, String reason) { } public void voiceGranted() { } public void voiceRevoked() { } public void banned(String actor, String reason) { } public void membershipGranted() { } public void membershipRevoked() { } public void moderatorGranted() { } public void moderatorRevoked() { } public void ownershipGranted() { } public void ownershipRevoked() { } public void adminGranted() { } public void adminRevoked() { } }); } public void chatRoomLeft(ChatRoom room) { if (this.groupChatRoom == room) { chatManager.removeChatRoomListener(this); agentInfoPanel.setVisible(false); } } public void chatRoomClosed(ChatRoom room) { if (this.groupChatRoom == room) { chatManager.removeChatRoomListener(this); chat.removeParticipantListener(listener); } } public void chatRoomActivated(ChatRoom room) { } public void userHasJoined(ChatRoom room, String userid) { } public void addInvitee(String jid, String message) { // So the problem with this is that I have no idea what the users actual // jid is in most cases. final UserManager userManager = SparkManager.getUserManager(); String displayName = userManager.getUserNicknameFromJID(jid); groupChatRoom.getTranscriptWindow().insertNotificationMessage( displayName + " has been invited to join this room.", ChatManager.NOTIFICATION_COLOR); if (roomInformation != null && !roomInformation.containsFeature("muc_nonanonymous")) { return; } final ImageIcon inviteIcon = SparkRes .getImageIcon(SparkRes.USER1_BACK_16x16); addUser(inviteIcon, displayName); invitees.put(displayName, message); } private ImageIcon getImageIcon(String participantJID) { String displayName = StringUtils.parseResource(participantJID); ImageIcon icon = SparkRes.getImageIcon(SparkRes.GREEN_BALL); icon.setDescription(displayName); return icon; } private void addParticipant(String participantJID, Presence presence) { // Remove reference to invitees for (String displayName : invitees.keySet()) { String jid = SparkManager.getUserManager().getJIDFromDisplayName( displayName); Occupant occ = chat.getOccupant(participantJID); if (occ != null) { String actualJID = occ.getJid(); if (actualJID.equals(jid)) { removeUser(displayName); } } } String nickname = StringUtils.parseResource(participantJID); if (!exists(nickname)) { Icon icon; icon = PresenceManager.getIconFromPresence(presence); if (icon == null) { icon = SparkRes.getImageIcon(SparkRes.GREEN_BALL); } addUser(icon, nickname); } else { Icon icon = PresenceManager.getIconFromPresence(presence); if (icon == null) { icon = SparkRes.getImageIcon(SparkRes.GREEN_BALL); } int index = getIndex(nickname); if (index != -1) { final JLabel userLabel = new JLabel(nickname, icon, JLabel.HORIZONTAL); model.setElementAt(userLabel, index); } } } public void userHasLeft(ChatRoom room, String userid) { if (room != groupChatRoom) { return; } int index = getIndex(userid); if (index != -1) { removeUser(userid); userMap.remove(userid); } } private boolean exists(String nickname) { for (int i = 0; i < model.getSize(); i++) { final JLabel userLabel = (JLabel) model.getElementAt(i); if (userLabel.getText().equals(nickname)) { return true; } } return false; } private String getSelectedUser() { JLabel label = (JLabel) participantsList.getSelectedValue(); if (label != null) { return label.getText(); } return null; } private void startChat(ChatRoom groupChat, String groupJID) { String userNickname = StringUtils.parseResource(groupJID); String roomTitle = userNickname + " - " + StringUtils.parseName(groupChat.getRoomname()); String nicknameOfUser = StringUtils.parseResource(groupJID); String nickname = groupChat.getNickname(); if (nicknameOfUser.equals(nickname)) { return; } ChatRoom chatRoom; try { chatRoom = chatManager.getChatContainer().getChatRoom(groupJID); } catch (ChatRoomNotFoundException e) { Log.debug("Could not find chat room - " + groupJID); // Create new room chatRoom = new ChatRoomImpl(groupJID, nicknameOfUser, roomTitle); chatManager.getChatContainer().addChatRoom(chatRoom); } chatManager.getChatContainer().activateChatRoom(chatRoom); } public void tabSelected() { // To change body of implemented methods use File | Settings | File // Templates. } public String getTabTitle() { return Res.getString("title.room.information"); } public Icon getTabIcon() { return SparkRes.getImageIcon(SparkRes.SMALL_BUSINESS_MAN_VIEW); } public String getTabToolTip() { return Res.getString("title.room.information"); } public JComponent getGUI() { return this; } private void kickUser(String nickname) { try { chat.kickParticipant(nickname, Res .getString("message.you.have.been.kicked")); } catch (XMPPException e) { groupChatRoom.insertText(Res.getString("message.kicked.error", nickname)); } } private void banUser(String displayName) { try { Occupant occupant = chat.getOccupant(userMap.get(displayName)); if (occupant != null) { String bareJID = StringUtils .parseBareAddress(occupant.getJid()); chat.banUser(bareJID, Res .getString("message.you.have.been.banned")); } } catch (XMPPException e) { Log.error(e); } } private void unbanUser(String jid) { try { chat.grantMembership(jid); } catch (XMPPException e) { Log.error(e); } } private void grantVoice(String nickname) { try { chat.grantVoice(nickname); } catch (XMPPException e) { Log.error(e); } } private void revokeVoice(String nickname) { try { chat.revokeVoice(nickname); } catch (XMPPException e) { Log.error(e); } } private void grantModerator(String nickname) { try { chat.grantModerator(nickname); } catch (XMPPException e) { Log.error(e); } } private void revokeModerator(String nickname) { try { chat.revokeModerator(nickname); } catch (XMPPException e) { Log.error(e); } } /** * Let's make sure that the panel doesn't strech past the scrollpane view * pane. * * @return the preferred dimension */ public Dimension getPreferredSize() { final Dimension size = super.getPreferredSize(); size.width = 150; return size; } private void checkPopup(MouseEvent evt) { Point p = evt.getPoint(); final int index = participantsList.locationToIndex(p); final JPopupMenu popup = new JPopupMenu(); if (index != -1) { participantsList.setSelectedIndex(index); final JLabel userLabel = (JLabel) model.getElementAt(index); final String selectedUser = userLabel.getText(); final String groupJID = userMap.get(selectedUser); String groupJIDNickname = StringUtils.parseResource(groupJID); final String nickname = groupChatRoom.getNickname(); final Occupant occupant = userManager.getOccupant(groupChatRoom, selectedUser); final boolean admin = SparkManager.getUserManager().isOwnerOrAdmin( groupChatRoom, chat.getNickname()); final boolean moderator = SparkManager.getUserManager() .isModerator(groupChatRoom, chat.getNickname()); final boolean userIsAdmin = userManager.isOwnerOrAdmin(occupant); final boolean userIsModerator = userManager.isModerator(occupant); boolean isMe = nickname.equals(groupJIDNickname); // Handle invites if (groupJIDNickname == null) { Action inviteAgainAction = new AbstractAction() { private static final long serialVersionUID = -1875073139356098243L; public void actionPerformed(ActionEvent actionEvent) { String message = invitees.get(selectedUser); String jid = userManager .getJIDFromDisplayName(selectedUser); chat.invite(jid, message); } }; inviteAgainAction.putValue(Action.NAME, Res.getString("menuitem.inivite.again")); popup.add(inviteAgainAction); Action removeInvite = new AbstractAction() { private static final long serialVersionUID = -3647279452501661970L; public void actionPerformed(ActionEvent actionEvent) { int index = getIndex(selectedUser); if (index != -1) { model.removeElementAt(index); } } }; removeInvite.putValue(Action.NAME, Res.getString("menuitem.remove")); popup.add(removeInvite); popup.show(participantsList, evt.getX(), evt.getY()); return; } if (isMe) { Action changeNicknameAction = new AbstractAction() { private static final long serialVersionUID = -7891803180672794112L; public void actionPerformed(ActionEvent actionEvent) { String newNickname = JOptionPane.showInputDialog( groupChatRoom, Res .getString("label.new.nickname") + ":", Res .getString("title.change.nickname"), JOptionPane.QUESTION_MESSAGE); if (ModelUtil.hasLength(newNickname)) { while (true) { newNickname = newNickname.trim(); String nick = chat.getNickname(); if (newNickname.equals(nick)) { // return; } try { chat.changeNickname(newNickname); break; } catch (XMPPException e1) { + if (e1.getXMPPError().getCode() == 406) { //handle deny changing nick + JOptionPane.showMessageDialog(groupChatRoom, Res.getString("message.nickname.not.acceptable"), Res.getString("title.change.nickname"), JOptionPane.ERROR_MESSAGE); + break; + } newNickname = JOptionPane .showInputDialog( groupChatRoom, Res .getString("message.nickname.in.use") + ":", Res .getString("title.change.nickname"), JOptionPane.QUESTION_MESSAGE); if (!ModelUtil.hasLength(newNickname)) { break; } } } } } }; changeNicknameAction.putValue(Action.NAME, Res .getString("menuitem.change.nickname")); changeNicknameAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.DESKTOP_IMAGE)); if (allowNicknameChange) { popup.add(changeNicknameAction); } } Action chatAction = new AbstractAction() { private static final long serialVersionUID = -2739549054781928195L; public void actionPerformed(ActionEvent actionEvent) { String selectedUser = getSelectedUser(); startChat(groupChatRoom, userMap.get(selectedUser)); } }; chatAction.putValue(Action.NAME, Res .getString("menuitem.start.a.chat")); chatAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.SMALL_MESSAGE_IMAGE)); if (!isMe) { popup.add(chatAction); } Action blockAction = new AbstractAction() { private static final long serialVersionUID = 8771362206105723776L; public void actionPerformed(ActionEvent e) { String user = getSelectedUser(); ImageIcon icon; if (groupChatRoom.isBlocked(groupJID)) { groupChatRoom.removeBlockedUser(groupJID); icon = getImageIcon(groupJID); } else { groupChatRoom.addBlockedUser(groupJID); icon = SparkRes.getImageIcon(SparkRes.BRICKWALL_IMAGE); } JLabel label = new JLabel(user, icon, JLabel.HORIZONTAL); model.setElementAt(label, index); } }; blockAction.putValue(Action.NAME, Res .getString("menuitem.block.user")); blockAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.BRICKWALL_IMAGE)); if (!isMe) { if (groupChatRoom.isBlocked(groupJID)) { blockAction.putValue(Action.NAME, Res .getString("menuitem.unblock.user")); } popup.add(blockAction); } Action kickAction = new AbstractAction() { private static final long serialVersionUID = 5769982955040961189L; public void actionPerformed(ActionEvent actionEvent) { kickUser(selectedUser); } }; kickAction.putValue(Action.NAME, Res .getString("menuitem.kick.user")); kickAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.SMALL_DELETE)); if (moderator && !userIsAdmin && !isMe) { popup.add(kickAction); } // Handle Voice Operations Action voiceAction = new AbstractAction() { private static final long serialVersionUID = 7628207942009369329L; public void actionPerformed(ActionEvent actionEvent) { if (userManager.hasVoice(groupChatRoom, selectedUser)) { revokeVoice(selectedUser); } else { grantVoice(selectedUser); } } }; voiceAction.putValue(Action.NAME, Res.getString("menuitem.voice")); voiceAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.MEGAPHONE_16x16)); if (moderator && !userIsModerator && !isMe) { if (userManager.hasVoice(groupChatRoom, selectedUser)) { voiceAction.putValue(Action.NAME, Res .getString("menuitem.revoke.voice")); } else { voiceAction.putValue(Action.NAME, Res .getString("menuitem.grant.voice")); } popup.add(voiceAction); } Action banAction = new AbstractAction() { private static final long serialVersionUID = 4290194898356641253L; public void actionPerformed(ActionEvent actionEvent) { banUser(selectedUser); } }; banAction.putValue(Action.NAME, Res.getString("menuitem.ban.user")); banAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.RED_FLAG_16x16)); if (admin && !userIsModerator && !isMe) { popup.add(banAction); } Action moderatorAction = new AbstractAction() { private static final long serialVersionUID = 8162535640460764896L; public void actionPerformed(ActionEvent actionEvent) { if (!userIsModerator) { grantModerator(selectedUser); } else { revokeModerator(selectedUser); } } }; moderatorAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.MODERATOR_IMAGE)); if (admin && !userIsModerator) { moderatorAction.putValue(Action.NAME, Res .getString("menuitem.grant.moderator")); popup.add(moderatorAction); } else if (admin && userIsModerator && !isMe) { moderatorAction.putValue(Action.NAME, Res .getString("menuitem.revoke.moderator")); popup.add(moderatorAction); } // Handle Unbanning of users. Action unbanAction = new AbstractAction() { private static final long serialVersionUID = 3672121864443182872L; public void actionPerformed(ActionEvent actionEvent) { String jid = ((JMenuItem) actionEvent.getSource()) .getText(); unbanUser(jid); } }; if (admin) { JMenu unbanMenu = new JMenu(Res.getString("menuitem.unban")); Iterator<Affiliate> bannedUsers = null; try { bannedUsers = chat.getOutcasts().iterator(); } catch (XMPPException e) { Log.error("Error loading all banned users", e); } while (bannedUsers != null && bannedUsers.hasNext()) { Affiliate bannedUser = (Affiliate) bannedUsers.next(); ImageIcon icon = SparkRes.getImageIcon(SparkRes.RED_BALL); JMenuItem bannedItem = new JMenuItem(bannedUser.getJid(), icon); unbanMenu.add(bannedItem); bannedItem.addActionListener(unbanAction); } if (unbanMenu.getMenuComponentCount() > 0) { popup.add(unbanMenu); } } } Action inviteAction = new AbstractAction() { private static final long serialVersionUID = 2240864466141501086L; public void actionPerformed(ActionEvent actionEvent) { ConferenceUtils.inviteUsersToRoom(groupChatRoom .getConferenceService(), groupChatRoom.getRoomname(), null); } }; inviteAction.putValue(Action.NAME, Res .getString("menuitem.invite.users")); inviteAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.CONFERENCE_IMAGE_16x16)); if (index != -1) { popup.addSeparator(); } popup.add(inviteAction); popup.show(participantsList, evt.getX(), evt.getY()); } public void setNicknameChangeAllowed(boolean allowed) { allowNicknameChange = allowed; } public int getIndex(String name) { for (int i = 0; i < model.getSize(); i++) { JLabel label = (JLabel) model.getElementAt(i); if (label.getText().equals(name)) { return i; } } return -1; } /** * Removes a user from the participant list based on their displayed name. * * @param displayName * the users displayed name to remove. */ public synchronized void removeUser(String displayName) { try { for (int i = 0; i < users.size(); i++) { JLabel label = users.get(i); if (label.getText().equals(displayName)) { users.remove(label); model.removeElement(label); } } for (int i = 0; i < model.size(); i++) { JLabel label = (JLabel) model.getElementAt(i); if (label.getText().equals(displayName)) { users.remove(label); model.removeElement(label); } } } catch (Exception e) { Log.error(e); } } /** * Adds a new user to the participant list. * * @param userIcon * the icon to use initially. * @param nickname * the users nickname. */ public synchronized void addUser(Icon userIcon, String nickname) { try { final JLabel user = new JLabel(nickname, userIcon, JLabel.HORIZONTAL); users.add(user); // Sort users alpha. Collections.sort(users, labelComp); // Add to the correct position in the model. final int index = users.indexOf(user); model.insertElementAt(user, index); } catch (Exception e) { Log.error(e); } } /** * Sorts ContactItems. */ final Comparator<JLabel> labelComp = new Comparator<JLabel>() { public int compare(JLabel item1, JLabel item2) { return item1.getText().toLowerCase().compareTo( item2.getText().toLowerCase()); } }; /** * The <code>JLabelIconRenderer</code> is the an implementation of * ListCellRenderer to add icons w/ associated text in JComboBox and JList. * * @author Derek DeMoro */ public class ParticipantRenderer extends JLabel implements ListCellRenderer { private static final long serialVersionUID = -7509947975798079141L; /** * Construct Default JLabelIconRenderer. */ public ParticipantRenderer() { setOpaque(true); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } JLabel label = (JLabel) value; setText(label.getText()); setIcon(label.getIcon()); return this; } } }
true
true
private void checkPopup(MouseEvent evt) { Point p = evt.getPoint(); final int index = participantsList.locationToIndex(p); final JPopupMenu popup = new JPopupMenu(); if (index != -1) { participantsList.setSelectedIndex(index); final JLabel userLabel = (JLabel) model.getElementAt(index); final String selectedUser = userLabel.getText(); final String groupJID = userMap.get(selectedUser); String groupJIDNickname = StringUtils.parseResource(groupJID); final String nickname = groupChatRoom.getNickname(); final Occupant occupant = userManager.getOccupant(groupChatRoom, selectedUser); final boolean admin = SparkManager.getUserManager().isOwnerOrAdmin( groupChatRoom, chat.getNickname()); final boolean moderator = SparkManager.getUserManager() .isModerator(groupChatRoom, chat.getNickname()); final boolean userIsAdmin = userManager.isOwnerOrAdmin(occupant); final boolean userIsModerator = userManager.isModerator(occupant); boolean isMe = nickname.equals(groupJIDNickname); // Handle invites if (groupJIDNickname == null) { Action inviteAgainAction = new AbstractAction() { private static final long serialVersionUID = -1875073139356098243L; public void actionPerformed(ActionEvent actionEvent) { String message = invitees.get(selectedUser); String jid = userManager .getJIDFromDisplayName(selectedUser); chat.invite(jid, message); } }; inviteAgainAction.putValue(Action.NAME, Res.getString("menuitem.inivite.again")); popup.add(inviteAgainAction); Action removeInvite = new AbstractAction() { private static final long serialVersionUID = -3647279452501661970L; public void actionPerformed(ActionEvent actionEvent) { int index = getIndex(selectedUser); if (index != -1) { model.removeElementAt(index); } } }; removeInvite.putValue(Action.NAME, Res.getString("menuitem.remove")); popup.add(removeInvite); popup.show(participantsList, evt.getX(), evt.getY()); return; } if (isMe) { Action changeNicknameAction = new AbstractAction() { private static final long serialVersionUID = -7891803180672794112L; public void actionPerformed(ActionEvent actionEvent) { String newNickname = JOptionPane.showInputDialog( groupChatRoom, Res .getString("label.new.nickname") + ":", Res .getString("title.change.nickname"), JOptionPane.QUESTION_MESSAGE); if (ModelUtil.hasLength(newNickname)) { while (true) { newNickname = newNickname.trim(); String nick = chat.getNickname(); if (newNickname.equals(nick)) { // return; } try { chat.changeNickname(newNickname); break; } catch (XMPPException e1) { newNickname = JOptionPane .showInputDialog( groupChatRoom, Res .getString("message.nickname.in.use") + ":", Res .getString("title.change.nickname"), JOptionPane.QUESTION_MESSAGE); if (!ModelUtil.hasLength(newNickname)) { break; } } } } } }; changeNicknameAction.putValue(Action.NAME, Res .getString("menuitem.change.nickname")); changeNicknameAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.DESKTOP_IMAGE)); if (allowNicknameChange) { popup.add(changeNicknameAction); } } Action chatAction = new AbstractAction() { private static final long serialVersionUID = -2739549054781928195L; public void actionPerformed(ActionEvent actionEvent) { String selectedUser = getSelectedUser(); startChat(groupChatRoom, userMap.get(selectedUser)); } }; chatAction.putValue(Action.NAME, Res .getString("menuitem.start.a.chat")); chatAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.SMALL_MESSAGE_IMAGE)); if (!isMe) { popup.add(chatAction); } Action blockAction = new AbstractAction() { private static final long serialVersionUID = 8771362206105723776L; public void actionPerformed(ActionEvent e) { String user = getSelectedUser(); ImageIcon icon; if (groupChatRoom.isBlocked(groupJID)) { groupChatRoom.removeBlockedUser(groupJID); icon = getImageIcon(groupJID); } else { groupChatRoom.addBlockedUser(groupJID); icon = SparkRes.getImageIcon(SparkRes.BRICKWALL_IMAGE); } JLabel label = new JLabel(user, icon, JLabel.HORIZONTAL); model.setElementAt(label, index); } }; blockAction.putValue(Action.NAME, Res .getString("menuitem.block.user")); blockAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.BRICKWALL_IMAGE)); if (!isMe) { if (groupChatRoom.isBlocked(groupJID)) { blockAction.putValue(Action.NAME, Res .getString("menuitem.unblock.user")); } popup.add(blockAction); } Action kickAction = new AbstractAction() { private static final long serialVersionUID = 5769982955040961189L; public void actionPerformed(ActionEvent actionEvent) { kickUser(selectedUser); } }; kickAction.putValue(Action.NAME, Res .getString("menuitem.kick.user")); kickAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.SMALL_DELETE)); if (moderator && !userIsAdmin && !isMe) { popup.add(kickAction); } // Handle Voice Operations Action voiceAction = new AbstractAction() { private static final long serialVersionUID = 7628207942009369329L; public void actionPerformed(ActionEvent actionEvent) { if (userManager.hasVoice(groupChatRoom, selectedUser)) { revokeVoice(selectedUser); } else { grantVoice(selectedUser); } } }; voiceAction.putValue(Action.NAME, Res.getString("menuitem.voice")); voiceAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.MEGAPHONE_16x16)); if (moderator && !userIsModerator && !isMe) { if (userManager.hasVoice(groupChatRoom, selectedUser)) { voiceAction.putValue(Action.NAME, Res .getString("menuitem.revoke.voice")); } else { voiceAction.putValue(Action.NAME, Res .getString("menuitem.grant.voice")); } popup.add(voiceAction); } Action banAction = new AbstractAction() { private static final long serialVersionUID = 4290194898356641253L; public void actionPerformed(ActionEvent actionEvent) { banUser(selectedUser); } }; banAction.putValue(Action.NAME, Res.getString("menuitem.ban.user")); banAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.RED_FLAG_16x16)); if (admin && !userIsModerator && !isMe) { popup.add(banAction); } Action moderatorAction = new AbstractAction() { private static final long serialVersionUID = 8162535640460764896L; public void actionPerformed(ActionEvent actionEvent) { if (!userIsModerator) { grantModerator(selectedUser); } else { revokeModerator(selectedUser); } } }; moderatorAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.MODERATOR_IMAGE)); if (admin && !userIsModerator) { moderatorAction.putValue(Action.NAME, Res .getString("menuitem.grant.moderator")); popup.add(moderatorAction); } else if (admin && userIsModerator && !isMe) { moderatorAction.putValue(Action.NAME, Res .getString("menuitem.revoke.moderator")); popup.add(moderatorAction); } // Handle Unbanning of users. Action unbanAction = new AbstractAction() { private static final long serialVersionUID = 3672121864443182872L; public void actionPerformed(ActionEvent actionEvent) { String jid = ((JMenuItem) actionEvent.getSource()) .getText(); unbanUser(jid); } }; if (admin) { JMenu unbanMenu = new JMenu(Res.getString("menuitem.unban")); Iterator<Affiliate> bannedUsers = null; try { bannedUsers = chat.getOutcasts().iterator(); } catch (XMPPException e) { Log.error("Error loading all banned users", e); } while (bannedUsers != null && bannedUsers.hasNext()) { Affiliate bannedUser = (Affiliate) bannedUsers.next(); ImageIcon icon = SparkRes.getImageIcon(SparkRes.RED_BALL); JMenuItem bannedItem = new JMenuItem(bannedUser.getJid(), icon); unbanMenu.add(bannedItem); bannedItem.addActionListener(unbanAction); } if (unbanMenu.getMenuComponentCount() > 0) { popup.add(unbanMenu); } } } Action inviteAction = new AbstractAction() { private static final long serialVersionUID = 2240864466141501086L; public void actionPerformed(ActionEvent actionEvent) { ConferenceUtils.inviteUsersToRoom(groupChatRoom .getConferenceService(), groupChatRoom.getRoomname(), null); } }; inviteAction.putValue(Action.NAME, Res .getString("menuitem.invite.users")); inviteAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.CONFERENCE_IMAGE_16x16)); if (index != -1) { popup.addSeparator(); } popup.add(inviteAction); popup.show(participantsList, evt.getX(), evt.getY()); }
private void checkPopup(MouseEvent evt) { Point p = evt.getPoint(); final int index = participantsList.locationToIndex(p); final JPopupMenu popup = new JPopupMenu(); if (index != -1) { participantsList.setSelectedIndex(index); final JLabel userLabel = (JLabel) model.getElementAt(index); final String selectedUser = userLabel.getText(); final String groupJID = userMap.get(selectedUser); String groupJIDNickname = StringUtils.parseResource(groupJID); final String nickname = groupChatRoom.getNickname(); final Occupant occupant = userManager.getOccupant(groupChatRoom, selectedUser); final boolean admin = SparkManager.getUserManager().isOwnerOrAdmin( groupChatRoom, chat.getNickname()); final boolean moderator = SparkManager.getUserManager() .isModerator(groupChatRoom, chat.getNickname()); final boolean userIsAdmin = userManager.isOwnerOrAdmin(occupant); final boolean userIsModerator = userManager.isModerator(occupant); boolean isMe = nickname.equals(groupJIDNickname); // Handle invites if (groupJIDNickname == null) { Action inviteAgainAction = new AbstractAction() { private static final long serialVersionUID = -1875073139356098243L; public void actionPerformed(ActionEvent actionEvent) { String message = invitees.get(selectedUser); String jid = userManager .getJIDFromDisplayName(selectedUser); chat.invite(jid, message); } }; inviteAgainAction.putValue(Action.NAME, Res.getString("menuitem.inivite.again")); popup.add(inviteAgainAction); Action removeInvite = new AbstractAction() { private static final long serialVersionUID = -3647279452501661970L; public void actionPerformed(ActionEvent actionEvent) { int index = getIndex(selectedUser); if (index != -1) { model.removeElementAt(index); } } }; removeInvite.putValue(Action.NAME, Res.getString("menuitem.remove")); popup.add(removeInvite); popup.show(participantsList, evt.getX(), evt.getY()); return; } if (isMe) { Action changeNicknameAction = new AbstractAction() { private static final long serialVersionUID = -7891803180672794112L; public void actionPerformed(ActionEvent actionEvent) { String newNickname = JOptionPane.showInputDialog( groupChatRoom, Res .getString("label.new.nickname") + ":", Res .getString("title.change.nickname"), JOptionPane.QUESTION_MESSAGE); if (ModelUtil.hasLength(newNickname)) { while (true) { newNickname = newNickname.trim(); String nick = chat.getNickname(); if (newNickname.equals(nick)) { // return; } try { chat.changeNickname(newNickname); break; } catch (XMPPException e1) { if (e1.getXMPPError().getCode() == 406) { //handle deny changing nick JOptionPane.showMessageDialog(groupChatRoom, Res.getString("message.nickname.not.acceptable"), Res.getString("title.change.nickname"), JOptionPane.ERROR_MESSAGE); break; } newNickname = JOptionPane .showInputDialog( groupChatRoom, Res .getString("message.nickname.in.use") + ":", Res .getString("title.change.nickname"), JOptionPane.QUESTION_MESSAGE); if (!ModelUtil.hasLength(newNickname)) { break; } } } } } }; changeNicknameAction.putValue(Action.NAME, Res .getString("menuitem.change.nickname")); changeNicknameAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.DESKTOP_IMAGE)); if (allowNicknameChange) { popup.add(changeNicknameAction); } } Action chatAction = new AbstractAction() { private static final long serialVersionUID = -2739549054781928195L; public void actionPerformed(ActionEvent actionEvent) { String selectedUser = getSelectedUser(); startChat(groupChatRoom, userMap.get(selectedUser)); } }; chatAction.putValue(Action.NAME, Res .getString("menuitem.start.a.chat")); chatAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.SMALL_MESSAGE_IMAGE)); if (!isMe) { popup.add(chatAction); } Action blockAction = new AbstractAction() { private static final long serialVersionUID = 8771362206105723776L; public void actionPerformed(ActionEvent e) { String user = getSelectedUser(); ImageIcon icon; if (groupChatRoom.isBlocked(groupJID)) { groupChatRoom.removeBlockedUser(groupJID); icon = getImageIcon(groupJID); } else { groupChatRoom.addBlockedUser(groupJID); icon = SparkRes.getImageIcon(SparkRes.BRICKWALL_IMAGE); } JLabel label = new JLabel(user, icon, JLabel.HORIZONTAL); model.setElementAt(label, index); } }; blockAction.putValue(Action.NAME, Res .getString("menuitem.block.user")); blockAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.BRICKWALL_IMAGE)); if (!isMe) { if (groupChatRoom.isBlocked(groupJID)) { blockAction.putValue(Action.NAME, Res .getString("menuitem.unblock.user")); } popup.add(blockAction); } Action kickAction = new AbstractAction() { private static final long serialVersionUID = 5769982955040961189L; public void actionPerformed(ActionEvent actionEvent) { kickUser(selectedUser); } }; kickAction.putValue(Action.NAME, Res .getString("menuitem.kick.user")); kickAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.SMALL_DELETE)); if (moderator && !userIsAdmin && !isMe) { popup.add(kickAction); } // Handle Voice Operations Action voiceAction = new AbstractAction() { private static final long serialVersionUID = 7628207942009369329L; public void actionPerformed(ActionEvent actionEvent) { if (userManager.hasVoice(groupChatRoom, selectedUser)) { revokeVoice(selectedUser); } else { grantVoice(selectedUser); } } }; voiceAction.putValue(Action.NAME, Res.getString("menuitem.voice")); voiceAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.MEGAPHONE_16x16)); if (moderator && !userIsModerator && !isMe) { if (userManager.hasVoice(groupChatRoom, selectedUser)) { voiceAction.putValue(Action.NAME, Res .getString("menuitem.revoke.voice")); } else { voiceAction.putValue(Action.NAME, Res .getString("menuitem.grant.voice")); } popup.add(voiceAction); } Action banAction = new AbstractAction() { private static final long serialVersionUID = 4290194898356641253L; public void actionPerformed(ActionEvent actionEvent) { banUser(selectedUser); } }; banAction.putValue(Action.NAME, Res.getString("menuitem.ban.user")); banAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.RED_FLAG_16x16)); if (admin && !userIsModerator && !isMe) { popup.add(banAction); } Action moderatorAction = new AbstractAction() { private static final long serialVersionUID = 8162535640460764896L; public void actionPerformed(ActionEvent actionEvent) { if (!userIsModerator) { grantModerator(selectedUser); } else { revokeModerator(selectedUser); } } }; moderatorAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.MODERATOR_IMAGE)); if (admin && !userIsModerator) { moderatorAction.putValue(Action.NAME, Res .getString("menuitem.grant.moderator")); popup.add(moderatorAction); } else if (admin && userIsModerator && !isMe) { moderatorAction.putValue(Action.NAME, Res .getString("menuitem.revoke.moderator")); popup.add(moderatorAction); } // Handle Unbanning of users. Action unbanAction = new AbstractAction() { private static final long serialVersionUID = 3672121864443182872L; public void actionPerformed(ActionEvent actionEvent) { String jid = ((JMenuItem) actionEvent.getSource()) .getText(); unbanUser(jid); } }; if (admin) { JMenu unbanMenu = new JMenu(Res.getString("menuitem.unban")); Iterator<Affiliate> bannedUsers = null; try { bannedUsers = chat.getOutcasts().iterator(); } catch (XMPPException e) { Log.error("Error loading all banned users", e); } while (bannedUsers != null && bannedUsers.hasNext()) { Affiliate bannedUser = (Affiliate) bannedUsers.next(); ImageIcon icon = SparkRes.getImageIcon(SparkRes.RED_BALL); JMenuItem bannedItem = new JMenuItem(bannedUser.getJid(), icon); unbanMenu.add(bannedItem); bannedItem.addActionListener(unbanAction); } if (unbanMenu.getMenuComponentCount() > 0) { popup.add(unbanMenu); } } } Action inviteAction = new AbstractAction() { private static final long serialVersionUID = 2240864466141501086L; public void actionPerformed(ActionEvent actionEvent) { ConferenceUtils.inviteUsersToRoom(groupChatRoom .getConferenceService(), groupChatRoom.getRoomname(), null); } }; inviteAction.putValue(Action.NAME, Res .getString("menuitem.invite.users")); inviteAction.putValue(Action.SMALL_ICON, SparkRes .getImageIcon(SparkRes.CONFERENCE_IMAGE_16x16)); if (index != -1) { popup.addSeparator(); } popup.add(inviteAction); popup.show(participantsList, evt.getX(), evt.getY()); }
diff --git a/gdx/src/com/badlogic/gdx/utils/GdxBuild.java b/gdx/src/com/badlogic/gdx/utils/GdxBuild.java index c4359b8bf..b5b3e9442 100644 --- a/gdx/src/com/badlogic/gdx/utils/GdxBuild.java +++ b/gdx/src/com/badlogic/gdx/utils/GdxBuild.java @@ -1,48 +1,48 @@ package com.badlogic.gdx.utils; import com.badlogic.gdx.jnigen.AntScriptGenerator; import com.badlogic.gdx.jnigen.BuildConfig; import com.badlogic.gdx.jnigen.BuildExecutor; import com.badlogic.gdx.jnigen.BuildTarget; import com.badlogic.gdx.jnigen.NativeCodeGenerator; import com.badlogic.gdx.jnigen.SharedLibraryLoader; import com.badlogic.gdx.jnigen.BuildTarget.TargetOs; /** * Builds the JNI wrappers via gdx-jnigen. * @author mzechner * */ public class GdxBuild { public static void main(String[] args) throws Exception { String JNI_DIR = "jni-new"; String LIBS_DIR = "libs-new"; // MD5Jni String[] includes = { "**/MD5Jni.java" }; new NativeCodeGenerator().generate("src", "bin", JNI_DIR + "/", includes, null); // Matrix4 includes = new String[] { "**/Matrix4.java" }; new NativeCodeGenerator().generate("src", "bin", JNI_DIR + "/", includes, null); // ETC1 includes = new String[] { "**/ETC1.java" }; new NativeCodeGenerator().generate("src", "bin", JNI_DIR + "/etc1/", includes, null); // GDX2D includes = new String[] { "**/Gdx2DPixmap.java" }; new NativeCodeGenerator().generate("src", "bin", JNI_DIR + "/gdx2d/", includes, null); // build String[] headerDirs = { "./", "etc1/", "gdx2d/" }; - BuildConfig config = new BuildConfig("gdx", "native", LIBS_DIR, JNI_DIR); + BuildConfig config = new BuildConfig("gdx", "../target/native", LIBS_DIR, JNI_DIR); BuildTarget target = BuildTarget.newDefaultTarget(TargetOs.Windows, false); target.compilerPrefix = ""; target.excludeFromMasterBuildFile = true; target.headerDirs = headerDirs; new AntScriptGenerator().generate(config, target); BuildExecutor.executeAnt(JNI_DIR + "/build-windows32.xml", "clean link -v"); } }
true
true
public static void main(String[] args) throws Exception { String JNI_DIR = "jni-new"; String LIBS_DIR = "libs-new"; // MD5Jni String[] includes = { "**/MD5Jni.java" }; new NativeCodeGenerator().generate("src", "bin", JNI_DIR + "/", includes, null); // Matrix4 includes = new String[] { "**/Matrix4.java" }; new NativeCodeGenerator().generate("src", "bin", JNI_DIR + "/", includes, null); // ETC1 includes = new String[] { "**/ETC1.java" }; new NativeCodeGenerator().generate("src", "bin", JNI_DIR + "/etc1/", includes, null); // GDX2D includes = new String[] { "**/Gdx2DPixmap.java" }; new NativeCodeGenerator().generate("src", "bin", JNI_DIR + "/gdx2d/", includes, null); // build String[] headerDirs = { "./", "etc1/", "gdx2d/" }; BuildConfig config = new BuildConfig("gdx", "native", LIBS_DIR, JNI_DIR); BuildTarget target = BuildTarget.newDefaultTarget(TargetOs.Windows, false); target.compilerPrefix = ""; target.excludeFromMasterBuildFile = true; target.headerDirs = headerDirs; new AntScriptGenerator().generate(config, target); BuildExecutor.executeAnt(JNI_DIR + "/build-windows32.xml", "clean link -v"); }
public static void main(String[] args) throws Exception { String JNI_DIR = "jni-new"; String LIBS_DIR = "libs-new"; // MD5Jni String[] includes = { "**/MD5Jni.java" }; new NativeCodeGenerator().generate("src", "bin", JNI_DIR + "/", includes, null); // Matrix4 includes = new String[] { "**/Matrix4.java" }; new NativeCodeGenerator().generate("src", "bin", JNI_DIR + "/", includes, null); // ETC1 includes = new String[] { "**/ETC1.java" }; new NativeCodeGenerator().generate("src", "bin", JNI_DIR + "/etc1/", includes, null); // GDX2D includes = new String[] { "**/Gdx2DPixmap.java" }; new NativeCodeGenerator().generate("src", "bin", JNI_DIR + "/gdx2d/", includes, null); // build String[] headerDirs = { "./", "etc1/", "gdx2d/" }; BuildConfig config = new BuildConfig("gdx", "../target/native", LIBS_DIR, JNI_DIR); BuildTarget target = BuildTarget.newDefaultTarget(TargetOs.Windows, false); target.compilerPrefix = ""; target.excludeFromMasterBuildFile = true; target.headerDirs = headerDirs; new AntScriptGenerator().generate(config, target); BuildExecutor.executeAnt(JNI_DIR + "/build-windows32.xml", "clean link -v"); }
diff --git a/module-nio/src/test/java/org/apache/http/nio/protocol/TestNIOHttp.java b/module-nio/src/test/java/org/apache/http/nio/protocol/TestNIOHttp.java index d7671746a..8a6ac4c50 100644 --- a/module-nio/src/test/java/org/apache/http/nio/protocol/TestNIOHttp.java +++ b/module-nio/src/test/java/org/apache/http/nio/protocol/TestNIOHttp.java @@ -1,1297 +1,1297 @@ /* * $HeadURL$ * $Revision$ * $Date$ * ==================================================================== * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.nio.protocol; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Random; import junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpRequest; import org.apache.http.nio.NHttpClientHandler; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.mockup.CountingEventListener; import org.apache.http.nio.mockup.SimpleHttpRequestHandlerResolver; import org.apache.http.nio.mockup.SimpleThreadPoolExecutor; import org.apache.http.nio.mockup.TestHttpClient; import org.apache.http.nio.mockup.TestHttpServer; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.BasicHttpProcessor; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpExecutionContext; import org.apache.http.protocol.HttpExpectationVerifier; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.protocol.RequestConnControl; import org.apache.http.protocol.RequestContent; import org.apache.http.protocol.RequestExpectContinue; import org.apache.http.protocol.RequestTargetHost; import org.apache.http.protocol.RequestUserAgent; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseServer; import org.apache.http.util.EncodingUtils; import org.apache.http.util.EntityUtils; /** * HttpCore NIO integration tests. * * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a> * * @version $Id$ */ public class TestNIOHttp extends TestCase { private static final int MODE_BUFFERING = 0; private static final int MODE_THROTTLING = 1; private int clientMode = MODE_BUFFERING; private int serverMode = MODE_BUFFERING; // ------------------------------------------------------------ Constructor public TestNIOHttp(String testName) { super(testName); } public int getClientMode() { return this.clientMode; } public void setClientMode(int clientMode) { this.clientMode = clientMode; } public int getServerMode() { return this.serverMode; } public void setServerMode(int serverMode) { this.serverMode = serverMode; } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestNIOHttp.class.getName() }; junit.textui.TestRunner.main(testCaseName); } static class ServerModeDecorator extends TestSetup { private int mode; public ServerModeDecorator(final TestNIOHttp test, int mode) { super(test); this.mode = mode; } protected void setUp() throws Exception { TestNIOHttp testcase = (TestNIOHttp)getTest(); testcase.setServerMode(this.mode); } } // ------------------------------------------------------- TestCase Methods public static Test suite() { TestSuite source = new TestSuite(TestNIOHttp.class); TestSuite suite = new TestSuite(); for (Enumeration en = source.tests(); en.hasMoreElements(); ) { TestNIOHttp test = (TestNIOHttp) en.nextElement(); suite.addTest(new ServerModeDecorator(test, MODE_BUFFERING)); } for (Enumeration en = source.tests(); en.hasMoreElements(); ) { TestNIOHttp test = (TestNIOHttp) en.nextElement(); suite.addTest(new ServerModeDecorator(test, MODE_THROTTLING)); } return suite; } private TestHttpServer server; private TestHttpClient client; private SimpleThreadPoolExecutor executor; protected void setUp() throws Exception { HttpParams serverParams = new BasicHttpParams(); serverParams .setIntParameter(HttpConnectionParams.SO_TIMEOUT, 2000) .setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false) .setBooleanParameter(HttpConnectionParams.TCP_NODELAY, true) .setParameter(HttpProtocolParams.ORIGIN_SERVER, "TEST-SERVER/1.1"); this.server = new TestHttpServer(serverParams); HttpParams clientParams = new BasicHttpParams(); clientParams .setIntParameter(HttpConnectionParams.SO_TIMEOUT, 2000) .setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 2000) .setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false) .setBooleanParameter(HttpConnectionParams.TCP_NODELAY, true) .setParameter(HttpProtocolParams.USER_AGENT, "TEST-CLIENT/1.1"); this.client = new TestHttpClient(clientParams); this.executor = new SimpleThreadPoolExecutor(); } protected void tearDown() throws Exception { this.executor.shutdown(); this.server.shutdown(); this.client.shutdown(); } private NHttpServiceHandler createHttpServiceHandler( final HttpRequestHandler requestHandler, final HttpExpectationVerifier expectationVerifier, final EventListener eventListener) { BasicHttpProcessor httpproc = new BasicHttpProcessor(); httpproc.addInterceptor(new ResponseDate()); httpproc.addInterceptor(new ResponseServer()); httpproc.addInterceptor(new ResponseContent()); httpproc.addInterceptor(new ResponseConnControl()); if (this.serverMode == MODE_BUFFERING) { BufferingHttpServiceHandler serviceHandler = new BufferingHttpServiceHandler( httpproc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), this.server.getParams()); serviceHandler.setHandlerResolver( new SimpleHttpRequestHandlerResolver(requestHandler)); serviceHandler.setExpectationVerifier(expectationVerifier); serviceHandler.setEventListener(eventListener); return serviceHandler; } if (this.serverMode == MODE_THROTTLING) { ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler( httpproc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), this.executor, this.server.getParams()); serviceHandler.setHandlerResolver( new SimpleHttpRequestHandlerResolver(requestHandler)); serviceHandler.setExpectationVerifier(expectationVerifier); serviceHandler.setEventListener(eventListener); return serviceHandler; } throw new IllegalStateException(); } private NHttpClientHandler createHttpClientHandler( final HttpRequestExecutionHandler requestExecutionHandler, final EventListener eventListener) { BasicHttpProcessor httpproc = new BasicHttpProcessor(); httpproc.addInterceptor(new RequestContent()); httpproc.addInterceptor(new RequestTargetHost()); httpproc.addInterceptor(new RequestConnControl()); httpproc.addInterceptor(new RequestUserAgent()); httpproc.addInterceptor(new RequestExpectContinue()); BufferingHttpClientHandler clientHandler = new BufferingHttpClientHandler( httpproc, requestExecutionHandler, new DefaultConnectionReuseStrategy(), this.client.getParams()); clientHandler.setEventListener(eventListener); return clientHandler; } /** * This test case executes a series of simple (non-pipelined) GET requests * over multiple connections. */ public void testSimpleHttpGets() throws Exception { final int connNo = 3; final int reqNo = 20; Random rnd = new Random(); // Prepare some random data final List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } List[] responseData = new List[connNo]; for (int i = 0; i < responseData.length; i++) { responseData[i] = new ArrayList(); } HttpRequestHandler requestHandler = new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String s = request.getRequestLine().getUri(); URI uri; try { uri = new URI(s); } catch (URISyntaxException ex) { throw new HttpException("Invalid request URI: " + s); } int index = Integer.parseInt(uri.getQuery()); byte[] data = (byte []) testData.get(index); ByteArrayEntity entity = new ByteArrayEntity(data); response.setEntity(entity); } }; HttpRequestExecutionHandler requestExecutionHandler = new HttpRequestExecutionHandler() { public void initalizeContext(final HttpContext context, final Object attachment) { context.setAttribute("LIST", (List) attachment); context.setAttribute("REQ-COUNT", new Integer(0)); context.setAttribute("RES-COUNT", new Integer(0)); } public HttpRequest submitRequest(final HttpContext context) { int i = ((Integer) context.getAttribute("REQ-COUNT")).intValue(); BasicHttpRequest get = null; if (i < reqNo) { get = new BasicHttpRequest("GET", "/?" + i); context.setAttribute("REQ-COUNT", new Integer(i + 1)); } return get; } public void handleResponse(final HttpResponse response, final HttpContext context) { NHttpConnection conn = (NHttpConnection) context.getAttribute( HttpExecutionContext.HTTP_CONNECTION); List list = (List) context.getAttribute("LIST"); int i = ((Integer) context.getAttribute("RES-COUNT")).intValue(); i++; context.setAttribute("RES-COUNT", new Integer(i)); try { HttpEntity entity = response.getEntity(); byte[] data = EntityUtils.toByteArray(entity); list.add(data); } catch (IOException ex) { fail(ex.getMessage()); } if (i < reqNo) { conn.requestInput(); } else { try { conn.close(); } catch (IOException ex) { fail(ex.getMessage()); } } } }; CountingEventListener serverEventListener = new CountingEventListener(); CountingEventListener clientEventListener = new CountingEventListener(); NHttpServiceHandler serviceHandler = createHttpServiceHandler( requestHandler, null, serverEventListener); NHttpClientHandler clientHandler = createHttpClientHandler( requestExecutionHandler, clientEventListener); this.server.start(serviceHandler); this.client.start(clientHandler); InetSocketAddress serverAddress = (InetSocketAddress) this.server.getSocketAddress(); for (int i = 0; i < responseData.length; i++) { this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), responseData[i]); } clientEventListener.await(connNo, 1000); assertEquals(connNo, clientEventListener.getConnCount()); this.client.shutdown(); this.server.shutdown(); for (int c = 0; c < responseData.length; c++) { List receivedPackets = responseData[c]; List expectedPackets = testData; assertEquals(expectedPackets.size(), receivedPackets.size()); for (int p = 0; p < testData.size(); p++) { byte[] expected = (byte[]) testData.get(p); byte[] received = (byte[]) receivedPackets.get(p); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } } } } /** * This test case executes a series of simple (non-pipelined) POST requests * with content length delimited content over multiple connections. */ public void testSimpleHttpPostsWithContentLength() throws Exception { final int connNo = 3; final int reqNo = 20; Random rnd = new Random(); // Prepare some random data final List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } List[] responseData = new List[connNo]; for (int i = 0; i < responseData.length; i++) { responseData[i] = new ArrayList(); } HttpRequestHandler requestHandler = new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(false); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }; HttpRequestExecutionHandler requestExecutionHandler = new HttpRequestExecutionHandler() { public void initalizeContext(final HttpContext context, final Object attachment) { context.setAttribute("LIST", (List) attachment); context.setAttribute("REQ-COUNT", new Integer(0)); context.setAttribute("RES-COUNT", new Integer(0)); } public HttpRequest submitRequest(final HttpContext context) { int i = ((Integer) context.getAttribute("REQ-COUNT")).intValue(); BasicHttpEntityEnclosingRequest post = null; if (i < reqNo) { post = new BasicHttpEntityEnclosingRequest("POST", "/?" + i); byte[] data = (byte[]) testData.get(i); ByteArrayEntity outgoing = new ByteArrayEntity(data); post.setEntity(outgoing); context.setAttribute("REQ-COUNT", new Integer(i + 1)); } return post; } public void handleResponse(final HttpResponse response, final HttpContext context) { NHttpConnection conn = (NHttpConnection) context.getAttribute( HttpExecutionContext.HTTP_CONNECTION); List list = (List) context.getAttribute("LIST"); int i = ((Integer) context.getAttribute("RES-COUNT")).intValue(); i++; context.setAttribute("RES-COUNT", new Integer(i)); try { HttpEntity entity = response.getEntity(); byte[] data = EntityUtils.toByteArray(entity); list.add(data); } catch (IOException ex) { fail(ex.getMessage()); } if (i < reqNo) { conn.requestInput(); } else { try { conn.close(); } catch (IOException ex) { fail(ex.getMessage()); } } } }; CountingEventListener serverEventListener = new CountingEventListener(); CountingEventListener clientEventListener = new CountingEventListener(); NHttpServiceHandler serviceHandler = createHttpServiceHandler( requestHandler, null, serverEventListener); NHttpClientHandler clientHandler = createHttpClientHandler( requestExecutionHandler, clientEventListener); this.server.start(serviceHandler); this.client.start(clientHandler); InetSocketAddress serverAddress = (InetSocketAddress) this.server.getSocketAddress(); for (int i = 0; i < responseData.length; i++) { this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), responseData[i]); } clientEventListener.await(connNo, 1000); assertEquals(connNo, clientEventListener.getConnCount()); this.client.shutdown(); this.server.shutdown(); for (int c = 0; c < responseData.length; c++) { List receivedPackets = responseData[c]; List expectedPackets = testData; assertEquals(expectedPackets.size(), receivedPackets.size()); for (int p = 0; p < testData.size(); p++) { byte[] expected = (byte[]) testData.get(p); byte[] received = (byte[]) receivedPackets.get(p); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } } } } /** * This test case executes a series of simple (non-pipelined) POST requests * with chunk coded content content over multiple connections. */ public void testSimpleHttpPostsChunked() throws Exception { final int connNo = 3; final int reqNo = 20; Random rnd = new Random(); // Prepare some random data final List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(20000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } List[] responseData = new List[connNo]; for (int i = 0; i < responseData.length; i++) { responseData[i] = new ArrayList(); } HttpRequestHandler requestHandler = new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }; HttpRequestExecutionHandler requestExecutionHandler = new HttpRequestExecutionHandler() { public void initalizeContext(final HttpContext context, final Object attachment) { context.setAttribute("LIST", (List) attachment); context.setAttribute("REQ-COUNT", new Integer(0)); context.setAttribute("RES-COUNT", new Integer(0)); } public HttpRequest submitRequest(final HttpContext context) { int i = ((Integer) context.getAttribute("REQ-COUNT")).intValue(); BasicHttpEntityEnclosingRequest post = null; if (i < reqNo) { post = new BasicHttpEntityEnclosingRequest("POST", "/?" + i); byte[] data = (byte[]) testData.get(i); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); post.setEntity(outgoing); context.setAttribute("REQ-COUNT", new Integer(i + 1)); } return post; } public void handleResponse(final HttpResponse response, final HttpContext context) { NHttpConnection conn = (NHttpConnection) context.getAttribute( HttpExecutionContext.HTTP_CONNECTION); List list = (List) context.getAttribute("LIST"); int i = ((Integer) context.getAttribute("RES-COUNT")).intValue(); i++; context.setAttribute("RES-COUNT", new Integer(i)); try { HttpEntity entity = response.getEntity(); byte[] data = EntityUtils.toByteArray(entity); list.add(data); } catch (IOException ex) { fail(ex.getMessage()); } if (i < reqNo) { conn.requestInput(); } else { try { conn.close(); } catch (IOException ex) { fail(ex.getMessage()); } } } }; CountingEventListener serverEventListener = new CountingEventListener(); CountingEventListener clientEventListener = new CountingEventListener(); NHttpServiceHandler serviceHandler = createHttpServiceHandler( requestHandler, null, serverEventListener); NHttpClientHandler clientHandler = createHttpClientHandler( requestExecutionHandler, clientEventListener); this.server.start(serviceHandler); this.client.start(clientHandler); InetSocketAddress serverAddress = (InetSocketAddress) this.server.getSocketAddress(); for (int i = 0; i < responseData.length; i++) { this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), responseData[i]); } clientEventListener.await(connNo, 1000); assertEquals(connNo, clientEventListener.getConnCount()); this.client.shutdown(); this.server.shutdown(); for (int c = 0; c < responseData.length; c++) { List receivedPackets = responseData[c]; List expectedPackets = testData; assertEquals(expectedPackets.size(), receivedPackets.size()); for (int p = 0; p < testData.size(); p++) { byte[] expected = (byte[]) testData.get(p); byte[] received = (byte[]) receivedPackets.get(p); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } } } } /** * This test case executes a series of simple (non-pipelined) HTTP/1.0 * POST requests over multiple persistent connections. */ public void testSimpleHttpPostsHTTP10() throws Exception { final int connNo = 3; final int reqNo = 20; Random rnd = new Random(); // Prepare some random data final List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } List[] responseData = new List[connNo]; for (int i = 0; i < responseData.length; i++) { responseData[i] = new ArrayList(); } HttpRequestHandler requestHandler = new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(false); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }; // Set protocol level to HTTP/1.0 this.client.getParams().setParameter( HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_0); HttpRequestExecutionHandler requestExecutionHandler = new HttpRequestExecutionHandler() { public void initalizeContext(final HttpContext context, final Object attachment) { context.setAttribute("LIST", (List) attachment); context.setAttribute("REQ-COUNT", new Integer(0)); context.setAttribute("RES-COUNT", new Integer(0)); } public HttpRequest submitRequest(final HttpContext context) { int i = ((Integer) context.getAttribute("REQ-COUNT")).intValue(); BasicHttpEntityEnclosingRequest post = null; if (i < reqNo) { post = new BasicHttpEntityEnclosingRequest("POST", "/?" + i); byte[] data = (byte[]) testData.get(i); ByteArrayEntity outgoing = new ByteArrayEntity(data); post.setEntity(outgoing); context.setAttribute("REQ-COUNT", new Integer(i + 1)); } return post; } public void handleResponse(final HttpResponse response, final HttpContext context) { NHttpConnection conn = (NHttpConnection) context.getAttribute( HttpExecutionContext.HTTP_CONNECTION); List list = (List) context.getAttribute("LIST"); int i = ((Integer) context.getAttribute("RES-COUNT")).intValue(); i++; context.setAttribute("RES-COUNT", new Integer(i)); try { HttpEntity entity = response.getEntity(); byte[] data = EntityUtils.toByteArray(entity); list.add(data); } catch (IOException ex) { fail(ex.getMessage()); } if (i < reqNo) { conn.requestInput(); } else { try { conn.close(); } catch (IOException ex) { fail(ex.getMessage()); } } } }; CountingEventListener serverEventListener = new CountingEventListener(); CountingEventListener clientEventListener = new CountingEventListener(); NHttpServiceHandler serviceHandler = createHttpServiceHandler( requestHandler, null, serverEventListener); NHttpClientHandler clientHandler = createHttpClientHandler( requestExecutionHandler, clientEventListener); this.server.start(serviceHandler); this.client.start(clientHandler); InetSocketAddress serverAddress = (InetSocketAddress) this.server.getSocketAddress(); for (int i = 0; i < responseData.length; i++) { this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), responseData[i]); } clientEventListener.await(connNo, 1000); assertEquals(connNo, clientEventListener.getConnCount()); this.client.shutdown(); this.server.shutdown(); for (int c = 0; c < responseData.length; c++) { List receivedPackets = responseData[c]; List expectedPackets = testData; assertEquals(expectedPackets.size(), receivedPackets.size()); for (int p = 0; p < testData.size(); p++) { byte[] expected = (byte[]) testData.get(p); byte[] received = (byte[]) receivedPackets.get(p); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } } } } /** * This test case executes a series of simple (non-pipelined) POST requests * over multiple connections using the 'expect: continue' handshake. */ public void testHttpPostsWithExpectContinue() throws Exception { final int connNo = 3; final int reqNo = 20; Random rnd = new Random(); // Prepare some random data final List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(20000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } List[] responseData = new List[connNo]; for (int i = 0; i < responseData.length; i++) { responseData[i] = new ArrayList(); } HttpRequestHandler requestHandler = new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }; // Activate 'expect: continue' handshake this.client.getParams().setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true); HttpRequestExecutionHandler requestExecutionHandler = new HttpRequestExecutionHandler() { public void initalizeContext(final HttpContext context, final Object attachment) { context.setAttribute("LIST", (List) attachment); context.setAttribute("REQ-COUNT", new Integer(0)); context.setAttribute("RES-COUNT", new Integer(0)); } public HttpRequest submitRequest(final HttpContext context) { int i = ((Integer) context.getAttribute("REQ-COUNT")).intValue(); BasicHttpEntityEnclosingRequest post = null; if (i < reqNo) { post = new BasicHttpEntityEnclosingRequest("POST", "/?" + i); byte[] data = (byte[]) testData.get(i); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); post.setEntity(outgoing); context.setAttribute("REQ-COUNT", new Integer(i + 1)); } return post; } public void handleResponse(final HttpResponse response, final HttpContext context) { NHttpConnection conn = (NHttpConnection) context.getAttribute( HttpExecutionContext.HTTP_CONNECTION); List list = (List) context.getAttribute("LIST"); int i = ((Integer) context.getAttribute("RES-COUNT")).intValue(); i++; context.setAttribute("RES-COUNT", new Integer(i)); try { HttpEntity entity = response.getEntity(); byte[] data = EntityUtils.toByteArray(entity); list.add(data); } catch (IOException ex) { fail(ex.getMessage()); } if (i < reqNo) { conn.requestInput(); } else { try { conn.close(); } catch (IOException ex) { fail(ex.getMessage()); } } } }; CountingEventListener serverEventListener = new CountingEventListener(); CountingEventListener clientEventListener = new CountingEventListener(); NHttpServiceHandler serviceHandler = createHttpServiceHandler( requestHandler, null, serverEventListener); NHttpClientHandler clientHandler = createHttpClientHandler( requestExecutionHandler, clientEventListener); this.server.start(serviceHandler); this.client.start(clientHandler); InetSocketAddress serverAddress = (InetSocketAddress) this.server.getSocketAddress(); for (int i = 0; i < responseData.length; i++) { this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), responseData[i]); } clientEventListener.await(connNo, 1000); assertEquals(connNo, clientEventListener.getConnCount()); this.client.shutdown(); this.server.shutdown(); for (int c = 0; c < responseData.length; c++) { List receivedPackets = responseData[c]; List expectedPackets = testData; assertEquals(expectedPackets.size(), receivedPackets.size()); for (int p = 0; p < testData.size(); p++) { byte[] expected = (byte[]) testData.get(p); byte[] received = (byte[]) receivedPackets.get(p); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } } } } /** * This test case executes a series of simple (non-pipelined) POST requests * over multiple connections that do not meet the target server expectations. */ public void testHttpPostsWithExpectationVerification() throws Exception { final int reqNo = 3; final List responses = new ArrayList(reqNo); HttpRequestHandler requestHandler = new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } }; HttpExpectationVerifier expectationVerifier = new HttpExpectationVerifier() { public void verify( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException { Header someheader = request.getFirstHeader("Secret"); if (someheader != null) { int secretNumber; try { secretNumber = Integer.parseInt(someheader.getValue()); } catch (NumberFormatException ex) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); return; } if (secretNumber < 2) { response.setStatusCode(HttpStatus.SC_EXPECTATION_FAILED); ByteArrayEntity outgoing = new ByteArrayEntity( EncodingUtils.getAsciiBytes("Wrong secret number")); response.setEntity(outgoing); } } } }; // Activate 'expect: continue' handshake this.client.getParams().setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true); HttpRequestExecutionHandler requestExecutionHandler = new HttpRequestExecutionHandler() { public void initalizeContext(final HttpContext context, final Object attachment) { context.setAttribute("LIST", (List) attachment); context.setAttribute("REQ-COUNT", new Integer(0)); context.setAttribute("RES-COUNT", new Integer(0)); } public HttpRequest submitRequest(final HttpContext context) { int i = ((Integer) context.getAttribute("REQ-COUNT")).intValue(); BasicHttpEntityEnclosingRequest post = null; if (i < reqNo) { post = new BasicHttpEntityEnclosingRequest("POST", "/"); post.addHeader("Secret", Integer.toString(i)); ByteArrayEntity outgoing = new ByteArrayEntity( EncodingUtils.getAsciiBytes("No content")); post.setEntity(outgoing); context.setAttribute("REQ-COUNT", new Integer(i + 1)); } return post; } public void handleResponse(final HttpResponse response, final HttpContext context) { NHttpConnection conn = (NHttpConnection) context.getAttribute( HttpExecutionContext.HTTP_CONNECTION); List list = (List) context.getAttribute("LIST"); int i = ((Integer) context.getAttribute("RES-COUNT")).intValue(); i++; context.setAttribute("RES-COUNT", new Integer(i)); HttpEntity entity = response.getEntity(); if (entity != null) { try { entity.consumeContent(); } catch (IOException ex) { fail(ex.getMessage()); } } list.add(response); if (i < reqNo) { conn.requestInput(); } else { try { conn.close(); } catch (IOException ex) { fail(ex.getMessage()); } } } }; CountingEventListener serverEventListener = new CountingEventListener(); CountingEventListener clientEventListener = new CountingEventListener(); NHttpServiceHandler serviceHandler = createHttpServiceHandler( requestHandler, expectationVerifier, serverEventListener); NHttpClientHandler clientHandler = createHttpClientHandler( requestExecutionHandler, clientEventListener); this.server.start(serviceHandler); this.client.start(clientHandler); InetSocketAddress serverAddress = (InetSocketAddress) this.server.getSocketAddress(); this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), responses); clientEventListener.await(1, 1000); this.client.shutdown(); this.server.shutdown(); assertEquals(reqNo, responses.size()); HttpResponse response = (HttpResponse) responses.get(0); assertEquals(HttpStatus.SC_EXPECTATION_FAILED, response.getStatusLine().getStatusCode()); response = (HttpResponse) responses.get(1); assertEquals(HttpStatus.SC_EXPECTATION_FAILED, response.getStatusLine().getStatusCode()); response = (HttpResponse) responses.get(2); assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } /** * This test case executes a series of simple (non-pipelined) HEAD requests * over multiple connections. */ public void testSimpleHttpHeads() throws Exception { final int connNo = 3; final int reqNo = 20; final String[] method = new String[1]; Random rnd = new Random(); // Prepare some random data final List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } List[] responseData = new List[connNo]; for (int i = 0; i < responseData.length; i++) { responseData[i] = new ArrayList(); } HttpRequestHandler requestHandler = new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String s = request.getRequestLine().getUri(); URI uri; try { uri = new URI(s); } catch (URISyntaxException ex) { throw new HttpException("Invalid request URI: " + s); } int index = Integer.parseInt(uri.getQuery()); byte[] data = (byte []) testData.get(index); ByteArrayEntity entity = new ByteArrayEntity(data); response.setEntity(entity); } }; HttpRequestExecutionHandler requestExecutionHandler = new HttpRequestExecutionHandler() { public void initalizeContext(final HttpContext context, final Object attachment) { context.setAttribute("LIST", (List) attachment); context.setAttribute("REQ-COUNT", new Integer(0)); context.setAttribute("RES-COUNT", new Integer(0)); } public HttpRequest submitRequest(final HttpContext context) { int i = ((Integer) context.getAttribute("REQ-COUNT")).intValue(); - BasicHttpEntityEnclosingRequest request = null; + BasicHttpRequest request = null; if (i < reqNo) { - request = new BasicHttpEntityEnclosingRequest(method[0], "/?" + i); + request = new BasicHttpRequest(method[0], "/?" + i); context.setAttribute("REQ-COUNT", new Integer(i + 1)); } return request; } public void handleResponse(final HttpResponse response, final HttpContext context) { NHttpConnection conn = (NHttpConnection) context.getAttribute( HttpExecutionContext.HTTP_CONNECTION); List list = (List) context.getAttribute("LIST"); int i = ((Integer) context.getAttribute("RES-COUNT")).intValue(); i++; context.setAttribute("RES-COUNT", new Integer(i)); list.add(response); if (i < reqNo) { conn.requestInput(); } else { try { conn.close(); } catch (IOException ex) { fail(ex.getMessage()); } } } }; CountingEventListener serverEventListener = new CountingEventListener(); CountingEventListener clientEventListener = new CountingEventListener(); NHttpServiceHandler serviceHandler = createHttpServiceHandler( requestHandler, null, serverEventListener); NHttpClientHandler clientHandler = createHttpClientHandler( requestExecutionHandler, clientEventListener); this.server.start(serviceHandler); this.client.start(clientHandler); InetSocketAddress serverAddress = (InetSocketAddress) this.server.getSocketAddress(); method[0] = "GET"; for (int i = 0; i < responseData.length; i++) { this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), responseData[i]); } clientEventListener.await(connNo, 1000); assertEquals(connNo, clientEventListener.getConnCount()); List[] responseDataGET = responseData; method[0] = "HEAD"; responseData = new List[connNo]; for (int i = 0; i < responseData.length; i++) { responseData[i] = new ArrayList(); } for (int i = 0; i < responseData.length; i++) { this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), responseData[i]); } clientEventListener.await(connNo * 2, 1000); assertEquals(connNo * 2, clientEventListener.getConnCount()); this.client.shutdown(); this.server.shutdown(); for (int c = 0; c < responseData.length; c++) { List headResponses = responseData[c]; List getResponses = responseDataGET[c]; List expectedPackets = testData; assertEquals(expectedPackets.size(), headResponses.size()); assertEquals(expectedPackets.size(), getResponses.size()); for (int p = 0; p < testData.size(); p++) { HttpResponse getResponse = (HttpResponse) getResponses.get(p); HttpResponse headResponse = (HttpResponse) headResponses.get(p); assertEquals(null, headResponse.getEntity()); Header[] getHeaders = getResponse.getAllHeaders(); Header[] headHeaders = headResponse.getAllHeaders(); assertEquals(getHeaders.length, headHeaders.length); for (int j = 0; j < getHeaders.length; j++) { if ("Date".equals(getHeaders[j].getName())) { continue; } assertEquals(getHeaders[j].toString(), headHeaders[j].toString()); } } } } }
false
true
public void testSimpleHttpHeads() throws Exception { final int connNo = 3; final int reqNo = 20; final String[] method = new String[1]; Random rnd = new Random(); // Prepare some random data final List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } List[] responseData = new List[connNo]; for (int i = 0; i < responseData.length; i++) { responseData[i] = new ArrayList(); } HttpRequestHandler requestHandler = new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String s = request.getRequestLine().getUri(); URI uri; try { uri = new URI(s); } catch (URISyntaxException ex) { throw new HttpException("Invalid request URI: " + s); } int index = Integer.parseInt(uri.getQuery()); byte[] data = (byte []) testData.get(index); ByteArrayEntity entity = new ByteArrayEntity(data); response.setEntity(entity); } }; HttpRequestExecutionHandler requestExecutionHandler = new HttpRequestExecutionHandler() { public void initalizeContext(final HttpContext context, final Object attachment) { context.setAttribute("LIST", (List) attachment); context.setAttribute("REQ-COUNT", new Integer(0)); context.setAttribute("RES-COUNT", new Integer(0)); } public HttpRequest submitRequest(final HttpContext context) { int i = ((Integer) context.getAttribute("REQ-COUNT")).intValue(); BasicHttpEntityEnclosingRequest request = null; if (i < reqNo) { request = new BasicHttpEntityEnclosingRequest(method[0], "/?" + i); context.setAttribute("REQ-COUNT", new Integer(i + 1)); } return request; } public void handleResponse(final HttpResponse response, final HttpContext context) { NHttpConnection conn = (NHttpConnection) context.getAttribute( HttpExecutionContext.HTTP_CONNECTION); List list = (List) context.getAttribute("LIST"); int i = ((Integer) context.getAttribute("RES-COUNT")).intValue(); i++; context.setAttribute("RES-COUNT", new Integer(i)); list.add(response); if (i < reqNo) { conn.requestInput(); } else { try { conn.close(); } catch (IOException ex) { fail(ex.getMessage()); } } } }; CountingEventListener serverEventListener = new CountingEventListener(); CountingEventListener clientEventListener = new CountingEventListener(); NHttpServiceHandler serviceHandler = createHttpServiceHandler( requestHandler, null, serverEventListener); NHttpClientHandler clientHandler = createHttpClientHandler( requestExecutionHandler, clientEventListener); this.server.start(serviceHandler); this.client.start(clientHandler); InetSocketAddress serverAddress = (InetSocketAddress) this.server.getSocketAddress(); method[0] = "GET"; for (int i = 0; i < responseData.length; i++) { this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), responseData[i]); } clientEventListener.await(connNo, 1000); assertEquals(connNo, clientEventListener.getConnCount()); List[] responseDataGET = responseData; method[0] = "HEAD"; responseData = new List[connNo]; for (int i = 0; i < responseData.length; i++) { responseData[i] = new ArrayList(); } for (int i = 0; i < responseData.length; i++) { this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), responseData[i]); } clientEventListener.await(connNo * 2, 1000); assertEquals(connNo * 2, clientEventListener.getConnCount()); this.client.shutdown(); this.server.shutdown(); for (int c = 0; c < responseData.length; c++) { List headResponses = responseData[c]; List getResponses = responseDataGET[c]; List expectedPackets = testData; assertEquals(expectedPackets.size(), headResponses.size()); assertEquals(expectedPackets.size(), getResponses.size()); for (int p = 0; p < testData.size(); p++) { HttpResponse getResponse = (HttpResponse) getResponses.get(p); HttpResponse headResponse = (HttpResponse) headResponses.get(p); assertEquals(null, headResponse.getEntity()); Header[] getHeaders = getResponse.getAllHeaders(); Header[] headHeaders = headResponse.getAllHeaders(); assertEquals(getHeaders.length, headHeaders.length); for (int j = 0; j < getHeaders.length; j++) { if ("Date".equals(getHeaders[j].getName())) { continue; } assertEquals(getHeaders[j].toString(), headHeaders[j].toString()); } } } }
public void testSimpleHttpHeads() throws Exception { final int connNo = 3; final int reqNo = 20; final String[] method = new String[1]; Random rnd = new Random(); // Prepare some random data final List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } List[] responseData = new List[connNo]; for (int i = 0; i < responseData.length; i++) { responseData[i] = new ArrayList(); } HttpRequestHandler requestHandler = new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String s = request.getRequestLine().getUri(); URI uri; try { uri = new URI(s); } catch (URISyntaxException ex) { throw new HttpException("Invalid request URI: " + s); } int index = Integer.parseInt(uri.getQuery()); byte[] data = (byte []) testData.get(index); ByteArrayEntity entity = new ByteArrayEntity(data); response.setEntity(entity); } }; HttpRequestExecutionHandler requestExecutionHandler = new HttpRequestExecutionHandler() { public void initalizeContext(final HttpContext context, final Object attachment) { context.setAttribute("LIST", (List) attachment); context.setAttribute("REQ-COUNT", new Integer(0)); context.setAttribute("RES-COUNT", new Integer(0)); } public HttpRequest submitRequest(final HttpContext context) { int i = ((Integer) context.getAttribute("REQ-COUNT")).intValue(); BasicHttpRequest request = null; if (i < reqNo) { request = new BasicHttpRequest(method[0], "/?" + i); context.setAttribute("REQ-COUNT", new Integer(i + 1)); } return request; } public void handleResponse(final HttpResponse response, final HttpContext context) { NHttpConnection conn = (NHttpConnection) context.getAttribute( HttpExecutionContext.HTTP_CONNECTION); List list = (List) context.getAttribute("LIST"); int i = ((Integer) context.getAttribute("RES-COUNT")).intValue(); i++; context.setAttribute("RES-COUNT", new Integer(i)); list.add(response); if (i < reqNo) { conn.requestInput(); } else { try { conn.close(); } catch (IOException ex) { fail(ex.getMessage()); } } } }; CountingEventListener serverEventListener = new CountingEventListener(); CountingEventListener clientEventListener = new CountingEventListener(); NHttpServiceHandler serviceHandler = createHttpServiceHandler( requestHandler, null, serverEventListener); NHttpClientHandler clientHandler = createHttpClientHandler( requestExecutionHandler, clientEventListener); this.server.start(serviceHandler); this.client.start(clientHandler); InetSocketAddress serverAddress = (InetSocketAddress) this.server.getSocketAddress(); method[0] = "GET"; for (int i = 0; i < responseData.length; i++) { this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), responseData[i]); } clientEventListener.await(connNo, 1000); assertEquals(connNo, clientEventListener.getConnCount()); List[] responseDataGET = responseData; method[0] = "HEAD"; responseData = new List[connNo]; for (int i = 0; i < responseData.length; i++) { responseData[i] = new ArrayList(); } for (int i = 0; i < responseData.length; i++) { this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), responseData[i]); } clientEventListener.await(connNo * 2, 1000); assertEquals(connNo * 2, clientEventListener.getConnCount()); this.client.shutdown(); this.server.shutdown(); for (int c = 0; c < responseData.length; c++) { List headResponses = responseData[c]; List getResponses = responseDataGET[c]; List expectedPackets = testData; assertEquals(expectedPackets.size(), headResponses.size()); assertEquals(expectedPackets.size(), getResponses.size()); for (int p = 0; p < testData.size(); p++) { HttpResponse getResponse = (HttpResponse) getResponses.get(p); HttpResponse headResponse = (HttpResponse) headResponses.get(p); assertEquals(null, headResponse.getEntity()); Header[] getHeaders = getResponse.getAllHeaders(); Header[] headHeaders = headResponse.getAllHeaders(); assertEquals(getHeaders.length, headHeaders.length); for (int j = 0; j < getHeaders.length; j++) { if ("Date".equals(getHeaders[j].getName())) { continue; } assertEquals(getHeaders[j].toString(), headHeaders[j].toString()); } } } }
diff --git a/source/de/tuclausthal/submissioninterface/authfilter/authentication/AuthenticationFilter.java b/source/de/tuclausthal/submissioninterface/authfilter/authentication/AuthenticationFilter.java index 28f10b4..94e67d8 100644 --- a/source/de/tuclausthal/submissioninterface/authfilter/authentication/AuthenticationFilter.java +++ b/source/de/tuclausthal/submissioninterface/authfilter/authentication/AuthenticationFilter.java @@ -1,118 +1,118 @@ /* * Copyright 2009 - 2010 Sven Strickroth <[email protected]> * * This file is part of the SubmissionInterface. * * SubmissionInterface is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * SubmissionInterface 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 SubmissionInterface. If not, see <http://www.gnu.org/licenses/>. */ package de.tuclausthal.submissioninterface.authfilter.authentication; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.Session; import de.tuclausthal.submissioninterface.authfilter.SessionAdapter; import de.tuclausthal.submissioninterface.authfilter.authentication.login.LoginData; import de.tuclausthal.submissioninterface.authfilter.authentication.login.LoginIf; import de.tuclausthal.submissioninterface.authfilter.authentication.verify.VerifyIf; import de.tuclausthal.submissioninterface.persistence.dao.DAOFactory; import de.tuclausthal.submissioninterface.persistence.datamodel.User; import de.tuclausthal.submissioninterface.servlets.RequestAdapter; /** * Authentication filter * @author Sven Strickroth */ public class AuthenticationFilter implements Filter { private boolean bindToIP = false; private LoginIf login; private VerifyIf verify; @Override public void destroy() { // nothing to do here } @Override public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) filterRequest; HttpServletResponse response = (HttpServletResponse) filterResponse; Session session = RequestAdapter.getSession(request); SessionAdapter sa = RequestAdapter.getSessionAdapter(request); if (sa.getUser() == null || (bindToIP && !sa.isIPCorrect(request.getRemoteAddr()))) { LoginData logindata = login.getLoginData(request); if (logindata == null) { login.failNoData(request, response); return; } else { User user = null; // if login requires no verification we load the user named in logindata if (login.requiresVerification()) { user = verify.checkCredentials(session, logindata); } else { user = DAOFactory.UserDAOIf(session).getUser(logindata.getUsername()); } if (user == null) { - login.failNoData("Username or password wrong.", request, response); + login.failNoData("Login fehlgeschlagen! Bitte versuchen Sie es erneut.", request, response); return; } else { // fix against session fixtures sa.startNewSession(request); sa.setUser(user); if (login.redirectAfterLogin() == true) { performRedirect(request, response); return; } } } } else if (login.redirectAfterLogin() && login.isSubsequentAuthRequest(request)) { performRedirect(request, response); return; } request.setAttribute("username", sa.getUser().getEmail()); chain.doFilter(request, response); } private void performRedirect(HttpServletRequest request, HttpServletResponse response) throws IOException { String queryString = ""; if (request.getQueryString() != null) { queryString = "?" + request.getQueryString(); } response.sendRedirect(response.encodeRedirectURL((request.getRequestURL().toString() + queryString).replace("\r", "%0d").replace("\n", "%0a"))); } @Override public void init(FilterConfig filterConfig) throws ServletException { if ("true".equals(filterConfig.getInitParameter("bindToIP")) || "yes".equals(filterConfig.getInitParameter("bindToIP")) || "1".equals(filterConfig.getInitParameter("bindToIP"))) { bindToIP = true; } try { login = (LoginIf) Class.forName(filterConfig.getInitParameter("login")).getDeclaredConstructor(FilterConfig.class).newInstance(filterConfig); verify = (VerifyIf) Class.forName(filterConfig.getInitParameter("verify")).getDeclaredConstructor(FilterConfig.class).newInstance(filterConfig); } catch (Exception e) { e.printStackTrace(); throw new ServletException(e.getMessage()); } } }
true
true
public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) filterRequest; HttpServletResponse response = (HttpServletResponse) filterResponse; Session session = RequestAdapter.getSession(request); SessionAdapter sa = RequestAdapter.getSessionAdapter(request); if (sa.getUser() == null || (bindToIP && !sa.isIPCorrect(request.getRemoteAddr()))) { LoginData logindata = login.getLoginData(request); if (logindata == null) { login.failNoData(request, response); return; } else { User user = null; // if login requires no verification we load the user named in logindata if (login.requiresVerification()) { user = verify.checkCredentials(session, logindata); } else { user = DAOFactory.UserDAOIf(session).getUser(logindata.getUsername()); } if (user == null) { login.failNoData("Username or password wrong.", request, response); return; } else { // fix against session fixtures sa.startNewSession(request); sa.setUser(user); if (login.redirectAfterLogin() == true) { performRedirect(request, response); return; } } } } else if (login.redirectAfterLogin() && login.isSubsequentAuthRequest(request)) { performRedirect(request, response); return; } request.setAttribute("username", sa.getUser().getEmail()); chain.doFilter(request, response); }
public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) filterRequest; HttpServletResponse response = (HttpServletResponse) filterResponse; Session session = RequestAdapter.getSession(request); SessionAdapter sa = RequestAdapter.getSessionAdapter(request); if (sa.getUser() == null || (bindToIP && !sa.isIPCorrect(request.getRemoteAddr()))) { LoginData logindata = login.getLoginData(request); if (logindata == null) { login.failNoData(request, response); return; } else { User user = null; // if login requires no verification we load the user named in logindata if (login.requiresVerification()) { user = verify.checkCredentials(session, logindata); } else { user = DAOFactory.UserDAOIf(session).getUser(logindata.getUsername()); } if (user == null) { login.failNoData("Login fehlgeschlagen! Bitte versuchen Sie es erneut.", request, response); return; } else { // fix against session fixtures sa.startNewSession(request); sa.setUser(user); if (login.redirectAfterLogin() == true) { performRedirect(request, response); return; } } } } else if (login.redirectAfterLogin() && login.isSubsequentAuthRequest(request)) { performRedirect(request, response); return; } request.setAttribute("username", sa.getUser().getEmail()); chain.doFilter(request, response); }
diff --git a/jpa/schema-gen-scripts/src/main/java/org/javaee7/jpa/schemagen/scripts/TestServlet.java b/jpa/schema-gen-scripts/src/main/java/org/javaee7/jpa/schemagen/scripts/TestServlet.java index 71241c97..adf84250 100644 --- a/jpa/schema-gen-scripts/src/main/java/org/javaee7/jpa/schemagen/scripts/TestServlet.java +++ b/jpa/schema-gen-scripts/src/main/java/org/javaee7/jpa/schemagen/scripts/TestServlet.java @@ -1,127 +1,127 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * http://glassfish.java.net/public/CDDL+GPL_1_1.html * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package org.javaee7.jpa.schemagen.scripts; import java.io.IOException; import java.io.PrintWriter; import javax.inject.Inject; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author Arun Gupta */ @WebServlet(urlPatterns = {"/TestServlet"}) public class TestServlet extends HttpServlet { @Inject EmployeeBean bean; /** * Processes requests for both HTTP * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { out.println("<html>"); out.println("<head>"); - out.println("<title>SList of Employees</title>"); + out.println("<title>List of Employees</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>List of Employees</h1>"); for (Employee e : bean.get()) { out.println(e.getName() + "<br>"); } out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
true
true
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { out.println("<html>"); out.println("<head>"); out.println("<title>SList of Employees</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>List of Employees</h1>"); for (Employee e : bean.get()) { out.println(e.getName() + "<br>"); } out.println("</body>"); out.println("</html>"); } }
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { out.println("<html>"); out.println("<head>"); out.println("<title>List of Employees</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>List of Employees</h1>"); for (Employee e : bean.get()) { out.println(e.getName() + "<br>"); } out.println("</body>"); out.println("</html>"); } }
diff --git a/src/org/apache/xerces/dom/DeferredAttrNSImpl.java b/src/org/apache/xerces/dom/DeferredAttrNSImpl.java index 4dceab6b..4fa4400a 100644 --- a/src/org/apache/xerces/dom/DeferredAttrNSImpl.java +++ b/src/org/apache/xerces/dom/DeferredAttrNSImpl.java @@ -1,179 +1,180 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999, 2000 The Apache Software Foundation. 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 end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * WARNING: because java doesn't support multi-inheritance some code is * duplicated. If you're changing this file you probably want to change * DeferredAttrImpl.java at the same time. */ /* $Id$ */ package org.apache.xerces.dom; import org.w3c.dom.*; import org.apache.xerces.utils.StringPool; /** * DeferredAttrNSImpl is to AttrNSImpl, what DeferredAttrImpl is to * AttrImpl. * @see DeferredAttrImpl */ public final class DeferredAttrNSImpl extends AttrNSImpl implements DeferredNode { // // Constants // /** Serialization version. */ static final long serialVersionUID = 6074924934945957154L; // // Data // /** Node index. */ protected transient int fNodeIndex; // // Constructors // /** * This is the deferred constructor. Only the fNodeIndex is given here. * All other data, can be requested from the ownerDocument via the index. */ DeferredAttrNSImpl(DeferredDocumentImpl ownerDocument, int nodeIndex) { super(ownerDocument, null); fNodeIndex = nodeIndex; syncData(true); syncChildren(true); } // <init>(DeferredDocumentImpl,int) // // DeferredNode methods // /** Returns the node index. */ public int getNodeIndex() { return fNodeIndex; } // // Protected methods // /** Synchronizes the data (name and value) for fast nodes. */ protected void synchronizeData() { // no need to sync in the future syncData(false); // fluff data DeferredDocumentImpl ownerDocument = (DeferredDocumentImpl) this.ownerDocument; int attrQName = ownerDocument.getNodeName(fNodeIndex); StringPool pool = ownerDocument.getStringPool(); name = pool.toString(attrQName); // extract prefix and local part from QName int index = name.indexOf(':'); String prefix; if (index < 0) { prefix = null; localName = name; } else { prefix = name.substring(0, index); localName = name.substring(index + 1); } specified(ownerDocument.getNodeValue(fNodeIndex) == 1); - namespaceURI = pool.toString(ownerDocument.getNodeURI(attrQName)); + //namespaceURI = pool.toString(ownerDocument.getNodeURI(attrQName)); + namespaceURI = pool.toString(ownerDocument.getNodeURI(fNodeIndex)); // DOM Level 2 wants all namespace declaration attributes // to be bound to "http://www.w3.org/2000/xmlns/" // So as long as the XML parser doesn't do it, it needs to // done here. if (namespaceURI == null) { if (prefix != null) { if (prefix.equals("xmlns")) { namespaceURI = "http://www.w3.org/2000/xmlns/"; } } else if (name.equals("xmlns")) { namespaceURI = "http://www.w3.org/2000/xmlns/"; } } } // synchronizeData() /** * Synchronizes the node's children with the internal structure. * Fluffing the children at once solves a lot of work to keep * the two structures in sync. The problem gets worse when * editing the tree -- this makes it a lot easier. */ protected void synchronizeChildren() { synchronizeChildren(fNodeIndex); } // synchronizeChildren() } // class DeferredAttrImpl
true
true
protected void synchronizeData() { // no need to sync in the future syncData(false); // fluff data DeferredDocumentImpl ownerDocument = (DeferredDocumentImpl) this.ownerDocument; int attrQName = ownerDocument.getNodeName(fNodeIndex); StringPool pool = ownerDocument.getStringPool(); name = pool.toString(attrQName); // extract prefix and local part from QName int index = name.indexOf(':'); String prefix; if (index < 0) { prefix = null; localName = name; } else { prefix = name.substring(0, index); localName = name.substring(index + 1); } specified(ownerDocument.getNodeValue(fNodeIndex) == 1); namespaceURI = pool.toString(ownerDocument.getNodeURI(attrQName)); // DOM Level 2 wants all namespace declaration attributes // to be bound to "http://www.w3.org/2000/xmlns/" // So as long as the XML parser doesn't do it, it needs to // done here. if (namespaceURI == null) { if (prefix != null) { if (prefix.equals("xmlns")) { namespaceURI = "http://www.w3.org/2000/xmlns/"; } } else if (name.equals("xmlns")) { namespaceURI = "http://www.w3.org/2000/xmlns/"; } } } // synchronizeData()
protected void synchronizeData() { // no need to sync in the future syncData(false); // fluff data DeferredDocumentImpl ownerDocument = (DeferredDocumentImpl) this.ownerDocument; int attrQName = ownerDocument.getNodeName(fNodeIndex); StringPool pool = ownerDocument.getStringPool(); name = pool.toString(attrQName); // extract prefix and local part from QName int index = name.indexOf(':'); String prefix; if (index < 0) { prefix = null; localName = name; } else { prefix = name.substring(0, index); localName = name.substring(index + 1); } specified(ownerDocument.getNodeValue(fNodeIndex) == 1); //namespaceURI = pool.toString(ownerDocument.getNodeURI(attrQName)); namespaceURI = pool.toString(ownerDocument.getNodeURI(fNodeIndex)); // DOM Level 2 wants all namespace declaration attributes // to be bound to "http://www.w3.org/2000/xmlns/" // So as long as the XML parser doesn't do it, it needs to // done here. if (namespaceURI == null) { if (prefix != null) { if (prefix.equals("xmlns")) { namespaceURI = "http://www.w3.org/2000/xmlns/"; } } else if (name.equals("xmlns")) { namespaceURI = "http://www.w3.org/2000/xmlns/"; } } } // synchronizeData()
diff --git a/src/main/java/org/spoutcraft/launcher/skin/MetroLoginFrame.java b/src/main/java/org/spoutcraft/launcher/skin/MetroLoginFrame.java index 6246282..7b06a57 100644 --- a/src/main/java/org/spoutcraft/launcher/skin/MetroLoginFrame.java +++ b/src/main/java/org/spoutcraft/launcher/skin/MetroLoginFrame.java @@ -1,416 +1,416 @@ /* * This file is part of Spoutcraft. * * Copyright (c) 2011-2012, SpoutDev <http://www.spout.org/> * Spoutcraft is licensed under the SpoutDev License Version 1. * * Spoutcraft 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. * * In addition, 180 days after any changes are published, you can use the * software, incorporating those changes, under the terms of the MIT license, * as described in the SpoutDev License Version 1. * * Spoutcraft 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, * the MIT license and the SpoutDev License Version 1 along with this program. * If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public * License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license, * including the MIT license. */ package org.spoutcraft.launcher.skin; import static org.spoutcraft.launcher.util.ResourceUtils.getResourceAsStream; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import javax.swing.*; import org.spoutcraft.launcher.entrypoint.SpoutcraftLauncher; import org.spoutcraft.launcher.skin.components.BackgroundImage; import org.spoutcraft.launcher.skin.components.DynamicButton; import org.spoutcraft.launcher.skin.components.HyperlinkJLabel; import org.spoutcraft.launcher.skin.components.ImageHyperlinkButton; import org.spoutcraft.launcher.skin.components.LiteButton; import org.spoutcraft.launcher.skin.components.LitePasswordBox; import org.spoutcraft.launcher.skin.components.LiteProgressBar; import org.spoutcraft.launcher.skin.components.LiteTextBox; import org.spoutcraft.launcher.skin.components.LoginFrame; import org.spoutcraft.launcher.skin.components.TransparentButton; import org.spoutcraft.launcher.util.ImageUtils; import org.spoutcraft.launcher.util.OperatingSystem; import org.spoutcraft.launcher.util.ResourceUtils; public class MetroLoginFrame extends LoginFrame implements ActionListener, KeyListener{ private static final long serialVersionUID = 1L; private static final URL gearIcon = LegacyLoginFrame.class.getResource("/org/spoutcraft/launcher/resources/gear.png"); private static final int FRAME_WIDTH = 880; private static final int FRAME_HEIGHT = 520; private static final String OPTIONS_ACTION = "options"; private static final String LOGIN_ACTION = "login"; private static final String IMAGE_LOGIN_ACTION = "image_login"; private static final String REMOVE_USER = "remove"; private final Map<JButton, DynamicButton> removeButtons = new HashMap<JButton, DynamicButton>(); private LiteTextBox name; private LitePasswordBox pass; private LiteButton login; private JCheckBox remember; private TransparentButton options; private LiteProgressBar progressBar; private OptionsMenu optionsMenu = null; public MetroLoginFrame() { initComponents(); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); setBounds((dim.width - FRAME_WIDTH) / 2, (dim.height - FRAME_HEIGHT) / 2, FRAME_WIDTH, FRAME_HEIGHT); setResizable(false); getContentPane().add(new BackgroundImage(FRAME_WIDTH, FRAME_HEIGHT)); } private void initComponents() { Font minecraft = getMinecraftFont(12); int xShift = 0; int yShift = 0; - if (OperatingSystem.getOS().isUnix()) { + if (this.isUndecorated()) { yShift += 30; } // Setup username box name = new LiteTextBox(this, "Username..."); name.setBounds(622 + xShift, 426 + yShift, 140, 24); name.setFont(minecraft); name.addKeyListener(this); // Setup password box pass = new LitePasswordBox(this, "Password..."); pass.setBounds(622 + xShift, 455 + yShift, 140, 24); pass.setFont(minecraft); pass.addKeyListener(this); // Setup remember checkbox remember = new JCheckBox("Remember"); remember.setBounds(775 + xShift, 455 + yShift, 110, 24); remember.setFont(minecraft); remember.setOpaque(false); remember.setBorderPainted(false); remember.setContentAreaFilled(false); remember.setBorder(null); remember.setForeground(Color.WHITE); remember.addKeyListener(this); // Setup login button login = new LiteButton("Login"); login.setBounds(775 + xShift, 426 + yShift, 92, 24); login.setFont(minecraft); login.setActionCommand(LOGIN_ACTION); login.addActionListener(this); login.addKeyListener(this); // Spoutcraft logo JLabel logo = new JLabel(); logo.setBounds(8, 15, 400, 109); setIcon(logo, "spoutcraft.png", logo.getWidth(), logo.getHeight()); // Progress Bar progressBar = new LiteProgressBar(); progressBar.setBounds(8, 130, 395, 23); progressBar.setVisible(false); progressBar.setStringPainted(true); progressBar.setOpaque(true); progressBar.setTransparency(0.70F); progressBar.setHoverTransparency(0.70F); progressBar.setFont(minecraft); // Home Link Font largerMinecraft; if (OperatingSystem.getOS().isUnix()) { largerMinecraft = minecraft.deriveFont((float)18); } else { largerMinecraft = minecraft.deriveFont((float)20); } HyperlinkJLabel home = new HyperlinkJLabel("Home", "http://www.spout.org/"); home.setFont(largerMinecraft); home.setBounds(545, 35, 65, 20); home.setForeground(Color.WHITE); home.setOpaque(false); home.setTransparency(0.70F); home.setHoverTransparency(1F); // Forums link HyperlinkJLabel forums = new HyperlinkJLabel("Forums", "http://forums.spout.org/"); forums.setFont(largerMinecraft); forums.setBounds(625, 35, 90, 20); forums.setForeground(Color.WHITE); forums.setOpaque(false); forums.setTransparency(0.70F); forums.setHoverTransparency(1F); // Issues link HyperlinkJLabel issues = new HyperlinkJLabel("Issues", "http://spout.in/issues"); issues.setFont(largerMinecraft); issues.setBounds(733, 35, 85, 20); issues.setForeground(Color.WHITE); issues.setOpaque(false); issues.setTransparency(0.70F); issues.setHoverTransparency(1F); // Options Button options = new TransparentButton(); options.setIcon(new ImageIcon(Toolkit.getDefaultToolkit().getImage(gearIcon))); options.setBounds(828, 28, 30, 30); options.setTransparency(0.70F); options.setHoverTransparency(1F); options.setActionCommand(OPTIONS_ACTION); options.addActionListener(this); // Steam button JButton steam = new ImageHyperlinkButton("http://spout.in/steam"); steam.setToolTipText("Game with us on Steam"); steam.setBounds(6, FRAME_HEIGHT - 62 + yShift, 28, 28); setIcon(steam, "steam.png", 28); // Twitter button JButton twitter = new ImageHyperlinkButton("http://spout.in/twitter"); twitter.setToolTipText("Follow us on Twitter"); twitter.setBounds(6 + 34 * 4 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28); setIcon(twitter, "twitter.png", 28); // Facebook button JButton facebook = new ImageHyperlinkButton("http://spout.in/facebook"); facebook.setToolTipText("Like us on Facebook"); facebook.setBounds(6 + 34 * 3 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28); setIcon(facebook, "facebook.png", 28); // Google+ button JButton gplus = new ImageHyperlinkButton("http://spout.in/gplus"); gplus.setToolTipText("Follow us on Google+"); gplus.setBounds(6 + 34 * 2 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28); setIcon(gplus, "gplus.png", 28); // YouTube button JButton youtube = new ImageHyperlinkButton("http://spout.in/youtube"); youtube.setToolTipText("Subscribe to our videos"); youtube.setBounds(6 + 34 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28); setIcon(youtube, "youtube.png", 28); Container contentPane = getContentPane(); contentPane.setLayout(null); java.util.List<String> savedUsers = getSavedUsernames(); int users = Math.min(5, this.getSavedUsernames().size()); for (int i = 0; i < users; i++) { String accountName = savedUsers.get(i); String userName = this.getUsername(accountName); DynamicButton userButton = new DynamicButton(this, getImage(userName), 44, accountName, userName); userButton.setFont(minecraft.deriveFont(14F)); userButton.setBounds((FRAME_WIDTH - 75) * (i + 1) / (users + 1), (FRAME_HEIGHT - 75) / 2 , 75, 75); contentPane.add(userButton); userButton.setActionCommand(IMAGE_LOGIN_ACTION); userButton.addActionListener(this); setIcon(userButton.getRemoveIcon(), "remove.png", 16); userButton.getRemoveIcon().addActionListener(this); userButton.getRemoveIcon().setActionCommand(REMOVE_USER); removeButtons.put(userButton.getRemoveIcon(), userButton); } contentPane.add(name); contentPane.add(pass); contentPane.add(remember); contentPane.add(login); contentPane.add(steam); contentPane.add(twitter); contentPane.add(facebook); contentPane.add(gplus); contentPane.add(youtube); contentPane.add(home); contentPane.add(forums); contentPane.add(issues); contentPane.add(logo); contentPane.add(options); contentPane.add(progressBar); setFocusTraversalPolicy(new LoginFocusTraversalPolicy()); } private void setIcon(JButton button, String iconName, int size) { try { button.setIcon(new ImageIcon(ImageUtils.scaleImage(ImageIO.read(ResourceUtils.getResourceAsStream("/org/spoutcraft/launcher/resources/" + iconName)), size, size))); } catch (IOException e) { e.printStackTrace(); } } private void setIcon(JLabel label, String iconName, int w, int h) { try { label.setIcon(new ImageIcon(ImageUtils.scaleImage(ImageIO.read(ResourceUtils.getResourceAsStream("/org/spoutcraft/launcher/resources/" + iconName)), w, h))); } catch (IOException e) { e.printStackTrace(); } } private BufferedImage getImage(String user){ try { URLConnection conn = (new URL("https://minotar.net/avatar/" + user + "/100")).openConnection(); InputStream stream = conn.getInputStream(); BufferedImage image = ImageIO.read(stream); return image; } catch (Exception e) { e.printStackTrace(); try { return ImageIO.read(getResourceAsStream("/org/spoutcraft/launcher/resources/steve.png")); } catch (IOException e1) { throw new RuntimeException("Error reading backup image", e1); } } } public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JComponent) { action(e.getActionCommand(), (JComponent)e.getSource()); } } private void action(String action, JComponent c) { if (action.equals(OPTIONS_ACTION)) { if (optionsMenu == null || !optionsMenu.isVisible()) { optionsMenu = new OptionsMenu(); optionsMenu.setModal(true); optionsMenu.setVisible(true); } } else if (action.equals(LOGIN_ACTION)) { String pass = new String(this.pass.getPassword()); if (getSelectedUser().length() > 0 && pass.length() > 0) { this.doLogin(getSelectedUser(), pass); if (remember.isSelected()) { saveUsername(getSelectedUser(), pass); } } } else if (action.equals(IMAGE_LOGIN_ACTION)) { DynamicButton userButton = (DynamicButton)c; this.name.setText(userButton.getAccount()); this.pass.setText(this.getSavedPassword(userButton.getAccount())); this.remember.setSelected(true); action(LOGIN_ACTION, userButton); } else if (action.equals(REMOVE_USER)) { DynamicButton userButton = removeButtons.get((JButton)c); this.removeAccount(userButton.getAccount()); userButton.setVisible(false); userButton.setEnabled(false); getContentPane().remove(userButton); c.setVisible(false); c.setEnabled(false); getContentPane().remove(c); removeButtons.remove(c); writeUsernameList(); } } public void stateChanged(String status, float progress) { int intProgress = Math.round(progress); progressBar.setValue(intProgress); if (status.length() > 60) { status = status.substring(0, 60) + "..."; } progressBar.setString(intProgress + "% " + status); } @Override public JProgressBar getProgressBar() { return progressBar; } @Override public void disableForm() { } @Override public void enableForm() { } @Override public String getSelectedUser() { return this.name.getText(); } //Emulates tab focus policy of name -> pass -> remember -> login private class LoginFocusTraversalPolicy extends FocusTraversalPolicy{ public Component getComponentAfter(Container con, Component c) { if (c == name) { return pass; } else if (c == pass) { return remember; } else if (c == remember) { return login; } else if (c == login) { return name; } return getFirstComponent(con); } public Component getComponentBefore(Container con, Component c) { if (c == name) { return login; } else if (c == pass) { return name; } else if (c == remember) { return pass; } else if (c == login) { return remember; } return getFirstComponent(con); } public Component getFirstComponent(Container c) { return name; } public Component getLastComponent(Container c) { return login; } public Component getDefaultComponent(Container c) { return name; } } public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER){ //Allows the user to press enter and log in from the login box focus, username box focus, or password box focus if (e.getComponent() == login || e.getComponent() == name || e.getComponent() == pass) { action(LOGIN_ACTION, (JComponent) e.getComponent()); } else if (e.getComponent() == remember) { remember.setSelected(!remember.isSelected()); } } } public void keyReleased(KeyEvent e) { } }
true
true
private void initComponents() { Font minecraft = getMinecraftFont(12); int xShift = 0; int yShift = 0; if (OperatingSystem.getOS().isUnix()) { yShift += 30; } // Setup username box name = new LiteTextBox(this, "Username..."); name.setBounds(622 + xShift, 426 + yShift, 140, 24); name.setFont(minecraft); name.addKeyListener(this); // Setup password box pass = new LitePasswordBox(this, "Password..."); pass.setBounds(622 + xShift, 455 + yShift, 140, 24); pass.setFont(minecraft); pass.addKeyListener(this); // Setup remember checkbox remember = new JCheckBox("Remember"); remember.setBounds(775 + xShift, 455 + yShift, 110, 24); remember.setFont(minecraft); remember.setOpaque(false); remember.setBorderPainted(false); remember.setContentAreaFilled(false); remember.setBorder(null); remember.setForeground(Color.WHITE); remember.addKeyListener(this); // Setup login button login = new LiteButton("Login"); login.setBounds(775 + xShift, 426 + yShift, 92, 24); login.setFont(minecraft); login.setActionCommand(LOGIN_ACTION); login.addActionListener(this); login.addKeyListener(this); // Spoutcraft logo JLabel logo = new JLabel(); logo.setBounds(8, 15, 400, 109); setIcon(logo, "spoutcraft.png", logo.getWidth(), logo.getHeight()); // Progress Bar progressBar = new LiteProgressBar(); progressBar.setBounds(8, 130, 395, 23); progressBar.setVisible(false); progressBar.setStringPainted(true); progressBar.setOpaque(true); progressBar.setTransparency(0.70F); progressBar.setHoverTransparency(0.70F); progressBar.setFont(minecraft); // Home Link Font largerMinecraft; if (OperatingSystem.getOS().isUnix()) { largerMinecraft = minecraft.deriveFont((float)18); } else { largerMinecraft = minecraft.deriveFont((float)20); } HyperlinkJLabel home = new HyperlinkJLabel("Home", "http://www.spout.org/"); home.setFont(largerMinecraft); home.setBounds(545, 35, 65, 20); home.setForeground(Color.WHITE); home.setOpaque(false); home.setTransparency(0.70F); home.setHoverTransparency(1F); // Forums link HyperlinkJLabel forums = new HyperlinkJLabel("Forums", "http://forums.spout.org/"); forums.setFont(largerMinecraft); forums.setBounds(625, 35, 90, 20); forums.setForeground(Color.WHITE); forums.setOpaque(false); forums.setTransparency(0.70F); forums.setHoverTransparency(1F); // Issues link HyperlinkJLabel issues = new HyperlinkJLabel("Issues", "http://spout.in/issues"); issues.setFont(largerMinecraft); issues.setBounds(733, 35, 85, 20); issues.setForeground(Color.WHITE); issues.setOpaque(false); issues.setTransparency(0.70F); issues.setHoverTransparency(1F); // Options Button options = new TransparentButton(); options.setIcon(new ImageIcon(Toolkit.getDefaultToolkit().getImage(gearIcon))); options.setBounds(828, 28, 30, 30); options.setTransparency(0.70F); options.setHoverTransparency(1F); options.setActionCommand(OPTIONS_ACTION); options.addActionListener(this); // Steam button JButton steam = new ImageHyperlinkButton("http://spout.in/steam"); steam.setToolTipText("Game with us on Steam"); steam.setBounds(6, FRAME_HEIGHT - 62 + yShift, 28, 28); setIcon(steam, "steam.png", 28); // Twitter button JButton twitter = new ImageHyperlinkButton("http://spout.in/twitter"); twitter.setToolTipText("Follow us on Twitter"); twitter.setBounds(6 + 34 * 4 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28); setIcon(twitter, "twitter.png", 28); // Facebook button JButton facebook = new ImageHyperlinkButton("http://spout.in/facebook"); facebook.setToolTipText("Like us on Facebook"); facebook.setBounds(6 + 34 * 3 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28); setIcon(facebook, "facebook.png", 28); // Google+ button JButton gplus = new ImageHyperlinkButton("http://spout.in/gplus"); gplus.setToolTipText("Follow us on Google+"); gplus.setBounds(6 + 34 * 2 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28); setIcon(gplus, "gplus.png", 28); // YouTube button JButton youtube = new ImageHyperlinkButton("http://spout.in/youtube"); youtube.setToolTipText("Subscribe to our videos"); youtube.setBounds(6 + 34 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28); setIcon(youtube, "youtube.png", 28); Container contentPane = getContentPane(); contentPane.setLayout(null); java.util.List<String> savedUsers = getSavedUsernames(); int users = Math.min(5, this.getSavedUsernames().size()); for (int i = 0; i < users; i++) { String accountName = savedUsers.get(i); String userName = this.getUsername(accountName); DynamicButton userButton = new DynamicButton(this, getImage(userName), 44, accountName, userName); userButton.setFont(minecraft.deriveFont(14F)); userButton.setBounds((FRAME_WIDTH - 75) * (i + 1) / (users + 1), (FRAME_HEIGHT - 75) / 2 , 75, 75); contentPane.add(userButton); userButton.setActionCommand(IMAGE_LOGIN_ACTION); userButton.addActionListener(this); setIcon(userButton.getRemoveIcon(), "remove.png", 16); userButton.getRemoveIcon().addActionListener(this); userButton.getRemoveIcon().setActionCommand(REMOVE_USER); removeButtons.put(userButton.getRemoveIcon(), userButton); } contentPane.add(name); contentPane.add(pass); contentPane.add(remember); contentPane.add(login); contentPane.add(steam); contentPane.add(twitter); contentPane.add(facebook); contentPane.add(gplus); contentPane.add(youtube); contentPane.add(home); contentPane.add(forums); contentPane.add(issues); contentPane.add(logo); contentPane.add(options); contentPane.add(progressBar); setFocusTraversalPolicy(new LoginFocusTraversalPolicy()); }
private void initComponents() { Font minecraft = getMinecraftFont(12); int xShift = 0; int yShift = 0; if (this.isUndecorated()) { yShift += 30; } // Setup username box name = new LiteTextBox(this, "Username..."); name.setBounds(622 + xShift, 426 + yShift, 140, 24); name.setFont(minecraft); name.addKeyListener(this); // Setup password box pass = new LitePasswordBox(this, "Password..."); pass.setBounds(622 + xShift, 455 + yShift, 140, 24); pass.setFont(minecraft); pass.addKeyListener(this); // Setup remember checkbox remember = new JCheckBox("Remember"); remember.setBounds(775 + xShift, 455 + yShift, 110, 24); remember.setFont(minecraft); remember.setOpaque(false); remember.setBorderPainted(false); remember.setContentAreaFilled(false); remember.setBorder(null); remember.setForeground(Color.WHITE); remember.addKeyListener(this); // Setup login button login = new LiteButton("Login"); login.setBounds(775 + xShift, 426 + yShift, 92, 24); login.setFont(minecraft); login.setActionCommand(LOGIN_ACTION); login.addActionListener(this); login.addKeyListener(this); // Spoutcraft logo JLabel logo = new JLabel(); logo.setBounds(8, 15, 400, 109); setIcon(logo, "spoutcraft.png", logo.getWidth(), logo.getHeight()); // Progress Bar progressBar = new LiteProgressBar(); progressBar.setBounds(8, 130, 395, 23); progressBar.setVisible(false); progressBar.setStringPainted(true); progressBar.setOpaque(true); progressBar.setTransparency(0.70F); progressBar.setHoverTransparency(0.70F); progressBar.setFont(minecraft); // Home Link Font largerMinecraft; if (OperatingSystem.getOS().isUnix()) { largerMinecraft = minecraft.deriveFont((float)18); } else { largerMinecraft = minecraft.deriveFont((float)20); } HyperlinkJLabel home = new HyperlinkJLabel("Home", "http://www.spout.org/"); home.setFont(largerMinecraft); home.setBounds(545, 35, 65, 20); home.setForeground(Color.WHITE); home.setOpaque(false); home.setTransparency(0.70F); home.setHoverTransparency(1F); // Forums link HyperlinkJLabel forums = new HyperlinkJLabel("Forums", "http://forums.spout.org/"); forums.setFont(largerMinecraft); forums.setBounds(625, 35, 90, 20); forums.setForeground(Color.WHITE); forums.setOpaque(false); forums.setTransparency(0.70F); forums.setHoverTransparency(1F); // Issues link HyperlinkJLabel issues = new HyperlinkJLabel("Issues", "http://spout.in/issues"); issues.setFont(largerMinecraft); issues.setBounds(733, 35, 85, 20); issues.setForeground(Color.WHITE); issues.setOpaque(false); issues.setTransparency(0.70F); issues.setHoverTransparency(1F); // Options Button options = new TransparentButton(); options.setIcon(new ImageIcon(Toolkit.getDefaultToolkit().getImage(gearIcon))); options.setBounds(828, 28, 30, 30); options.setTransparency(0.70F); options.setHoverTransparency(1F); options.setActionCommand(OPTIONS_ACTION); options.addActionListener(this); // Steam button JButton steam = new ImageHyperlinkButton("http://spout.in/steam"); steam.setToolTipText("Game with us on Steam"); steam.setBounds(6, FRAME_HEIGHT - 62 + yShift, 28, 28); setIcon(steam, "steam.png", 28); // Twitter button JButton twitter = new ImageHyperlinkButton("http://spout.in/twitter"); twitter.setToolTipText("Follow us on Twitter"); twitter.setBounds(6 + 34 * 4 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28); setIcon(twitter, "twitter.png", 28); // Facebook button JButton facebook = new ImageHyperlinkButton("http://spout.in/facebook"); facebook.setToolTipText("Like us on Facebook"); facebook.setBounds(6 + 34 * 3 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28); setIcon(facebook, "facebook.png", 28); // Google+ button JButton gplus = new ImageHyperlinkButton("http://spout.in/gplus"); gplus.setToolTipText("Follow us on Google+"); gplus.setBounds(6 + 34 * 2 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28); setIcon(gplus, "gplus.png", 28); // YouTube button JButton youtube = new ImageHyperlinkButton("http://spout.in/youtube"); youtube.setToolTipText("Subscribe to our videos"); youtube.setBounds(6 + 34 + xShift, FRAME_HEIGHT - 62 + yShift, 28, 28); setIcon(youtube, "youtube.png", 28); Container contentPane = getContentPane(); contentPane.setLayout(null); java.util.List<String> savedUsers = getSavedUsernames(); int users = Math.min(5, this.getSavedUsernames().size()); for (int i = 0; i < users; i++) { String accountName = savedUsers.get(i); String userName = this.getUsername(accountName); DynamicButton userButton = new DynamicButton(this, getImage(userName), 44, accountName, userName); userButton.setFont(minecraft.deriveFont(14F)); userButton.setBounds((FRAME_WIDTH - 75) * (i + 1) / (users + 1), (FRAME_HEIGHT - 75) / 2 , 75, 75); contentPane.add(userButton); userButton.setActionCommand(IMAGE_LOGIN_ACTION); userButton.addActionListener(this); setIcon(userButton.getRemoveIcon(), "remove.png", 16); userButton.getRemoveIcon().addActionListener(this); userButton.getRemoveIcon().setActionCommand(REMOVE_USER); removeButtons.put(userButton.getRemoveIcon(), userButton); } contentPane.add(name); contentPane.add(pass); contentPane.add(remember); contentPane.add(login); contentPane.add(steam); contentPane.add(twitter); contentPane.add(facebook); contentPane.add(gplus); contentPane.add(youtube); contentPane.add(home); contentPane.add(forums); contentPane.add(issues); contentPane.add(logo); contentPane.add(options); contentPane.add(progressBar); setFocusTraversalPolicy(new LoginFocusTraversalPolicy()); }
diff --git a/src/webserver/Response.java b/src/webserver/Response.java index 0847fbd..1664c32 100644 --- a/src/webserver/Response.java +++ b/src/webserver/Response.java @@ -1,117 +1,119 @@ package webserver; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public class Response { public Map<String, String> headers; public byte[] code = null; public static final int BUFFER_SIZE = 8192; // 8Kb static final byte[] NEW_LINE = { 13, 10 }; private boolean headersSent; private Client client; public int httpMajor; public int httpMinor; public boolean closeAfterEnd; public Response(Client client) { headers = new HashMap<String, String>(); headersSent = false; httpMajor = 0; httpMinor = 0; closeAfterEnd = true; this.client = client; } protected FileChannel fileToSend; private long fileSize = 0; public void sendFile(FileChannel file, long size) { fileToSend = file; fileSize = size; } public void end() { client.requestFinished(); if (closeAfterEnd) { client.close(); } } private long filePosition = 0; private ByteBuffer[] hb; //returns true if everything written, false if more to write. public boolean write() { if(hb == null){ hb = new ByteBuffer[headers.size() + 3]; if (code == null) { code = STATUS_405; // noone handled the request, return method // not allowed. } hb[0] = ByteBuffer .wrap(("HTTP/" + httpMajor + "." + httpMinor + " ") .getBytes()); hb[1] = ByteBuffer.wrap(code); int i = 2; for (Entry<String, String> header : headers.entrySet()) { hb[i] = ByteBuffer.wrap((header.getKey() + ": " + header.getValue() + "\r\n").getBytes()); i++; } hb[i] = ByteBuffer.wrap(NEW_LINE); } if (!headersSent) { try { client.ch.write(hb); if(hb[hb.length-1].remaining() == 0){ headersSent = true; }else{ return false; } } catch (IOException e) { System.err.println("Could not write to client"); client.close(); } } if(fileToSend != null){ try { filePosition += fileToSend.transferTo(filePosition, fileSize, client.ch); if(filePosition != fileSize){ return false; //write again + }else{ + fileToSend.close(); } } catch (IOException e) { System.err.println("Error: could not send file, closing connection"); client.close(); } } //if we get here, the request is finished! end(); return true; } public static final byte[] STATUS_200 = "200 OK\r\n".getBytes(), STATUS_404 = "404 Not Found\r\n".getBytes(), STATUS_405 = "405 Method Not Allowed\r\n".getBytes(), STATUS_500 = "500 Internal Server Error\r\n".getBytes(), STATUS_505 = "505 HTTP Version Not Supported\r\n".getBytes(), STATUS_304 = "304 Not Modified\r\n".getBytes(); }
true
true
public boolean write() { if(hb == null){ hb = new ByteBuffer[headers.size() + 3]; if (code == null) { code = STATUS_405; // noone handled the request, return method // not allowed. } hb[0] = ByteBuffer .wrap(("HTTP/" + httpMajor + "." + httpMinor + " ") .getBytes()); hb[1] = ByteBuffer.wrap(code); int i = 2; for (Entry<String, String> header : headers.entrySet()) { hb[i] = ByteBuffer.wrap((header.getKey() + ": " + header.getValue() + "\r\n").getBytes()); i++; } hb[i] = ByteBuffer.wrap(NEW_LINE); } if (!headersSent) { try { client.ch.write(hb); if(hb[hb.length-1].remaining() == 0){ headersSent = true; }else{ return false; } } catch (IOException e) { System.err.println("Could not write to client"); client.close(); } } if(fileToSend != null){ try { filePosition += fileToSend.transferTo(filePosition, fileSize, client.ch); if(filePosition != fileSize){ return false; //write again } } catch (IOException e) { System.err.println("Error: could not send file, closing connection"); client.close(); } } //if we get here, the request is finished! end(); return true; }
public boolean write() { if(hb == null){ hb = new ByteBuffer[headers.size() + 3]; if (code == null) { code = STATUS_405; // noone handled the request, return method // not allowed. } hb[0] = ByteBuffer .wrap(("HTTP/" + httpMajor + "." + httpMinor + " ") .getBytes()); hb[1] = ByteBuffer.wrap(code); int i = 2; for (Entry<String, String> header : headers.entrySet()) { hb[i] = ByteBuffer.wrap((header.getKey() + ": " + header.getValue() + "\r\n").getBytes()); i++; } hb[i] = ByteBuffer.wrap(NEW_LINE); } if (!headersSent) { try { client.ch.write(hb); if(hb[hb.length-1].remaining() == 0){ headersSent = true; }else{ return false; } } catch (IOException e) { System.err.println("Could not write to client"); client.close(); } } if(fileToSend != null){ try { filePosition += fileToSend.transferTo(filePosition, fileSize, client.ch); if(filePosition != fileSize){ return false; //write again }else{ fileToSend.close(); } } catch (IOException e) { System.err.println("Error: could not send file, closing connection"); client.close(); } } //if we get here, the request is finished! end(); return true; }
diff --git a/Enlighted/src/com/github/CubieX/Enlighted/EnlightedCommandHandler.java b/Enlighted/src/com/github/CubieX/Enlighted/EnlightedCommandHandler.java index a1b0627..15ceb5b 100644 --- a/Enlighted/src/com/github/CubieX/Enlighted/EnlightedCommandHandler.java +++ b/Enlighted/src/com/github/CubieX/Enlighted/EnlightedCommandHandler.java @@ -1,64 +1,64 @@ package com.github.CubieX.Enlighted; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class EnlightedCommandHandler implements CommandExecutor { private Enlighted plugin = null; private EnlightedConfigHandler cHandler = null; public EnlightedCommandHandler(Enlighted plugin, EnlightedConfigHandler cHandler) { this.plugin = plugin; this.cHandler = cHandler; } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if(Enlighted.debug){Enlighted.log.info("onCommand");} if (cmd.getName().equalsIgnoreCase("el")) { // If the player typed /el then do the following... (can be run from console also) if (args.length == 0) { //no arguments, so help will be displayed return false; } if (args.length==1) { if (args[0].equalsIgnoreCase("version")) // argument 0 is given and correct { sender.sendMessage(ChatColor.YELLOW + "This server is running " + plugin.getDescription().getName() + " version " + plugin.getDescription().getVersion()); return true; } if (args[0].equalsIgnoreCase("reload")) // argument 0 is given and correct { - if(sender.hasPermission("enlighted.reload")) + if(sender.hasPermission("enlighted.admin")) { cHandler.reloadConfig(sender); return true; } else { sender.sendMessage(ChatColor.RED + "You do not have sufficient permission to reload " + plugin.getDescription().getName() + "!"); } } } else { sender.sendMessage(ChatColor.YELLOW + "Ungueltige Anzahl Argumente."); } } return false; // if false is returned, the help for the command stated in the plugin.yml will be displayed to the player } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if(Enlighted.debug){Enlighted.log.info("onCommand");} if (cmd.getName().equalsIgnoreCase("el")) { // If the player typed /el then do the following... (can be run from console also) if (args.length == 0) { //no arguments, so help will be displayed return false; } if (args.length==1) { if (args[0].equalsIgnoreCase("version")) // argument 0 is given and correct { sender.sendMessage(ChatColor.YELLOW + "This server is running " + plugin.getDescription().getName() + " version " + plugin.getDescription().getVersion()); return true; } if (args[0].equalsIgnoreCase("reload")) // argument 0 is given and correct { if(sender.hasPermission("enlighted.reload")) { cHandler.reloadConfig(sender); return true; } else { sender.sendMessage(ChatColor.RED + "You do not have sufficient permission to reload " + plugin.getDescription().getName() + "!"); } } } else { sender.sendMessage(ChatColor.YELLOW + "Ungueltige Anzahl Argumente."); } } return false; // if false is returned, the help for the command stated in the plugin.yml will be displayed to the player }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if(Enlighted.debug){Enlighted.log.info("onCommand");} if (cmd.getName().equalsIgnoreCase("el")) { // If the player typed /el then do the following... (can be run from console also) if (args.length == 0) { //no arguments, so help will be displayed return false; } if (args.length==1) { if (args[0].equalsIgnoreCase("version")) // argument 0 is given and correct { sender.sendMessage(ChatColor.YELLOW + "This server is running " + plugin.getDescription().getName() + " version " + plugin.getDescription().getVersion()); return true; } if (args[0].equalsIgnoreCase("reload")) // argument 0 is given and correct { if(sender.hasPermission("enlighted.admin")) { cHandler.reloadConfig(sender); return true; } else { sender.sendMessage(ChatColor.RED + "You do not have sufficient permission to reload " + plugin.getDescription().getName() + "!"); } } } else { sender.sendMessage(ChatColor.YELLOW + "Ungueltige Anzahl Argumente."); } } return false; // if false is returned, the help for the command stated in the plugin.yml will be displayed to the player }
diff --git a/src/game/GUI.java b/src/game/GUI.java index 0fbd8fb..6f51ae4 100644 --- a/src/game/GUI.java +++ b/src/game/GUI.java @@ -1,162 +1,162 @@ package game; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JDialog; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; /** * @author mauriceschleusinger * */ public class GUI implements ActionListener { /** * Using the Java Actionlistener */ private JMenuBar menubar; /** * new MenuBar which contains the menu-tabs and elements */ private JMenu spiel; /** * new tab named "Spiel" */ private JMenuItem starten; /** * new item in Tab "Spiel" named "starten" */ private JMenuItem beenden; /** * new item in Tab "Spiel" named "beenden" */ private JMenu optionen; /** * new tab named "Optionen" */ private JMenuItem spname; /** * new item in Tab "Optionen" named "spname" */ private JMenuItem groesse; /** * new item in Tab "Optionen" named "groesse" */ private JMenu netzwerk; /** * new tab named "Netzwerk" */ private JMenuItem startserver; /** * new item in Tab "Netzwerk" named "startserver" */ private JMenuItem stopserver; /** * new item in Tab "Netzwerk" named "stopserver" */ private JMenuItem findserver; /** * new item in Tab "Netzwerk" named "findserver" */ private Launcher frame; /** * @param frame */ public GUI(Launcher frame) { this.frame = frame; // Create Menubar this.menubar = new JMenuBar(); // Buttons for "Spiel" this.spiel = new JMenu("Spiel"); this.starten = new JMenuItem("Neustarten"); this.starten.addActionListener(this); this.beenden = new JMenuItem("Beenden"); this.beenden.addActionListener(this); // this.spiel.add(this.starten); this.spiel.add(this.beenden); this.menubar.add(this.spiel); // Buttons for "Netzwerk" this.netzwerk = new JMenu("Netzwerk"); /* * this.startserver = new JMenuItem("Server starten"); this.stopserver = * new JMenuItem("Server beenden"); this.findserver = new * JMenuItem("Server suchen"); this.netzwerk.add(this.startserver); * this.netzwerk.add(this.stopserver); * this.netzwerk.add(this.findserver); */ - this.netzwerk.add(new JMenuItem("noch nicht verf�gbar")); + this.netzwerk.add(new JMenuItem("noch nicht verfügbar")); this.menubar.add(this.netzwerk); // Buttons for "Optionen" this.optionen = new JMenu("Optionen"); /* * this.spname = new JMenuItem("Spielername"); this.groesse = new * JMenuItem("Groesse"); this.optionen.add(this.spname); * this.optionen.add(this.groesse); */ - this.optionen.add(new JMenuItem("noch nicht verf�gbar")); + this.optionen.add(new JMenuItem("noch nicht verfügbar")); this.menubar.add(this.optionen); // set Menubar this.frame.setJMenuBar(this.menubar); } /* * (non-Javadoc) * * @see * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ /* * (non-Javadoc) * * @see * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ @Override // this method is called if a button is pressed public void actionPerformed(ActionEvent arg0) { // If the "restart"-button is pressed the game asks to restart the game if (arg0.getSource() == this.starten) { Object[] options = { "Neustart", "abbrechen" }; JOptionPane question = new JOptionPane( "Spiel neustarten? Der aktuelle fortschritt geht verloren"); question.setOptions(options); JDialog dialog = question.createDialog(this.frame, "Achtung"); dialog.setVisible(true); Object obj = question.getValue(); if (obj.equals(options[0])) { // restarts the game (not working yet) this.frame.game.stop(); this.frame.game.start(); } dialog.dispose(); question.disable(); // If the exit-button is pressed the game asks to exit the game } else if (arg0.getSource() == this.beenden) { Object[] options = { "beenden", "abbrechen" }; JOptionPane question = new JOptionPane( "Spiel beenden? Der aktuelle fortschritt geht verloren"); question.setOptions(options); JDialog dialog = question.createDialog(this.frame, "Achtung"); dialog.setVisible(true); Object obj = question.getValue(); // ends the game and closes the JFrame if (obj.equals(options[0])) { System.exit(0); } dialog.dispose(); } } }
false
true
public GUI(Launcher frame) { this.frame = frame; // Create Menubar this.menubar = new JMenuBar(); // Buttons for "Spiel" this.spiel = new JMenu("Spiel"); this.starten = new JMenuItem("Neustarten"); this.starten.addActionListener(this); this.beenden = new JMenuItem("Beenden"); this.beenden.addActionListener(this); // this.spiel.add(this.starten); this.spiel.add(this.beenden); this.menubar.add(this.spiel); // Buttons for "Netzwerk" this.netzwerk = new JMenu("Netzwerk"); /* * this.startserver = new JMenuItem("Server starten"); this.stopserver = * new JMenuItem("Server beenden"); this.findserver = new * JMenuItem("Server suchen"); this.netzwerk.add(this.startserver); * this.netzwerk.add(this.stopserver); * this.netzwerk.add(this.findserver); */ this.netzwerk.add(new JMenuItem("noch nicht verf�gbar")); this.menubar.add(this.netzwerk); // Buttons for "Optionen" this.optionen = new JMenu("Optionen"); /* * this.spname = new JMenuItem("Spielername"); this.groesse = new * JMenuItem("Groesse"); this.optionen.add(this.spname); * this.optionen.add(this.groesse); */ this.optionen.add(new JMenuItem("noch nicht verf�gbar")); this.menubar.add(this.optionen); // set Menubar this.frame.setJMenuBar(this.menubar); }
public GUI(Launcher frame) { this.frame = frame; // Create Menubar this.menubar = new JMenuBar(); // Buttons for "Spiel" this.spiel = new JMenu("Spiel"); this.starten = new JMenuItem("Neustarten"); this.starten.addActionListener(this); this.beenden = new JMenuItem("Beenden"); this.beenden.addActionListener(this); // this.spiel.add(this.starten); this.spiel.add(this.beenden); this.menubar.add(this.spiel); // Buttons for "Netzwerk" this.netzwerk = new JMenu("Netzwerk"); /* * this.startserver = new JMenuItem("Server starten"); this.stopserver = * new JMenuItem("Server beenden"); this.findserver = new * JMenuItem("Server suchen"); this.netzwerk.add(this.startserver); * this.netzwerk.add(this.stopserver); * this.netzwerk.add(this.findserver); */ this.netzwerk.add(new JMenuItem("noch nicht verfügbar")); this.menubar.add(this.netzwerk); // Buttons for "Optionen" this.optionen = new JMenu("Optionen"); /* * this.spname = new JMenuItem("Spielername"); this.groesse = new * JMenuItem("Groesse"); this.optionen.add(this.spname); * this.optionen.add(this.groesse); */ this.optionen.add(new JMenuItem("noch nicht verfügbar")); this.menubar.add(this.optionen); // set Menubar this.frame.setJMenuBar(this.menubar); }
diff --git a/Routy/src/org/routy/ResultsActivity.java b/Routy/src/org/routy/ResultsActivity.java index d11d358..224f4fd 100644 --- a/Routy/src/org/routy/ResultsActivity.java +++ b/Routy/src/org/routy/ResultsActivity.java @@ -1,344 +1,344 @@ package org.routy; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import org.routy.model.PreferencesModel; import org.routy.model.Route; import org.routy.model.RouteOptimizePreference; import org.routy.sound.SoundPlayer; import org.routy.view.ResultsSegmentView; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.location.Address; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.MarkerOptions; public class ResultsActivity extends Activity { private static final int INSTRUCTIONS_DIALOG = 1; Context mContext; // MapFragment stuff private MapFragment mapFragment; private GoogleMap mMap; private List<LatLng> points; private List<Address> addresses; private SharedPreferences resultsActivityPrefs; // The Route sent by DestinationActivity Route route; private LinearLayout resultsLayout; private final String TAG = "ResultsActivity"; // private SoundPool sounds; // private int click; private RouteOptimizePreference routeOptimizePreference; // AudioManager audioManager; // float volume; @SuppressWarnings({ "unchecked" }) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_results); mContext = this; // audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); // volume = audioManager // .getStreamVolume(AudioManager.STREAM_SYSTEM); // // sounds = new SoundPool(3, AudioManager.STREAM_MUSIC, 0); // click = sounds.load(this, R.raw.routyclick, 1); // Get the layout containing the list of destination resultsLayout = (LinearLayout) findViewById(R.id.linearlayout_results); Bundle extras = getIntent().getExtras(); if (extras != null) { int distance = (Integer) extras.get("distance"); addresses = (ArrayList<Address>) extras.get("addresses"); // Log.v(TAG, "Results: " + addresses.size() + " addresses"); route = new Route(addresses, distance); routeOptimizePreference = (RouteOptimizePreference) extras.get("optimize_for"); } initMapView(); resultsActivityPrefs = getSharedPreferences("results_prefs", MODE_PRIVATE); // First-time user dialog cookie // boolean noobCookie = resultsActivityPrefs.getBoolean("noob_cookie", false); if (PreferencesModel.getSingleton().isResultsNoob()){ showNoobDialog(); userAintANoobNoMore(); } } /** * Displays an {@link AlertDialog} with one button that dismisses the dialog. Dialog displays helpful first-time info. * * @param message */ @SuppressWarnings("deprecation") private void showNoobDialog() { // Yes, this is deprecated, but there's a conflict with RA.java extending FragmentActivity and MapActivity showDialog(INSTRUCTIONS_DIALOG); } /** * If the user sees the first-time instruction dialog, they won't see it again next time. */ private void userAintANoobNoMore() { SharedPreferences.Editor ed = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit(); ed.putBoolean("results_noob", false); ed.commit(); PreferencesModel.getSingleton().setResultsNoob(false); } @Override protected Dialog onCreateDialog(int id) { switch(id){ case INSTRUCTIONS_DIALOG: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.results_noob_title); builder.setMessage(R.string.results_noob_instructions); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { return; } }); return builder.create(); } return null; } void initMapView() { mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapfrag_results); mMap = mapFragment.getMap(); points = new ArrayList<LatLng>(); if (mMap == null) { // Log.e(TAG, "map service is not available"); } else { try { MapsInitializer.initialize(this); buildResultsView(); } catch (Exception e) { // Log.e(TAG, "Error initializing Map -- " + e.getMessage()); } } //Drawable drawable = this.getResources().getDrawable(R.drawable.pin1); } private void zoomToOverlays(List<LatLng> points) { // Compute northeast and southeast corners // Marker icons are 67x67 for the largest one (home) LatLngBounds.Builder builder = LatLngBounds.builder(); for (LatLng point : points) { builder.include(point); } CameraUpdate update = CameraUpdateFactory.newLatLngBounds(builder.build(), 300, 300, 0); // TODO Need to figure out how to get the width of the viewing area mMap.animateCamera(update); } // Dynamically build the results screen by building a ResultsRowView, which inflates view_result_segment private void buildResultsView() { int addressesSize = route.getAddresses().size(); Address address = null; // TODO: do we need lastAddress? boolean isLastAddress = false; ResultsSegmentView v; LatLng latlng = null; for (int addressIndex = 0; addressIndex < addressesSize; addressIndex++) { address = route.getAddresses().get(addressIndex); // special case if it's the last segment if (addressIndex == addressesSize - 1) { isLastAddress = true; } // Convert all the lat/long values to LatLng objects to use for computing the map boundaries later latlng = new LatLng(address.getLatitude(), address.getLongitude()); points.add(latlng); if (addressIndex == 0) { // Set the initial camera position looking right at the origin location mMap.moveCamera(CameraUpdateFactory.newCameraPosition(CameraPosition.builder().target(latlng).build())); } mMap.addMarker(new MarkerOptions().position(latlng) .title(Util.getAddressText(address)) .icon(BitmapDescriptorFactory.fromResource(Util.getItemizedPinId(addressIndex)))); v = new ResultsSegmentView(mContext, address, addressIndex, isLastAddress) { @Override public void onSegmentClicked(int id, boolean isLastAddress) { SoundPlayer.playClick(ResultsActivity.this); showSegmentInGoogleMaps(id, isLastAddress); } @Override public void onAddressClicked(int id) { // Animate map to the address clicked on. animateToAddress(id); } }; resultsLayout.addView(v, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } // Sit-chee-ate the map zoomToOverlays(points); // Route information display TextView results_header = (TextView) findViewById(R.id.results_textview_header); if (routeOptimizePreference.equals(RouteOptimizePreference.PREFER_DISTANCE)) { String truncatedDistanceInMiles = convertMetersToMiles(route.getTotalDistance()); - results_header.setText(results_header.getText() + " distance is:\n" + truncatedDistanceInMiles + " miles:"); + results_header.setText(results_header.getText() + " distance is\n" + truncatedDistanceInMiles + " miles:"); } else if (routeOptimizePreference.equals(RouteOptimizePreference.PREFER_DURATION)) { String durationInMinutes = convertSecondsToMinutes(route.getTotalDistance()); - results_header.setText(results_header.getText() + " time is:\n" + durationInMinutes + " minutes:"); + results_header.setText(results_header.getText() + " time is\n" + durationInMinutes + " minutes:"); } } private void animateToAddress(int id) { try { LatLng target = points.get(id); // Log.v(TAG, "max zoom level is: " + mMap.getMaxZoomLevel()); mMap.animateCamera(CameraUpdateFactory.newCameraPosition(CameraPosition.builder().target(target).tilt(30).zoom(mMap.getMaxZoomLevel() - 3).build())); } catch (IndexOutOfBoundsException e) { // Log.e(TAG, "Trying to animate to address with id=" + id + " but that's out of bounds."); } } private void showSegmentInGoogleMaps(int id, boolean isLastAddress) { if (!isLastAddress){ /*if (PreferencesModel.getSingleton().isSoundsOn()) { volume = audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM); volume = volume / audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM); sounds.play(click, volume, volume, 1, 0, 1); }*/ // Get start and end Addresses from route[] - the index is the id in ResultsSegmentView Address startAddress = route.getAddresses().get(id); Address endAddress = route.getAddresses().get(id + 1); // Build call to Google Maps native app double startAddressLat = startAddress.getLatitude(); double startAddressLong = startAddress.getLongitude(); double endAddressLat = endAddress.getLatitude(); double endAddressLong = endAddress.getLongitude(); // Button segment GMaps call String mapsCall = "http://maps.google.com/maps?saddr=" + startAddressLat + "," + startAddressLong + "&daddr=" + endAddressLat + "," + endAddressLong; // Log.d(TAG, "maps segment call URI: " + mapsCall); // Open Google Maps App on the device Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(mapsCall)); startActivity(intent); } } private String convertMetersToMiles(int distanceInMeters) { final double MILE_RATIO = 0.000621371; double distanceInMiles = distanceInMeters * MILE_RATIO; return new DecimalFormat("#.##").format(distanceInMiles); } private String convertSecondsToMinutes(int durationInSeconds) { final double RATIO = 60; double durationInMinutes = durationInSeconds / RATIO; return Long.valueOf(Math.round(durationInMinutes)).toString(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_results, menu); return true; } @Override public void onStart() { super.onStart(); // Analytics EasyTracker.getInstance().activityStart(this); } @Override public void onStop() { super.onStop(); // Analytics EasyTracker.getInstance().activityStop(this); } /*@Override protected void onResume() { super.onResume(); // sounds = new SoundPool(3, AudioManager.STREAM_MUSIC, 0); // click = sounds.load(this, R.raw.routyclick, 1); }*/ @Override public void onPause() { super.onPause(); SoundPlayer.done(); } @Override public boolean onPrepareOptionsMenu(Menu menu) { return false; } }
false
true
private void buildResultsView() { int addressesSize = route.getAddresses().size(); Address address = null; // TODO: do we need lastAddress? boolean isLastAddress = false; ResultsSegmentView v; LatLng latlng = null; for (int addressIndex = 0; addressIndex < addressesSize; addressIndex++) { address = route.getAddresses().get(addressIndex); // special case if it's the last segment if (addressIndex == addressesSize - 1) { isLastAddress = true; } // Convert all the lat/long values to LatLng objects to use for computing the map boundaries later latlng = new LatLng(address.getLatitude(), address.getLongitude()); points.add(latlng); if (addressIndex == 0) { // Set the initial camera position looking right at the origin location mMap.moveCamera(CameraUpdateFactory.newCameraPosition(CameraPosition.builder().target(latlng).build())); } mMap.addMarker(new MarkerOptions().position(latlng) .title(Util.getAddressText(address)) .icon(BitmapDescriptorFactory.fromResource(Util.getItemizedPinId(addressIndex)))); v = new ResultsSegmentView(mContext, address, addressIndex, isLastAddress) { @Override public void onSegmentClicked(int id, boolean isLastAddress) { SoundPlayer.playClick(ResultsActivity.this); showSegmentInGoogleMaps(id, isLastAddress); } @Override public void onAddressClicked(int id) { // Animate map to the address clicked on. animateToAddress(id); } }; resultsLayout.addView(v, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } // Sit-chee-ate the map zoomToOverlays(points); // Route information display TextView results_header = (TextView) findViewById(R.id.results_textview_header); if (routeOptimizePreference.equals(RouteOptimizePreference.PREFER_DISTANCE)) { String truncatedDistanceInMiles = convertMetersToMiles(route.getTotalDistance()); results_header.setText(results_header.getText() + " distance is:\n" + truncatedDistanceInMiles + " miles:"); } else if (routeOptimizePreference.equals(RouteOptimizePreference.PREFER_DURATION)) { String durationInMinutes = convertSecondsToMinutes(route.getTotalDistance()); results_header.setText(results_header.getText() + " time is:\n" + durationInMinutes + " minutes:"); } }
private void buildResultsView() { int addressesSize = route.getAddresses().size(); Address address = null; // TODO: do we need lastAddress? boolean isLastAddress = false; ResultsSegmentView v; LatLng latlng = null; for (int addressIndex = 0; addressIndex < addressesSize; addressIndex++) { address = route.getAddresses().get(addressIndex); // special case if it's the last segment if (addressIndex == addressesSize - 1) { isLastAddress = true; } // Convert all the lat/long values to LatLng objects to use for computing the map boundaries later latlng = new LatLng(address.getLatitude(), address.getLongitude()); points.add(latlng); if (addressIndex == 0) { // Set the initial camera position looking right at the origin location mMap.moveCamera(CameraUpdateFactory.newCameraPosition(CameraPosition.builder().target(latlng).build())); } mMap.addMarker(new MarkerOptions().position(latlng) .title(Util.getAddressText(address)) .icon(BitmapDescriptorFactory.fromResource(Util.getItemizedPinId(addressIndex)))); v = new ResultsSegmentView(mContext, address, addressIndex, isLastAddress) { @Override public void onSegmentClicked(int id, boolean isLastAddress) { SoundPlayer.playClick(ResultsActivity.this); showSegmentInGoogleMaps(id, isLastAddress); } @Override public void onAddressClicked(int id) { // Animate map to the address clicked on. animateToAddress(id); } }; resultsLayout.addView(v, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } // Sit-chee-ate the map zoomToOverlays(points); // Route information display TextView results_header = (TextView) findViewById(R.id.results_textview_header); if (routeOptimizePreference.equals(RouteOptimizePreference.PREFER_DISTANCE)) { String truncatedDistanceInMiles = convertMetersToMiles(route.getTotalDistance()); results_header.setText(results_header.getText() + " distance is\n" + truncatedDistanceInMiles + " miles:"); } else if (routeOptimizePreference.equals(RouteOptimizePreference.PREFER_DURATION)) { String durationInMinutes = convertSecondsToMinutes(route.getTotalDistance()); results_header.setText(results_header.getText() + " time is\n" + durationInMinutes + " minutes:"); } }
diff --git a/zorka-agent/src/main/java/com/jitlogic/zorka/util/ObjectInspector.java b/zorka-agent/src/main/java/com/jitlogic/zorka/util/ObjectInspector.java index 3eed02c0..538bb593 100644 --- a/zorka-agent/src/main/java/com/jitlogic/zorka/util/ObjectInspector.java +++ b/zorka-agent/src/main/java/com/jitlogic/zorka/util/ObjectInspector.java @@ -1,151 +1,151 @@ package com.jitlogic.zorka.util; import com.jitlogic.zorka.agent.JmxObject; import javax.management.j2ee.statistics.Stats; import javax.management.openmbean.CompositeData; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Tools for introspection of various objects. * * TODO fix & describe get() semantics in more detail * * @author RLE <[email protected]> */ public class ObjectInspector { private final ZorkaLog log = ZorkaLogger.getLog(this.getClass()); public Method lookupMethod(Class<?> clazz, String name) { try { return name != null ? clazz.getMethod(name) : null; } catch (NoSuchMethodException e) { for (Class<?> icl : clazz.getInterfaces()) { Method m = lookupMethod(icl, name); if (m != null) { return m; } } Class<?> mcl = clazz; while ((mcl = mcl.getSuperclass()) != null && mcl != clazz) { Method m = lookupMethod(mcl, name); if (m != null) { return m; } } } return null; } public String methodName(String name, String prefix) { if (name.startsWith(".")) { return null; } if (name.endsWith("()")) { return name.substring(0, name.length()-2); } else { return prefix + name.substring(0,1).toUpperCase() + name.substring(1); } } public Method lookupGetter(Class<?> clazz, String name) { //String methodName Method m = lookupMethod(clazz, methodName(name, "get")); if (m != null) { return m; } m = lookupMethod(clazz, methodName(name, "is")); if (m != null) { return m; } m = lookupMethod(clazz, name); return m; } public Object get(Object obj, Object key) { if (obj == null) { return null; } else if (obj instanceof Map<?, ?>) { return ((Map<?,?>)obj).get(key); } else if (obj instanceof List<?>) { Integer idx = (Integer)ZorkaUtil.coerce(key, Integer.class); return idx != null ? ((List<?>)obj).get(idx) : null; } else if (obj.getClass().isArray()) { Integer idx = (Integer)ZorkaUtil.coerce(key, Integer.class); return idx != null ? ((Object[])obj)[idx] : null; } else if (obj instanceof CompositeData) { return ((CompositeData)obj).get(""+key); } else if (obj instanceof Stats){ return ((Stats)obj).getStatistic(""+key); } else if (obj instanceof JmxObject) { return ((JmxObject)obj).get(key); } else if (obj instanceof Class<?>) { String name = (String)key; if (name.endsWith("()")) { Method m = lookupGetter((Class)obj, name); try { return m.invoke(null); } catch (Exception e) { log.error("Method '" + m.getName() + "' invocation failed", e); return null; } } } if (key instanceof String) { String name = (String)key; Class<?> clazz = obj.getClass(); // Try getter method (if any) Method m = lookupGetter(clazz, name); if (m != null) { try { return m.invoke(obj); } catch (Exception e) { log.error("Method '" + m.getName() + "' invocation failed", e); return null; } } // Try field (if any) try { Field field = clazz.getField(name); - return field.get(name); + return field.get(obj); } catch (Exception e) { log.error("Field '" + name + "' fetch failed", e); return null; } } return null; } public List<String> listAttrNames(Object obj) { List<String> lst = new ArrayList<String>(); if (obj instanceof Map) { for (Object key : ((Map<?,?>)obj).keySet()) { lst.add(key.toString()); } } else if (obj instanceof Stats) { for (String name : ((Stats)obj).getStatisticNames()) { lst.add(name); } } // TODO uzupelnic return lst; } }
true
true
public Object get(Object obj, Object key) { if (obj == null) { return null; } else if (obj instanceof Map<?, ?>) { return ((Map<?,?>)obj).get(key); } else if (obj instanceof List<?>) { Integer idx = (Integer)ZorkaUtil.coerce(key, Integer.class); return idx != null ? ((List<?>)obj).get(idx) : null; } else if (obj.getClass().isArray()) { Integer idx = (Integer)ZorkaUtil.coerce(key, Integer.class); return idx != null ? ((Object[])obj)[idx] : null; } else if (obj instanceof CompositeData) { return ((CompositeData)obj).get(""+key); } else if (obj instanceof Stats){ return ((Stats)obj).getStatistic(""+key); } else if (obj instanceof JmxObject) { return ((JmxObject)obj).get(key); } else if (obj instanceof Class<?>) { String name = (String)key; if (name.endsWith("()")) { Method m = lookupGetter((Class)obj, name); try { return m.invoke(null); } catch (Exception e) { log.error("Method '" + m.getName() + "' invocation failed", e); return null; } } } if (key instanceof String) { String name = (String)key; Class<?> clazz = obj.getClass(); // Try getter method (if any) Method m = lookupGetter(clazz, name); if (m != null) { try { return m.invoke(obj); } catch (Exception e) { log.error("Method '" + m.getName() + "' invocation failed", e); return null; } } // Try field (if any) try { Field field = clazz.getField(name); return field.get(name); } catch (Exception e) { log.error("Field '" + name + "' fetch failed", e); return null; } } return null; }
public Object get(Object obj, Object key) { if (obj == null) { return null; } else if (obj instanceof Map<?, ?>) { return ((Map<?,?>)obj).get(key); } else if (obj instanceof List<?>) { Integer idx = (Integer)ZorkaUtil.coerce(key, Integer.class); return idx != null ? ((List<?>)obj).get(idx) : null; } else if (obj.getClass().isArray()) { Integer idx = (Integer)ZorkaUtil.coerce(key, Integer.class); return idx != null ? ((Object[])obj)[idx] : null; } else if (obj instanceof CompositeData) { return ((CompositeData)obj).get(""+key); } else if (obj instanceof Stats){ return ((Stats)obj).getStatistic(""+key); } else if (obj instanceof JmxObject) { return ((JmxObject)obj).get(key); } else if (obj instanceof Class<?>) { String name = (String)key; if (name.endsWith("()")) { Method m = lookupGetter((Class)obj, name); try { return m.invoke(null); } catch (Exception e) { log.error("Method '" + m.getName() + "' invocation failed", e); return null; } } } if (key instanceof String) { String name = (String)key; Class<?> clazz = obj.getClass(); // Try getter method (if any) Method m = lookupGetter(clazz, name); if (m != null) { try { return m.invoke(obj); } catch (Exception e) { log.error("Method '" + m.getName() + "' invocation failed", e); return null; } } // Try field (if any) try { Field field = clazz.getField(name); return field.get(obj); } catch (Exception e) { log.error("Field '" + name + "' fetch failed", e); return null; } } return null; }
diff --git a/src/main/java/skype/SkypePlayBroadcaster.java b/src/main/java/skype/SkypePlayBroadcaster.java index b63ed85..374980e 100644 --- a/src/main/java/skype/SkypePlayBroadcaster.java +++ b/src/main/java/skype/SkypePlayBroadcaster.java @@ -1,42 +1,41 @@ package skype; import com.skype.SkypeException; import com.skype.Stream; import com.thoughtworks.xstream.XStream; import sliceWars.RemotePlay; import sliceWars.RemotePlayListener; public class SkypePlayBroadcaster implements RemotePlayListener{ private RemotePlayListener local; private Stream stream; public void setLocalPlayer(RemotePlayListener local){ this.local = local; } public void setSkypePlayerStream(Stream stream){ this.stream = stream; } @Override public void play(RemotePlay play) { - if(stream != null){ - XStream xstream = new XStream(); - String xml = xstream.toXML(play); - try { - stream.write(xml); - } catch (SkypeException e) { - throw new RuntimeException(e); - } + XStream xstream = new XStream(); + String xml = xstream.toXML(play); + try { + stream.write(xml); + } catch (SkypeException e) { + throw new RuntimeException(e); } + local.play(play); } public void remotePlay(RemotePlay play) { if(local != null) local.play(play); } }
false
true
public void play(RemotePlay play) { if(stream != null){ XStream xstream = new XStream(); String xml = xstream.toXML(play); try { stream.write(xml); } catch (SkypeException e) { throw new RuntimeException(e); } } }
public void play(RemotePlay play) { XStream xstream = new XStream(); String xml = xstream.toXML(play); try { stream.write(xml); } catch (SkypeException e) { throw new RuntimeException(e); } local.play(play); }
diff --git a/src/org/trie/spellchecker/TrieSpellChecker.java b/src/org/trie/spellchecker/TrieSpellChecker.java index 70020ff..39d2d12 100644 --- a/src/org/trie/spellchecker/TrieSpellChecker.java +++ b/src/org/trie/spellchecker/TrieSpellChecker.java @@ -1,93 +1,93 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.trie.spellchecker; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Leandro Ordonez <[email protected]> */ public class TrieSpellChecker { public static final List<String> DICT = new ArrayList<>(); public static void initialize() { try { BufferedReader br = new BufferedReader(new FileReader("src/org/trie/util/american-english")); String line; while ((line = br.readLine()) != null) { DICT.add(line); } // System.out.println(DICT); } catch (FileNotFoundException ex) { Logger.getLogger(TrieSpellChecker.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(TrieSpellChecker.class.getName()).log(Level.SEVERE, null, ex); } } public static String compoundSplitter(String concatenatedWord) { return compoundSplitter(concatenatedWord, 0); } private static String compoundSplitter(String concatenatedWord, int level) { if (DICT.isEmpty()) { initialize(); } - if (DICT.contains(concatenatedWord)) { + if (DICT.contains(concatenatedWord) || DICT.contains(concatenatedWord.toLowerCase())) { return concatenatedWord; } else { String firstTerm, secondTerm, lastGoodFirst = "#none"; int i = 2; while (i <= concatenatedWord.length()) { firstTerm = concatenatedWord.substring(0, i); secondTerm = concatenatedWord.substring(i); if (DICT.contains(firstTerm)) { lastGoodFirst = firstTerm; if (DICT.contains(secondTerm)) { return firstTerm + " " + secondTerm; } else { i++; } //return firstTerm + " " + secondTerm; } else { if (firstTerm.equals(concatenatedWord)) { - if(level < 1){ + if(level < 1 && !lastGoodFirst.equals("#none")){ return lastGoodFirst + " " + compoundSplitter(concatenatedWord.substring(lastGoodFirst.length()), level+1); } else { - return (lastGoodFirst.equals("#none"))? "\b" + concatenatedWord : concatenatedWord; + return (level > 0)? "\b" + concatenatedWord : concatenatedWord; } } else { i++; } } } // System.out.println(lastFirstCorrect); } return concatenatedWord; } public static void main(String[] args) { System.out.println(TrieSpellChecker.compoundSplitter("housenumbernumeric")); // -> house number numeric System.out.println(TrieSpellChecker.compoundSplitter("wickedweather")); // -> wicked weather System.out.println(TrieSpellChecker.compoundSplitter("liquidweather")); // -> liquid weather System.out.println(TrieSpellChecker.compoundSplitter("driveourtrucks")); // -> drive our trucks System.out.println(TrieSpellChecker.compoundSplitter("gocompact")); // -> go compact System.out.println(TrieSpellChecker.compoundSplitter("slimprojector")); // -> slim projector System.out.println(TrieSpellChecker.compoundSplitter("orcore")); // -> or core System.out.println(TrieSpellChecker.compoundSplitter("zipcode")); // -> zip code System.out.println(TrieSpellChecker.compoundSplitter("asdkjkeerver")); // -> asdkjkeerver } }
false
true
private static String compoundSplitter(String concatenatedWord, int level) { if (DICT.isEmpty()) { initialize(); } if (DICT.contains(concatenatedWord)) { return concatenatedWord; } else { String firstTerm, secondTerm, lastGoodFirst = "#none"; int i = 2; while (i <= concatenatedWord.length()) { firstTerm = concatenatedWord.substring(0, i); secondTerm = concatenatedWord.substring(i); if (DICT.contains(firstTerm)) { lastGoodFirst = firstTerm; if (DICT.contains(secondTerm)) { return firstTerm + " " + secondTerm; } else { i++; } //return firstTerm + " " + secondTerm; } else { if (firstTerm.equals(concatenatedWord)) { if(level < 1){ return lastGoodFirst + " " + compoundSplitter(concatenatedWord.substring(lastGoodFirst.length()), level+1); } else { return (lastGoodFirst.equals("#none"))? "\b" + concatenatedWord : concatenatedWord; } } else { i++; } } } // System.out.println(lastFirstCorrect); } return concatenatedWord; }
private static String compoundSplitter(String concatenatedWord, int level) { if (DICT.isEmpty()) { initialize(); } if (DICT.contains(concatenatedWord) || DICT.contains(concatenatedWord.toLowerCase())) { return concatenatedWord; } else { String firstTerm, secondTerm, lastGoodFirst = "#none"; int i = 2; while (i <= concatenatedWord.length()) { firstTerm = concatenatedWord.substring(0, i); secondTerm = concatenatedWord.substring(i); if (DICT.contains(firstTerm)) { lastGoodFirst = firstTerm; if (DICT.contains(secondTerm)) { return firstTerm + " " + secondTerm; } else { i++; } //return firstTerm + " " + secondTerm; } else { if (firstTerm.equals(concatenatedWord)) { if(level < 1 && !lastGoodFirst.equals("#none")){ return lastGoodFirst + " " + compoundSplitter(concatenatedWord.substring(lastGoodFirst.length()), level+1); } else { return (level > 0)? "\b" + concatenatedWord : concatenatedWord; } } else { i++; } } } // System.out.println(lastFirstCorrect); } return concatenatedWord; }
diff --git a/src/pong/control/HitDetection.java b/src/pong/control/HitDetection.java index ca00aca..35755bb 100644 --- a/src/pong/control/HitDetection.java +++ b/src/pong/control/HitDetection.java @@ -1,88 +1,87 @@ package pong.control; import org.jbox2d.callbacks.ContactImpulse; import org.jbox2d.callbacks.ContactListener; import org.jbox2d.collision.Manifold; import org.jbox2d.dynamics.Body; import org.jbox2d.dynamics.contacts.Contact; import pong.model.*; public class HitDetection implements ContactListener { GameEngine ge; public HitDetection(GameEngine ge) { this.ge = ge; } @Override public void beginContact(Contact arg0) { GameItem item1 = (GameItem)arg0.getFixtureA().getBody().getUserData(); GameItem item2 = (GameItem)arg0.getFixtureB().getBody().getUserData(); //Has a ball hit a wall? if((item1 instanceof Ball && item2 instanceof Wall) || (item2 instanceof Ball && item1 instanceof Wall) ){ ballHitWall(item1, item2); } //Has a ball hit a paddle? if((item1 instanceof Paddle && item2 instanceof Ball) || (item2 instanceof Ball && item1 instanceof Paddle) ){ ballHitPaddle(item1, item2); } } private void ballHitPaddle(GameItem item1, GameItem item2) { // Play sound effect when a ball hits a paddle ge.playSound("blip.wav"); } private void ballHitWall(GameItem item1, GameItem item2){ Ball ball; Wall wall; if(item1 instanceof Ball){ ball = (Ball)item1; wall = (Wall)item2; }else{ ball = (Ball)item2; wall = (Wall)item1; } Player player; player = ge.getPlayer1(); if(player.getGoals().contains(wall)){ //Player 1's goal has been hit ge.ballOut(player); } player = ge.getPlayer2(); if(player.getGoals().contains(wall)){ //Player 2's goal has been hit ge.ballOut(player); } else if( !(player.getGoals().contains(wall)) && !(ge.getPlayer1().getGoals().contains(wall)) ){ // Regular wall has been hit, play wallsound - System.out.println("hej"); - ge.playSound("wallsound.wav"); + ge.playSound("wallsound2.wav"); } } @Override public void endContact(Contact arg0) { // TODO Auto-generated method stub } @Override public void postSolve(Contact arg0, ContactImpulse arg1) { // TODO Auto-generated method stub } @Override public void preSolve(Contact arg0, Manifold arg1) { // TODO Auto-generated method stub } }
true
true
private void ballHitWall(GameItem item1, GameItem item2){ Ball ball; Wall wall; if(item1 instanceof Ball){ ball = (Ball)item1; wall = (Wall)item2; }else{ ball = (Ball)item2; wall = (Wall)item1; } Player player; player = ge.getPlayer1(); if(player.getGoals().contains(wall)){ //Player 1's goal has been hit ge.ballOut(player); } player = ge.getPlayer2(); if(player.getGoals().contains(wall)){ //Player 2's goal has been hit ge.ballOut(player); } else if( !(player.getGoals().contains(wall)) && !(ge.getPlayer1().getGoals().contains(wall)) ){ // Regular wall has been hit, play wallsound System.out.println("hej"); ge.playSound("wallsound.wav"); } }
private void ballHitWall(GameItem item1, GameItem item2){ Ball ball; Wall wall; if(item1 instanceof Ball){ ball = (Ball)item1; wall = (Wall)item2; }else{ ball = (Ball)item2; wall = (Wall)item1; } Player player; player = ge.getPlayer1(); if(player.getGoals().contains(wall)){ //Player 1's goal has been hit ge.ballOut(player); } player = ge.getPlayer2(); if(player.getGoals().contains(wall)){ //Player 2's goal has been hit ge.ballOut(player); } else if( !(player.getGoals().contains(wall)) && !(ge.getPlayer1().getGoals().contains(wall)) ){ // Regular wall has been hit, play wallsound ge.playSound("wallsound2.wav"); } }
diff --git a/webapp/src/main/java/org/vaadin/tori/widgetset/client/ui/threadlistingrow/VThreadListingRow.java b/webapp/src/main/java/org/vaadin/tori/widgetset/client/ui/threadlistingrow/VThreadListingRow.java index bf9e5146..07261be3 100644 --- a/webapp/src/main/java/org/vaadin/tori/widgetset/client/ui/threadlistingrow/VThreadListingRow.java +++ b/webapp/src/main/java/org/vaadin/tori/widgetset/client/ui/threadlistingrow/VThreadListingRow.java @@ -1,381 +1,381 @@ /* * Copyright 2011 Vaadin 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.vaadin.tori.widgetset.client.ui.threadlistingrow; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import com.google.gwt.dom.client.Node; import com.google.gwt.dom.client.NodeList; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.logical.shared.CloseEvent; import com.google.gwt.event.logical.shared.CloseHandler; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Focusable; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HasWidgets; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.Widget; import com.vaadin.terminal.gwt.client.ApplicationConnection; import com.vaadin.terminal.gwt.client.ComponentConnector; import com.vaadin.terminal.gwt.client.UIDL; import com.vaadin.terminal.gwt.client.VCaptionWrapper; import com.vaadin.terminal.gwt.client.VConsole; import com.vaadin.terminal.gwt.client.VTooltip; import com.vaadin.terminal.gwt.client.ui.VOverlay; import com.vaadin.terminal.gwt.client.ui.richtextarea.VRichTextArea; public class VThreadListingRow extends HTML { public static final String CLASSNAME = "v-popupview"; /** For server-client communication */ String uidlId; ApplicationConnection client; /** This variable helps to communicate popup visibility to the server */ boolean hostPopupVisible; final CustomPopup popup; private final Label loading = new Label(); private int x = -1; private int y = -1; /** * loading constructor */ public VThreadListingRow() { super(); popup = new CustomPopup(); setStyleName(CLASSNAME); popup.setStyleName(CLASSNAME + "-popup"); loading.setStyleName(CLASSNAME + "-loading"); setHTML(""); popup.setWidget(loading); // When we click to open the popup... addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { final com.google.gwt.dom.client.Element elem = Element.as(event .getNativeEvent().getEventTarget()); if (elem.getClassName().contains("menutrigger")) { // bottom right corner of the menutrigger x = elem.getAbsoluteLeft() + elem.getOffsetWidth(); y = elem.getAbsoluteTop() + elem.getOffsetHeight(); // x = event.getClientX() + Window.getScrollLeft(); // y = event.getClientY() + Window.getScrollTop(); updateState(true); } else { final String threadURI = getThreadURI(getElement()); if (threadURI != null) { event.preventDefault(); event.stopPropagation(); - Window.Location.replace(threadURI); + Window.Location.assign(threadURI); } else { VConsole.error("Thread was clicked, but no URI was found for the thread."); } } } }); // ..and when we close it popup.addCloseHandler(new CloseHandler<PopupPanel>() { @Override public void onClose(final CloseEvent<PopupPanel> event) { x = -1; y = -1; updateState(false); } }); popup.setAnimationEnabled(true); sinkEvents(VTooltip.TOOLTIP_EVENTS); } private String getThreadURI(final Element thisElement) { final NodeList<Node> childNodes = thisElement.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { final Element e = (Element) childNodes.getItem(i); final String tagName = e.getTagName(); if ("a".equalsIgnoreCase(tagName)) { return e.getPropertyString("href"); } } return null; } /** * Update popup visibility to server * * @param y * @param x * * @param visibility */ private void updateState(final boolean visible) { // If we know the server connection // then update the current situation if (uidlId != null && client != null && isAttached()) { client.updateVariable(uidlId, "popupVisibility", visible, true); } } void preparePopup(final CustomPopup popup) { popup.setVisible(false); popup.show(); } /** * Determines the correct position for a popup and displays the popup at * that position. * * By default, the popup is shown centered relative to its host component, * ensuring it is visible on the screen if possible. * * Can be overridden to customize the popup position. * * @param popup */ protected void showPopup(final CustomPopup popup) { popup.setPopupPosition(0, 0); popup.setVisible(true); } void reposition() { if (x > 0 && y > 0) { popup.setPopupPosition(x, y); } else { VConsole.error("Can't position " + getClass().getName() + " popup."); } } /** * Make sure that we remove the popup when the main widget is removed. * * @see com.google.gwt.user.client.ui.Widget#onUnload() */ @Override protected void onDetach() { popup.hide(); super.onDetach(); } private static native void nativeBlur(Element e) /*-{ if(e && e.blur) { e.blur(); } }-*/; /** * This class is only protected to enable overriding showPopup, and is * currently not intended to be extended or otherwise used directly. Its API * (other than it being a VOverlay) is to be considered private and * potentially subject to change. */ protected class CustomPopup extends VOverlay { private ComponentConnector popupComponentPaintable = null; Widget popupComponentWidget = null; VCaptionWrapper captionWrapper = null; private boolean hasHadMouseOver = false; private boolean hideOnMouseOut = true; private final Set<Element> activeChildren = new HashSet<Element>(); private boolean hiding = false; public CustomPopup() { super(true, false, true); // autoHide, not modal, dropshadow } // For some reason ONMOUSEOUT events are not always received, so we have // to use ONMOUSEMOVE that doesn't target the popup @SuppressWarnings("deprecation") @Override public boolean onEventPreview(final Event event) { final Element target = DOM.eventGetTarget(event); final boolean eventTargetsPopup = DOM.isOrHasChild(getElement(), target); final int type = DOM.eventGetType(event); // Catch children that use keyboard, so we can unfocus them when // hiding if (eventTargetsPopup && type == Event.ONKEYPRESS) { activeChildren.add(target); } if (eventTargetsPopup && type == Event.ONMOUSEMOVE) { hasHadMouseOver = true; } if (!eventTargetsPopup && type == Event.ONMOUSEMOVE) { if (hasHadMouseOver && hideOnMouseOut) { hide(); return true; } } // Was the TAB key released outside of our popup? if (!eventTargetsPopup && type == Event.ONKEYUP && event.getKeyCode() == KeyCodes.KEY_TAB) { // Should we hide on focus out (mouse out)? if (hideOnMouseOut) { hide(); return true; } } return super.onEventPreview(event); } @Override public void hide(final boolean autoClosed) { hiding = true; syncChildren(); if (popupComponentWidget != null && popupComponentWidget != loading) { remove(popupComponentWidget); } hasHadMouseOver = false; super.hide(autoClosed); } @Override public void show() { if (!hiding) { hide(true); } hiding = false; super.show(); } /** * Try to sync all known active child widgets to server */ public void syncChildren() { // Notify children with focus if ((popupComponentWidget instanceof Focusable)) { ((Focusable) popupComponentWidget).setFocus(false); } else { checkForRTE(popupComponentWidget); } // Notify children that have used the keyboard for (final Element e : activeChildren) { try { nativeBlur(e); } catch (final Exception ignored) { } } activeChildren.clear(); } private void checkForRTE(final Widget popupComponentWidget2) { if (popupComponentWidget2 instanceof VRichTextArea) { ((VRichTextArea) popupComponentWidget2) .synchronizeContentToServer(); } else if (popupComponentWidget2 instanceof HasWidgets) { final HasWidgets hw = (HasWidgets) popupComponentWidget2; final Iterator<Widget> iterator = hw.iterator(); while (iterator.hasNext()) { checkForRTE(iterator.next()); } } } @Override public boolean remove(final Widget w) { popupComponentPaintable = null; popupComponentWidget = null; captionWrapper = null; return super.remove(w); } public void updateFromUIDL(final UIDL uidl, final ApplicationConnection client) { final ComponentConnector newPopupComponent = client .getPaintable(uidl.getChildUIDL(0)); if (newPopupComponent != popupComponentPaintable) { final Widget newWidget = newPopupComponent.getWidget(); setWidget(newWidget); popupComponentWidget = newWidget; popupComponentPaintable = newPopupComponent; } } public void setHideOnMouseOut(final boolean hideOnMouseOut) { this.hideOnMouseOut = hideOnMouseOut; } /* * * We need a hack make popup act as a child of VPopupView in Vaadin's * component tree, but work in default GWT manner when closing or * opening. * * (non-Javadoc) * * @see com.google.gwt.user.client.ui.Widget#getParent() */ @Override public Widget getParent() { if (!isAttached() || hiding) { return super.getParent(); } else { return VThreadListingRow.this; } } @Override protected void onDetach() { super.onDetach(); hiding = false; } @Override public Element getContainerElement() { return super.getContainerElement(); } }// class CustomPopup @Override public void onBrowserEvent(final Event event) { super.onBrowserEvent(event); if (client != null) { client.handleTooltipEvent(event, this); } } }// class VPopupView
true
true
public VThreadListingRow() { super(); popup = new CustomPopup(); setStyleName(CLASSNAME); popup.setStyleName(CLASSNAME + "-popup"); loading.setStyleName(CLASSNAME + "-loading"); setHTML(""); popup.setWidget(loading); // When we click to open the popup... addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { final com.google.gwt.dom.client.Element elem = Element.as(event .getNativeEvent().getEventTarget()); if (elem.getClassName().contains("menutrigger")) { // bottom right corner of the menutrigger x = elem.getAbsoluteLeft() + elem.getOffsetWidth(); y = elem.getAbsoluteTop() + elem.getOffsetHeight(); // x = event.getClientX() + Window.getScrollLeft(); // y = event.getClientY() + Window.getScrollTop(); updateState(true); } else { final String threadURI = getThreadURI(getElement()); if (threadURI != null) { event.preventDefault(); event.stopPropagation(); Window.Location.replace(threadURI); } else { VConsole.error("Thread was clicked, but no URI was found for the thread."); } } } }); // ..and when we close it popup.addCloseHandler(new CloseHandler<PopupPanel>() { @Override public void onClose(final CloseEvent<PopupPanel> event) { x = -1; y = -1; updateState(false); } }); popup.setAnimationEnabled(true); sinkEvents(VTooltip.TOOLTIP_EVENTS); }
public VThreadListingRow() { super(); popup = new CustomPopup(); setStyleName(CLASSNAME); popup.setStyleName(CLASSNAME + "-popup"); loading.setStyleName(CLASSNAME + "-loading"); setHTML(""); popup.setWidget(loading); // When we click to open the popup... addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { final com.google.gwt.dom.client.Element elem = Element.as(event .getNativeEvent().getEventTarget()); if (elem.getClassName().contains("menutrigger")) { // bottom right corner of the menutrigger x = elem.getAbsoluteLeft() + elem.getOffsetWidth(); y = elem.getAbsoluteTop() + elem.getOffsetHeight(); // x = event.getClientX() + Window.getScrollLeft(); // y = event.getClientY() + Window.getScrollTop(); updateState(true); } else { final String threadURI = getThreadURI(getElement()); if (threadURI != null) { event.preventDefault(); event.stopPropagation(); Window.Location.assign(threadURI); } else { VConsole.error("Thread was clicked, but no URI was found for the thread."); } } } }); // ..and when we close it popup.addCloseHandler(new CloseHandler<PopupPanel>() { @Override public void onClose(final CloseEvent<PopupPanel> event) { x = -1; y = -1; updateState(false); } }); popup.setAnimationEnabled(true); sinkEvents(VTooltip.TOOLTIP_EVENTS); }
diff --git a/src/swt/org/pathvisio/gui/swt/dialogs/CommentsDialog.java b/src/swt/org/pathvisio/gui/swt/dialogs/CommentsDialog.java index 0316bf74..ba43f5b3 100644 --- a/src/swt/org/pathvisio/gui/swt/dialogs/CommentsDialog.java +++ b/src/swt/org/pathvisio/gui/swt/dialogs/CommentsDialog.java @@ -1,164 +1,164 @@ // PathVisio, // a tool for data visualization and analysis using Biological Pathways // Copyright 2006-2007 BiGCaT Bioinformatics // // 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.pathvisio.gui.swt.dialogs; import java.util.Iterator; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.ICellModifier; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TextCellEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.pathvisio.model.PathwayElement; import org.pathvisio.model.PathwayElement.Comment; import org.pathvisio.util.swt.TableColumnResizer; public class CommentsDialog extends PathwayElementDialog { static final String[] tableHeaders = new String[] { "Source", "Comment" }; TableViewer tableViewer; public CommentsDialog(Shell parent, PathwayElement e) { super(parent, e); } protected Control createDialogArea(Composite parent) { Composite comp = (Composite)super.createDialogArea(parent); comp.setLayout(new GridLayout(2, false)); Composite tableComp = new Composite(comp, SWT.NONE); tableComp.setLayout(new FillLayout()); GridData g = new GridData(GridData.FILL_BOTH); g.horizontalSpan = 2; g.widthHint = 300; g.heightHint = 200; tableComp.setLayoutData(g); - Table t = new Table(tableComp, SWT.BORDER | SWT.MULTI | SWT.WRAP); + Table t = new Table(tableComp, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI | SWT.WRAP); t.setHeaderVisible(true); TableColumn tc1 = new TableColumn(t, SWT.NONE); TableColumn tc2 = new TableColumn(t, SWT.NONE); tc1.setText(tableHeaders[0]); tc2.setText(tableHeaders[1]); tc1.setWidth(50); tc2.setWidth(80); new TableColumnResizer(t, tableComp, new int[] { 30, 70 }); tableViewer = new TableViewer(t); tableViewer.setCellModifier(cellModifier); tableViewer.setLabelProvider(labelProvider); tableViewer.setColumnProperties(tableHeaders); tableViewer.setContentProvider(new ArrayContentProvider()); tableViewer.setCellEditors(new CellEditor[] { new TextCellEditor(t), new TextCellEditor(t) }); Button add = new Button(comp, SWT.PUSH); add.setText("Add comment"); add.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); Button remove = new Button(comp, SWT.PUSH); remove.setText("Remove comment"); add.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); add.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addPressed(); } }); remove.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { removePressed(); } }); tableViewer.setInput(input.getComments()); return comp; } protected void addPressed() { input.addComment("Type your comment here", ""); refresh(); } protected void removePressed() { Iterator it = ((IStructuredSelection)tableViewer.getSelection()).iterator(); while(it.hasNext()) { Comment c = (Comment)it.next(); input.removeComment(c); } refresh(); } ICellModifier cellModifier = new ICellModifier() { public boolean canModify(Object element, String property) { return true; } public Object getValue(Object element, String property) { Comment c = (Comment)element; String value = property.equals(tableHeaders[0]) ? c.getSource() : c.getComment(); return value == null ? "" : value; } public void modify(Object element, String property, Object value) { if(value == null) return; Comment c = (Comment)((TableItem)element).getData(); if(property.equals(tableHeaders[0])) { c.setSource((String)value); } else { c.setComment((String)value); } refresh(); } }; ITableLabelProvider labelProvider = new ITableLabelProvider() { public Image getColumnImage(Object element, int columnIndex) { return null; } public String getColumnText(Object element, int columnIndex) { Comment c = (Comment)element; return columnIndex == 0 ? c.getSource() : c.getComment(); } public void addListener(ILabelProviderListener listener) { } public void dispose() { } public boolean isLabelProperty(Object element, String property) { return false; } public void removeListener(ILabelProviderListener listener) { } }; protected void refresh() { tableViewer.refresh(); } }
true
true
protected Control createDialogArea(Composite parent) { Composite comp = (Composite)super.createDialogArea(parent); comp.setLayout(new GridLayout(2, false)); Composite tableComp = new Composite(comp, SWT.NONE); tableComp.setLayout(new FillLayout()); GridData g = new GridData(GridData.FILL_BOTH); g.horizontalSpan = 2; g.widthHint = 300; g.heightHint = 200; tableComp.setLayoutData(g); Table t = new Table(tableComp, SWT.BORDER | SWT.MULTI | SWT.WRAP); t.setHeaderVisible(true); TableColumn tc1 = new TableColumn(t, SWT.NONE); TableColumn tc2 = new TableColumn(t, SWT.NONE); tc1.setText(tableHeaders[0]); tc2.setText(tableHeaders[1]); tc1.setWidth(50); tc2.setWidth(80); new TableColumnResizer(t, tableComp, new int[] { 30, 70 }); tableViewer = new TableViewer(t); tableViewer.setCellModifier(cellModifier); tableViewer.setLabelProvider(labelProvider); tableViewer.setColumnProperties(tableHeaders); tableViewer.setContentProvider(new ArrayContentProvider()); tableViewer.setCellEditors(new CellEditor[] { new TextCellEditor(t), new TextCellEditor(t) }); Button add = new Button(comp, SWT.PUSH); add.setText("Add comment"); add.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); Button remove = new Button(comp, SWT.PUSH); remove.setText("Remove comment"); add.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); add.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addPressed(); } }); remove.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { removePressed(); } }); tableViewer.setInput(input.getComments()); return comp; }
protected Control createDialogArea(Composite parent) { Composite comp = (Composite)super.createDialogArea(parent); comp.setLayout(new GridLayout(2, false)); Composite tableComp = new Composite(comp, SWT.NONE); tableComp.setLayout(new FillLayout()); GridData g = new GridData(GridData.FILL_BOTH); g.horizontalSpan = 2; g.widthHint = 300; g.heightHint = 200; tableComp.setLayoutData(g); Table t = new Table(tableComp, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI | SWT.WRAP); t.setHeaderVisible(true); TableColumn tc1 = new TableColumn(t, SWT.NONE); TableColumn tc2 = new TableColumn(t, SWT.NONE); tc1.setText(tableHeaders[0]); tc2.setText(tableHeaders[1]); tc1.setWidth(50); tc2.setWidth(80); new TableColumnResizer(t, tableComp, new int[] { 30, 70 }); tableViewer = new TableViewer(t); tableViewer.setCellModifier(cellModifier); tableViewer.setLabelProvider(labelProvider); tableViewer.setColumnProperties(tableHeaders); tableViewer.setContentProvider(new ArrayContentProvider()); tableViewer.setCellEditors(new CellEditor[] { new TextCellEditor(t), new TextCellEditor(t) }); Button add = new Button(comp, SWT.PUSH); add.setText("Add comment"); add.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); Button remove = new Button(comp, SWT.PUSH); remove.setText("Remove comment"); add.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); add.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addPressed(); } }); remove.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { removePressed(); } }); tableViewer.setInput(input.getComments()); return comp; }
diff --git a/src/haven/PView.java b/src/haven/PView.java index 0f9b806e..7da8ceeb 100644 --- a/src/haven/PView.java +++ b/src/haven/PView.java @@ -1,185 +1,186 @@ /* * This file is part of the Haven & Hearth game client. * Copyright (C) 2009 Fredrik Tolf <[email protected]>, and * Björn Johannessen <[email protected]> * * Redistribution and/or modification of this file is subject to the * terms of the GNU Lesser General Public License, version 3, 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. * * Other parts of this source tree adhere to other copying * rights. Please see the file `COPYING' in the root directory of the * source tree for details. * * A copy the GNU Lesser General Public License is distributed along * with the source tree of which this file is a part in the file * `doc/LPGL-3'. If it is missing for any reason, please see the Free * Software Foundation's website at <http://www.fsf.org/>, or write * to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package haven; import static haven.GOut.checkerr; import javax.media.opengl.*; public abstract class PView extends Widget { private RenderList rls; public static final GLState.Slot<RenderState> proj = new GLState.Slot<RenderState>(RenderState.class, HavenPanel.proj2d); public static final GLState.Slot<Camera> cam = new GLState.Slot<Camera>(Camera.class, proj); public static final GLState.Slot<Location> loc = new GLState.Slot<Location>(Location.class, cam); public Profile prof = new Profile(300); protected Light.Model lm; private GLState pstate; public class RenderState extends GLState { public final float field = 0.5f; public final float aspect = ((float)sz.y) / ((float)sz.x); public final Matrix4f projmat = new Matrix4f(); public void apply(GOut g) { GL gl = g.gl; gl.glScissor(g.ul.x, ui.root.sz.y - g.ul.y - g.sz.y, g.sz.x, g.sz.y); gl.glViewport(g.ul.x, ui.root.sz.y - g.ul.y - g.sz.y, g.sz.x, g.sz.y); gl.glAlphaFunc(gl.GL_GREATER, 0.5f); gl.glEnable(gl.GL_DEPTH_TEST); gl.glEnable(gl.GL_CULL_FACE); gl.glEnable(gl.GL_SCISSOR_TEST); gl.glDepthFunc(gl.GL_LEQUAL); gl.glClearDepth(1.0); g.st.matmode(GL.GL_PROJECTION); gl.glPushMatrix(); gl.glLoadIdentity(); gl.glFrustum(-field, field, -aspect * field, aspect * field, 1, 5000); projmat.getgl(gl, GL.GL_PROJECTION_MATRIX); g.st.matmode(gl.GL_MODELVIEW); gl.glPushMatrix(); gl.glLoadIdentity(); } public void unapply(GOut g) { GL gl = g.gl; g.st.matmode(gl.GL_MODELVIEW); gl.glPopMatrix(); g.st.matmode(gl.GL_PROJECTION); gl.glPopMatrix(); gl.glDisable(gl.GL_DEPTH_TEST); gl.glDisable(gl.GL_CULL_FACE); gl.glDisable(gl.GL_SCISSOR_TEST); gl.glViewport(g.root().ul.x, g.root().ul.y, g.root().sz.x, g.root().sz.y); gl.glScissor(g.root().ul.x, g.root().ul.y, g.root().sz.x, g.root().sz.y); } public void prep(Buffer b) { b.put(proj, this); } public Coord3f toscreen(Coord3f ec) { float[] o = projmat.mul4(ec.to4a(1)); o[0] /= o[3]; o[1] /= o[3]; o[0] = ((o[0] + 1) / 2) * sz.x; o[1] = ((-o[1] + 1) / 2) * sz.y; return(new Coord3f(o[0], o[1], o[2])); } } public PView(Coord c, Coord sz, Widget parent) { super(c, sz, parent); pstate = new RenderState(); lm = new Light.Model(); lm.cc = GL.GL_SEPARATE_SPECULAR_COLOR; } protected GLState.Buffer basic(GOut g) { GLState.Buffer buf = g.st.copy(); pstate.prep(buf); camera().prep(buf); return(buf); } protected abstract Camera camera(); protected abstract void setup(RenderList rls); public void resize(Coord sz) { super.resize(sz); pstate = new RenderState(); } private final Rendered scene = new Rendered() { public void draw(GOut g) { } public Order setup(RenderList rl) { PView.this.setup(rl); return(null); } }; public void draw(GOut g) { if(rls == null) rls = new RenderList(g.gc); Profile.Frame curf = null; if(Config.profile) curf = prof.new Frame(); GLState.Buffer bk = g.st.copy(); GLState.Buffer def = basic(g); if(g.gc.fsaa) States.fsaa.prep(def); try { lm.prep(def); new Light.LightList().prep(def); rls.setup(scene, def); if(curf != null) curf.tick("setup"); rls.sort(); if(curf != null) curf.tick("sort"); g.st.set(def); g.apply(); if(curf != null) curf.tick("cls"); GL gl = g.gl; gl.glClear(gl.GL_DEPTH_BUFFER_BIT | gl.GL_COLOR_BUFFER_BIT); g.st.time = 0; rls.render(g); if(curf != null) { curf.add("apply", g.st.time); curf.tick("render", g.st.time); } } finally { g.st.set(bk); } for(int i = 0; i < rls.cur; i++) { if(rls.list[i].r instanceof Render2D) ((Render2D)rls.list[i].r).draw2d(g); } - curf.tick("2d"); + if(curf != null) + curf.tick("2d"); if(curf != null) curf.fin(); } public interface Render2D extends Rendered { public void draw2d(GOut g); } public static abstract class Draw2D implements Render2D { public void draw(GOut g) {} public Order setup(RenderList r) { return(null); } } }
true
true
public void draw(GOut g) { if(rls == null) rls = new RenderList(g.gc); Profile.Frame curf = null; if(Config.profile) curf = prof.new Frame(); GLState.Buffer bk = g.st.copy(); GLState.Buffer def = basic(g); if(g.gc.fsaa) States.fsaa.prep(def); try { lm.prep(def); new Light.LightList().prep(def); rls.setup(scene, def); if(curf != null) curf.tick("setup"); rls.sort(); if(curf != null) curf.tick("sort"); g.st.set(def); g.apply(); if(curf != null) curf.tick("cls"); GL gl = g.gl; gl.glClear(gl.GL_DEPTH_BUFFER_BIT | gl.GL_COLOR_BUFFER_BIT); g.st.time = 0; rls.render(g); if(curf != null) { curf.add("apply", g.st.time); curf.tick("render", g.st.time); } } finally { g.st.set(bk); } for(int i = 0; i < rls.cur; i++) { if(rls.list[i].r instanceof Render2D) ((Render2D)rls.list[i].r).draw2d(g); } curf.tick("2d"); if(curf != null) curf.fin(); }
public void draw(GOut g) { if(rls == null) rls = new RenderList(g.gc); Profile.Frame curf = null; if(Config.profile) curf = prof.new Frame(); GLState.Buffer bk = g.st.copy(); GLState.Buffer def = basic(g); if(g.gc.fsaa) States.fsaa.prep(def); try { lm.prep(def); new Light.LightList().prep(def); rls.setup(scene, def); if(curf != null) curf.tick("setup"); rls.sort(); if(curf != null) curf.tick("sort"); g.st.set(def); g.apply(); if(curf != null) curf.tick("cls"); GL gl = g.gl; gl.glClear(gl.GL_DEPTH_BUFFER_BIT | gl.GL_COLOR_BUFFER_BIT); g.st.time = 0; rls.render(g); if(curf != null) { curf.add("apply", g.st.time); curf.tick("render", g.st.time); } } finally { g.st.set(bk); } for(int i = 0; i < rls.cur; i++) { if(rls.list[i].r instanceof Render2D) ((Render2D)rls.list[i].r).draw2d(g); } if(curf != null) curf.tick("2d"); if(curf != null) curf.fin(); }
diff --git a/trunk/CruxBasicWidgets/src/br/com/sysmap/crux/basic/client/FlexTableFactory.java b/trunk/CruxBasicWidgets/src/br/com/sysmap/crux/basic/client/FlexTableFactory.java index d748c8956..d5ca0b9cd 100644 --- a/trunk/CruxBasicWidgets/src/br/com/sysmap/crux/basic/client/FlexTableFactory.java +++ b/trunk/CruxBasicWidgets/src/br/com/sysmap/crux/basic/client/FlexTableFactory.java @@ -1,52 +1,52 @@ /* * 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.basic.client; import com.google.gwt.dom.client.Element; import com.google.gwt.user.client.ui.FlexTable; /** * Factory for FlexTable widget * @author Thiago Bustamante */ public class FlexTableFactory extends HTMLTableFactory<FlexTable> { @Override protected FlexTable instantiateWidget(Element element, String widgetId) { return new FlexTable(); } @Override protected void prepareCell(FlexTable widget, int indexRow, int indexCol, String widgetId) { if (indexRow < 0 || indexCol < 0) { throw new IndexOutOfBoundsException(messages.flexTableInvalidRowColIndexes(widgetId)); } - int r = 0; + int r = widget.getRowCount(); while (widget.getRowCount() < indexRow+1) { widget.insertRow(r++); } - if (widget.getCellCount(indexRow) < indexCol+1) + while (widget.getCellCount(indexRow) < indexCol+1) { widget.addCell(indexRow); } } }
false
true
protected void prepareCell(FlexTable widget, int indexRow, int indexCol, String widgetId) { if (indexRow < 0 || indexCol < 0) { throw new IndexOutOfBoundsException(messages.flexTableInvalidRowColIndexes(widgetId)); } int r = 0; while (widget.getRowCount() < indexRow+1) { widget.insertRow(r++); } if (widget.getCellCount(indexRow) < indexCol+1) { widget.addCell(indexRow); } }
protected void prepareCell(FlexTable widget, int indexRow, int indexCol, String widgetId) { if (indexRow < 0 || indexCol < 0) { throw new IndexOutOfBoundsException(messages.flexTableInvalidRowColIndexes(widgetId)); } int r = widget.getRowCount(); while (widget.getRowCount() < indexRow+1) { widget.insertRow(r++); } while (widget.getCellCount(indexRow) < indexCol+1) { widget.addCell(indexRow); } }
diff --git a/org/codalang/codaserver/CodaServer.java b/org/codalang/codaserver/CodaServer.java index f96f0cd..4aad967 100644 --- a/org/codalang/codaserver/CodaServer.java +++ b/org/codalang/codaserver/CodaServer.java @@ -1,8139 +1,8139 @@ /* * Main.java * * Created on February 22, 2007, 6:53 PM * * CodaServer and related original technologies are copyright 2008, 18th Street Software, LLC. * * Permission to use them is granted under the terms of the GNU GPLv2. */ package org.codalang.codaserver; import com.caucho.hessian.client.HessianProxyFactory; import com.stevesoft.pat.Regex; import groovy.lang.GroovyClassLoader; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; import org.codalang.codaserver.database.*; import org.codalang.codaserver.executioncontext.ExecutionContext; import org.codalang.codaserver.httpServer.ICodaAPI; import org.codalang.codaserver.httpServer.httpServer; import org.codalang.codaserver.language.CaseInsensitiveStringStream; import org.codalang.codaserver.language.CodaLexer; import org.codalang.codaserver.language.CodaParser; import org.codalang.codaserver.language.objects.*; import org.codalang.codaserver.language.types.BaseCodaProcedure; import org.codalang.codaserver.language.types.Database; import org.ho.yaml.Yaml; import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; import sun.misc.BASE64Encoder; import java.io.*; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.SQLException; import java.sql.Types; import java.text.ParseException; import java.util.*; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author michaelarace */ public class CodaServer { public static final int OBJECT_TYPE_DATASOURCE = 1; public static final int OBJECT_TYPE_USER = 2; public static final int OBJECT_TYPE_GROUP = 3; public static final int OBJECT_TYPE_ROLE = 4; public static final int OBJECT_TYPE_PERMISSION = 5; public static final int OBJECT_TYPE_TYPE = 6; public static final int OBJECT_TYPE_TABLE = 7; public static final int OBJECT_TYPE_APPLICATION = 8; public static final int OBJECT_TYPE_TABLE_COLUMN = 9; public static final int OBJECT_TYPE_FORM_STATUS_ADJ = 10; public static final int OBJECT_TYPE_FORM_STATUS_VERB = 11; public static final int OBJECT_TYPE_CRON = 12; public static final int OBJECT_TYPE_INDEX = 13; public static final int OBJECT_TYPE_PROCEDURE = 14; public static final int OBJECT_TYPE_TABLE_TRIGGER = 15; public static final int OBJECT_TYPE_FORM_TRIGGER = 16; // the variables of the server private Configuration configuration; private String configPath = "./conf" + System.getProperty("file.separator") + "coda.conf"; private Logger logger; private CodaDatabase database; private FancyGroovyClassLoader classLoader = new FancyGroovyClassLoader(this.getClass().getClassLoader()); private String listenerString = "CodaServer HTTP Listener 1.0"; private boolean useTypeCache = true; // some variables for determining system state. These are only used if caching is enabled. private SessionContainer sessions; private DeployedApplicationContainer deployedApplications; //The Cron scheduler private Scheduler scheduler; //private Hashtable<String,Scheduler> schedulers; //The types hashtable private Hashtable<Long,TypeParser> types = new Hashtable(); // the WebServer Object private httpServer webServer; /** Creates a new instance of Main * @param configPath*/ public CodaServer(String configPath) { // Kill stderr PrintStream errTemp = System.err; System.setErr(new PrintStream(new ByteArrayOutputStream())); this.configPath = configPath; // Read the configuration file try { this.configuration = Yaml.loadType(new File(configPath), Configuration.class ); } catch (FileNotFoundException e) { System.out.println("Error reading configuration file at \""+ configPath +"\""); System.exit(0); } // Instantiate the logger try { logger = java.util.logging.Logger.getLogger("org.codalang.codaserver"); String logDir = "log" + System.getProperty("file.separator"); if (configuration.getLogDirectory() != null) { logDir = configuration.getLogDirectory()+ System.getProperty("file.separator"); } logger.addHandler(new FileHandler(logDir + "coda_%u-%g.log", 5000000, 100)); } catch (IOException e) { System.out.println("Error initializing the logger. Can I write there?"); System.exit(0); } /* System.setErr(errTemp); */ } /** * @param args the command line arguments */ public static void main(String[] args) { int newPort = -1; String configPath = "conf" + System.getProperty("file.separator") + "coda.conf", username = "", password = "", rootPassword = "password"; boolean doFormat = false; for (int i = 0; i < args.length; i++) { if (args[i].equalsIgnoreCase("-p")) { try { newPort = Integer.parseInt(args[i+1]); i++; } catch (NumberFormatException e) { //do nothing } } else if (args[i].equalsIgnoreCase("-c")) { File temp = new File(args[i+1]); if (temp.isFile() && temp.canRead()) { configPath = args[i+1]; } i++; } else if (args[i].equalsIgnoreCase("-format")) { doFormat = true; username = args[i+1]; if (args[i+2].equals("\"\"")) { password = ""; } else { password = args[i+2]; } rootPassword = args[i+3]; i = i + 3; } } CodaServer app = new CodaServer(configPath); if (newPort > 0) { app.setPort(newPort); } // for test /* doFormat = true; username = "sa"; password = ""; rootPassword = "password"; /*/ if (doFormat) { app.formatConfigDatabase(username, password, rootPassword, true); } else { app.start(); } } public void start () { // Connect to the server database if (this.configuration.getDatabaseConfiguration()[0].configurationComplete()) { try { Class.forName(this.configuration.getDatabaseConfiguration()[0].getDriverClass()); } catch (ClassNotFoundException e) { System.out.println("The specified driver class, \"" + this.configuration.getDatabaseConfiguration()[0].getDriverClass() + "\", is not in the classpath."); System.exit(0); } try { database = (CodaDatabase) Class.forName(this.configuration.getDatabaseConfiguration()[0].getDriverClass()).newInstance(); database.setLogger(logger); Hashtable<String,String> options = new Hashtable<String,String>(); for (int i =0; i < this.configuration.getDatabaseConfiguration()[0].getOptions().length; i++) { options.put(this.configuration.getDatabaseConfiguration()[0].getOptions()[i].getSetting(), this.configuration.getDatabaseConfiguration()[0].getOptions()[i].getValue()); } if (database.connect(configuration.getDatabaseConfiguration()[0].getHostname(), configuration.getDatabaseConfiguration()[0].getUsername(), configuration.getDatabaseConfiguration()[0].getPassword(), configuration.getDatabaseConfiguration()[0].getSchema(), options)) { System.out.println("CodaServer Database connected!"); } else { System.out.println("Can't connect to the database specified in the configuration file. Please make sure the information is entered correctly."); System.exit(0); } } catch (ClassNotFoundException e) { System.out.println("The specified driver class, \"" + this.configuration.getDatabaseConfiguration()[0].getDriverClass() + "\", is not in the classpath."); System.exit(0); } catch (InstantiationException e) { System.out.println("We can't seem to connect to the database. Are the username and password correct?"); System.exit(0); } catch (IllegalAccessException e) { System.out.println("We can't seem to connect to the database. Are the username and password correct?"); System.exit(0); } } else { System.out.println("The database configuration was incomplete. Please check it and try again."); System.exit(0); } // Load the applications deployedApplications = new DeployedApplicationContainer(database, true, logger); deployedApplications.initialize(false, classLoader); // Start the sesion container this.sessions = new SessionContainer(database, true); // Get a connection CodaConnection connection = database.getConnection(); // Load the types try { Class.forName("org.codalang.codaserver.language.types.Longstring"); Class.forName("org.codalang.codaserver.language.types.File"); Class.forName("org.codalang.codaserver.language.types.Database"); Class.forName("org.codalang.codaserver.language.types.Timestamp"); Class.forName("org.codalang.codaserver.language.types.Reference"); } catch (ClassNotFoundException e) { System.out.println("Cannot load built-in type classes."); System.exit(0); } CodaResultSet rs3 = connection.runQuery("select id, built_in_flag, type_name, validation_mask, save_mask, class_file from types where built_in_flag = 1 or active_flag = 1 " , null); if (!rs3.getErrorStatus()) { while (rs3.next()) { if (rs3.getDataInt(1) == 1) { types.put(rs3.getDataLong(0), new TypeParser(rs3.getDataLong(0), rs3.getData(2).toUpperCase())); } else { types.put(rs3.getDataLong(0), new TypeParser(rs3.getDataLong(0), rs3.getData(2).toUpperCase(), rs3.getData(3), rs3.getData(4))); this.reloadType(rs3.getDataLong(0)); //this.loadClass("org.codalang.codaserver.language.types.user." + CodaServer.camelCapitalize(rs3.getData(2), true), rs3.getData(5)); } } } else { System.out.println("Cannot load type information; is your database valid?"); System.exit(0); } if(this.configuration.getRunCron() == 1) { // initialize the scheduler Properties schedulerProps = new Properties(); schedulerProps.setProperty("org.quartz.scheduler.instanceName", "scheduler"); schedulerProps.setProperty("org.quartz.scheduler.instanceId", "1"); schedulerProps.setProperty("org.quartz.scheduler.rmi.export", "false"); schedulerProps.setProperty("org.quartz.scheduler.rmi.proxy", "false"); schedulerProps.setProperty("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool"); schedulerProps.setProperty("org.quartz.threadPool.threadCount", "20"); schedulerProps.setProperty("org.quartz.jobStore.class", "org.quartz.simpl.RAMJobStore"); StdSchedulerFactory schedFactory = new StdSchedulerFactory(); try { schedFactory.initialize(schedulerProps); scheduler = schedFactory.getScheduler(); } catch (org.quartz.SchedulerException e) { System.out.println("Problem with default scheduler settings. You can fix it if you read Java."); System.exit(0); } // Set the session killer JobDetail sessionDetail = new JobDetail("SessionTimer", null, SessionTimerJob.class); JobDataMap sessionMap = new JobDataMap(); sessionMap.put("server", this); sessionDetail.setJobDataMap(sessionMap); try { this.scheduleJob("SESSION_TIMER", "0 1/1 * * * ?", sessionDetail); } catch (ParseException pe) { System.out.println("...SessionTimerCron failed to launch."); } catch (SchedulerException se) { System.out.println("...SessionTimerCron failed to launch."); } // load the application crons //* System.out.println("Loading crons..."); Hashtable<String,DeployedApplication> apps = deployedApplications.getDeployedApplications(); for (String appName : apps.keySet()) { DeployedApplication da = apps.get(appName); for (int i = 1; i < 4; i++) { CodaDatabase db = null; if (da.getEnvironmentDatasource(i) != null) { db = da.getEnvironmentDatasource(i).getDatabase(); } if (db != null) { CodaConnection appConnection = db.getConnection(); String prefix = appConnection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix =""; } CodaResultSet rs = appConnection.runQuery("select c.id, c.cron_name, c.minute_part, c.hour_part, c.day_of_month_part, c.month_part, c.day_of_week_part, p.procedure_name, c.executing_user_name from "+prefix+"crons c inner join "+prefix+"procedures p on p.id = c.procedure_id " ,null); if (!rs.getErrorStatus()) { if (rs.getRowsReturned() == 0) { System.out.println("...Done."); } else { while (rs.next()) { long executingUserId = this.getIdForObjectName(connection, rs.getData(8), this.OBJECT_TYPE_USER); if (executingUserId > 0) { Vector<String> parameters = new Vector(); CodaResultSet rs1 = appConnection.runQuery("select p.parameter_value from "+prefix+"cron_parameters p where p.cron_id " + appConnection.formatStringForSQL("cron_parameters", "cron_id", rs.getData(0)) + " order by p.procedure_parameter_id asc ",null); if (!rs1.getErrorStatus()) { while (rs1.next()) { parameters.add(rs1.getData(0)); } } JobDetail detail = new JobDetail(appName.toUpperCase() + "_" + i + "_" + rs.getData(1), null, ProcedureJob.class); JobDataMap map = new JobDataMap(); map.put("cronName", rs.getData(1)); map.put("server", this); map.put("applicationName", appName); map.put("environment", i); map.put("procedureName", rs.getData(7)); map.put("parameters", parameters); map.put("userId", executingUserId); detail.setJobDataMap(map); try { this.scheduleJob(appName, i, rs.getData(1), "0 " + rs.getData(2) + " " + rs.getData(3) + " " + rs.getData(4) + " " + rs.getData(5) + " " + rs.getData(6), detail); } catch (ParseException pe) { System.out.println("..." + appName + ":" + (i == 1 ? "DEV" : (i == 2 ? "TEST" : "PROD")) + " Failed. Check cron " + rs.getData(1) + " for sanity."); } catch (SchedulerException se) { System.out.println("..." + appName + ":" + (i == 1 ? "DEV" : (i == 2 ? "TEST" : "PROD")) + " Failed. The scheduler is acting up."); } System.out.println("..." + appName + ":" + (i == 1 ? "DEV" : (i == 2 ? "TEST" : "PROD")) + " Worked!"); } } System.out.println("...Done."); } } else { System.out.println("..." + appName + ":" + (i == 1 ? "DEV" : (i == 2 ? "TEST" : "PROD")) + " Failed. Is its database up?"); } } } } try { scheduler.start(); System.out.println("Scheduler initialized!"); } catch (SchedulerException e) { System.out.println("Cannot initialize scheduler!"); } //*/ if (this.getClustedFlag()) { connection.runStatement("delete from cluster where ip_address = " +connection.formatStringForSQL("cluster", "ip_address", this.getIpAddress()) + " amd port = " + connection.formatStringForSQL("cluster", "port", Integer.toString(this.getPort()))); Hashtable values = new Hashtable(); values.put("ip_address", this.getIpAddress()); values.put("port", this.getPort()); values.put("run_crons", this.configuration.getRunCron()); connection.insertRow("cluster", values); connection.commit(); } } System.out.println("Starting CodaServer Server..."); webServer = new httpServer(logger, configuration.getListenerConfiguration()[0].getPort(), configuration.getListenerConfiguration()[0].getSoTimeout(), configuration.getListenerConfiguration()[0].getSocketBufferSize(), configuration.getListenerConfiguration()[0].getStaleConnectorCheck() == 1, configuration.getListenerConfiguration()[0].getTcpNoDelay() == 1, listenerString); System.out.println("Socket open on port " + configuration.getListenerConfiguration()[0].getPort() + ". Enjoy!"); webServer.start(this); } public void setPort(int port) { configuration.getListenerConfiguration()[0].setPort(port); } public SessionContainer getSessions() { return sessions; } public String getIpAddress() { return configuration.getListenerConfiguration()[0].getIpAddress(); } public int getPort() { return configuration.getListenerConfiguration()[0].getPort(); } // These are utility functions public boolean getClustedFlag () { return this.configuration.getCluster() == 1; } public Vector getClustedSystems() { Vector retval = new Vector(); if (this.getClustedFlag()) { CodaResultSet rs = database.getConnection().runQuery("select ip_address, port from cluster where ip_address <> " + database.getConnection().formatStringForSQL("cluster", "ip_address", this.getIpAddress()) + " and port <> " + database.getConnection().formatStringForSQL("cluster", "port", Integer.toString(this.getPort())), null); if (!rs.getErrorStatus()) { while (rs.next()) { Hashtable temp = new Hashtable(); temp.put("ip_address", rs.getData(0)); temp.put("port", rs.getDataInt(1)); retval.add(temp); } } } return retval; } public void sendTypeUpdateToCluster (long typeId) { if (this.getClustedFlag()) { HessianProxyFactory factory = new HessianProxyFactory(); Vector<Hashtable> servers = this.getClustedSystems(); for (Hashtable value : servers) { ICodaAPI basic; try { basic = (ICodaAPI) factory.create(ICodaAPI.class, "http://" + (String)value.get("ip_address") + ":" + (Integer)value.get("port")); basic.reloadType(this.getIpAddress(), this.getPort(), typeId); // test if errors or data } catch ( java.net.MalformedURLException e ) { this.log(Level.WARNING, "Please check the hostname and port."); } catch (com.caucho.hessian.client.HessianRuntimeException ex) { this.log(Level.WARNING, "There was a runtime exception talking to the server, probably a timeout."); } } } } public void sendSessionUpdateToCluster (String sessionKey) { if (this.getClustedFlag()) { HessianProxyFactory factory = new HessianProxyFactory(); Vector<Hashtable> servers = this.getClustedSystems(); for (Hashtable value : servers) { ICodaAPI basic; try { basic = (ICodaAPI) factory.create(ICodaAPI.class, "http://" + (String)value.get("ip_address") + ":" + (Integer)value.get("port")); basic.reloadSession(this.getIpAddress(), this.getPort(), sessionKey); // test if errors or data } catch ( java.net.MalformedURLException e ) { this.log(Level.WARNING, "Please check the hostname and port."); } catch (com.caucho.hessian.client.HessianRuntimeException ex) { this.log(Level.WARNING, "There was a runtime exception talking to the server, probably a timeout."); } } } } public void sendApplicationUpdateToCluster (String applicationName, String environment) { if (this.getClustedFlag()) { HessianProxyFactory factory = new HessianProxyFactory(); Vector<Hashtable> servers = this.getClustedSystems(); for (Hashtable value : servers) { ICodaAPI basic; try { basic = (ICodaAPI) factory.create(ICodaAPI.class, "http://" + (String)value.get("ip_address") + ":" + (Integer)value.get("port")); basic.reloadApplication(this.getIpAddress(), this.getPort(), applicationName, environment); // test if errors or data } catch ( java.net.MalformedURLException e ) { this.log(Level.WARNING, "Please check the hostname and port."); } catch (com.caucho.hessian.client.HessianRuntimeException ex) { this.log(Level.WARNING, "There was a runtime exception talking to the server, probably a timeout."); } } } } public boolean verifyClusterMember(String ipAddress, int port) { if (this.getClustedFlag()) { CodaConnection connection = database.getConnection(); CodaResultSet rs = connection.runQuery("select count(*) from cluser where ip_address = " + connection.formatStringForSQL("cluster", "ip_address", ipAddress) + " and port = "+Integer.toString(port), null); if (!rs.getErrorStatus() && rs.next()) { return rs.getDataInt(0) == 1; } else { return false; } } else { return false; } } public static String encrypt(String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch(NoSuchAlgorithmException e) { // do nothing } try { md.update(password.getBytes("UTF-8")); } catch(UnsupportedEncodingException e) { // do nothing } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } public void loadClass(String className, String classFile) { //if (this.configuration.getUseCache() == 1) { Class groovyClass = classLoader.parseClass(classFile); classLoader.linkClass(groovyClass); try { Class.forName(className, true, classLoader); } catch (ClassNotFoundException ex) { logger.log(Level.WARNING, "Class '" + className + "' was not found in the classloader."); } //} } public static void addRootPermissions(CodaConnection connection, String applicationName) { String userId = "1"; CodaResultSet rs = connection.runQuery("select id from users where user_name = 'ROOT'",null); if (!rs.getErrorStatus() && rs.next()) { userId = rs.getData(0); } if (applicationName == null) { Hashtable<String,Object> values = new Hashtable<String,Object>(); values.put("user_id", userId); values.put("server_permission_name", "CONNECT"); connection.insertRow("user_server_permissions", values); values.put("server_permission_name", "MANAGE_USERS"); connection.insertRow("user_server_permissions", values); values.put("server_permission_name", "MANAGE_USER_DATA"); connection.insertRow("user_server_permissions", values); values.put("server_permission_name", "MANAGE_GROUPS"); connection.insertRow("user_server_permissions", values); values.put("server_permission_name", "MANAGE_TYPES"); connection.insertRow("user_server_permissions", values); values.put("server_permission_name", "MANAGE_APPLICATIONS"); connection.insertRow("user_server_permissions", values); values.put("server_permission_name", "MANAGE_DATASOURCES"); connection.insertRow("user_server_permissions", values); values.put("server_permission_name", "MANAGE_SESSIONS"); connection.insertRow("user_server_permissions", values); values.put("server_permission_name", "QUERY_SYSTEM_TABLES"); connection.insertRow("user_server_permissions", values); } else { CodaResultSet rs1 = connection.runQuery("select a.id from applications a where a.active_flag = 1 and a.application_name = " + connection.formatStringForSQL("applications", "application_name", applicationName.toUpperCase()),null); if (!rs1.getErrorStatus() && rs1.next()) { long applicationId = rs1.getDataLong(0); Hashtable<String,Object> values = new Hashtable<String,Object>(); values.put("user_id", userId); values.put("application_id", applicationId); values.put("application_permission_name", "CONNECT"); connection.insertRow("user_application_permissions", values); values.put("application_permission_name", "MANAGE_USERS"); connection.insertRow("user_application_permissions", values); values.put("application_permission_name", "MANAGE_ROLES"); connection.insertRow("user_application_permissions", values); values.put("application_permission_name", "DEVELOPER"); connection.insertRow("user_application_permissions", values); values.put("application_permission_name", "MANAGE_CRONS"); connection.insertRow("user_application_permissions", values); } } } // These methods return server data public long getIdForObjectName(CodaConnection connection, String objectName, int objectType) { CodaResultSet rs = null; switch (objectType) { case CodaServer.OBJECT_TYPE_DATASOURCE: rs = connection.runQuery("select d.id from datasources d where d.datasource_name = " + connection.formatStringForSQL("datasources", "datasource_name", objectName.toUpperCase()), null); break; case CodaServer.OBJECT_TYPE_APPLICATION: rs = connection.runQuery("select a.id from applications a where a.active_flag = 1 and a.application_name = " + connection.formatStringForSQL("applications", "application_name", objectName.toUpperCase()), null); break; case CodaServer.OBJECT_TYPE_USER: rs = connection.runQuery("select u.id from users u where u.active_flag = 1 and u.user_name = " +connection.formatStringForSQL("users", "user_name", objectName.toUpperCase()), null); break; case CodaServer.OBJECT_TYPE_TYPE: rs = connection.runQuery("select t.id from types t where (t.active_flag = 1 or t.built_in_flag = 1) and t.type_name = " + connection.formatStringForSQL("types", "type_name", objectName.toUpperCase()), null); break; case CodaServer.OBJECT_TYPE_GROUP: rs = connection.runQuery("select g.id from groups g where g.active_flag = 1 and g.group_name = " +connection.formatStringForSQL("groups", "group_name", objectName.toUpperCase()),null); } if (rs != null && !rs.getErrorStatus() && rs.next()) { return rs.getDataLong(0); } return -1; } public long getIdForObjectName(String objectName, int objectType, CodaConnection connection) { // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } CodaResultSet rs = null; switch (objectType) { case CodaServer.OBJECT_TYPE_ROLE: rs = connection.runQuery("select id from "+prefix+"roles where role_name = " + connection.formatStringForSQL(prefix+"roles", "role_name", objectName.toUpperCase()),null); break; case CodaServer.OBJECT_TYPE_PERMISSION: rs = connection.runQuery("select id from "+prefix+"permissions where permission_name = " + connection.formatStringForSQL(prefix+"permissions", "permission_name", objectName.toUpperCase()),null); break; case CodaServer.OBJECT_TYPE_CRON: rs = connection.runQuery("select id from "+prefix+"crons where cron_name = " + connection.formatStringForSQL(prefix+"crons", "cron_name", objectName.toUpperCase()),null); break; case CodaServer.OBJECT_TYPE_TABLE: rs = connection.runQuery("select id from "+prefix+"tables where table_name = " + connection.formatStringForSQL(prefix+"tables", "table_name", objectName.toUpperCase()),null); break; case CodaServer.OBJECT_TYPE_INDEX: rs = connection.runQuery("select id from "+prefix+"indexes where index_name = " + connection.formatStringForSQL(prefix+"indexes", "index_name", objectName.toUpperCase()),null); break; case CodaServer.OBJECT_TYPE_PROCEDURE: rs = connection.runQuery("select id from "+prefix+"procedures where procedure_name = " + connection.formatStringForSQL(prefix+"procedures", "procedure_name", objectName.toUpperCase()),null); break; case CodaServer.OBJECT_TYPE_TABLE_COLUMN: String tableId = objectName.substring(0, objectName.indexOf(".")); String fieldName = objectName.substring(objectName.indexOf(".") + 1); rs = connection.runQuery("select id from "+prefix+"table_fields where table_id = "+connection.formatStringForSQL(prefix+"table_fields", "table_id", tableId) + " and field_name = " + connection.formatStringForSQL(prefix+"table_fields", "field_name", fieldName.toUpperCase()),null); break; case CodaServer.OBJECT_TYPE_FORM_STATUS_ADJ: tableId = objectName.substring(0, objectName.indexOf(".")); String statusNameAdj = objectName.substring(objectName.indexOf(".") + 1); rs = connection.runQuery("select id from "+prefix+"form_statuses where table_id = "+connection.formatStringForSQL(prefix+"form_statuses", "table_id", tableId) + " and adj_status_name = " + connection.formatStringForSQL(prefix+"form_statuses", "adj_status_name", statusNameAdj.toUpperCase()),null); break; case CodaServer.OBJECT_TYPE_FORM_STATUS_VERB: tableId = objectName.substring(0, objectName.indexOf(".")); String statusNameVerb = objectName.substring(objectName.indexOf(".") + 1); rs = connection.runQuery("select id from "+prefix+"form_statuses where table_id = "+connection.formatStringForSQL(prefix+"form_statuses", "table_id", tableId) + " and verb_status_name = " + connection.formatStringForSQL(prefix+"form_statuses", "verb_status_name", statusNameVerb.toUpperCase()),null); break; case CodaServer.OBJECT_TYPE_TABLE_TRIGGER: int firstPeriod = objectName.indexOf("."); int secondPeriod = objectName.indexOf(".", firstPeriod + 1); tableId = objectName.substring(0, firstPeriod); String operationId = objectName.substring(firstPeriod + 1, secondPeriod); String beforeFlag = objectName.substring(secondPeriod + 1); rs = connection.runQuery("select id from "+prefix+"triggers where table_id = "+connection.formatStringForSQL(prefix+"triggers", "table_id", tableId) + " and operation_id = " + connection.formatStringForSQL(prefix+"triggers", "operation_id", operationId) + " and before_flag = " + connection.formatStringForSQL(prefix+"triggers", "before_flag", beforeFlag),null); break; case CodaServer.OBJECT_TYPE_FORM_TRIGGER: firstPeriod = objectName.indexOf("."); secondPeriod = objectName.indexOf(".", firstPeriod + 1); int thirdPeriod = objectName.indexOf(".", secondPeriod + 1); tableId = objectName.substring(0, firstPeriod); operationId = objectName.substring(firstPeriod + 1, secondPeriod); String formStatusId = objectName.substring(secondPeriod + 1, thirdPeriod); beforeFlag = objectName.substring(thirdPeriod + 1); rs = connection.runQuery("select id from "+prefix+"triggers where table_id = "+connection.formatStringForSQL(prefix+"triggers", "table_id", tableId) + (!formStatusId.equalsIgnoreCase("-1") ? " and form_status_id = " + connection.formatStringForSQL(prefix+"triggers", "form_status_id", formStatusId) : " and operation_id = " + connection.formatStringForSQL(prefix+"triggers", "operation_id", operationId)) + " and before_flag = " + connection.formatStringForSQL(prefix+"triggers", "before_flag", beforeFlag),null); break; } if (rs != null && !rs.getErrorStatus() && rs.next()) { return rs.getDataLong(0); } return -1; } public String getSessionApplication(String sessionKey) { return sessions.getSessionApplication(sessionKey); } public long getSessionUserId(String sessionKey) { return sessions.getSessionUserId(sessionKey); } public long getSessionGroupId(String sessionKey) { return sessions.getSessionGroupId(sessionKey); } public int getSessionEnvironmentId(String sessionKey) { return sessions.getSessionEnvironmentId(sessionKey); } public String getSessionUsername(String sessionKey) { return sessions.getSessionUsername(sessionKey); } public String getSessionGroup(String sessionKey) { return sessions.getSessionGroup(sessionKey); } public void scheduleJob (String applicationName, int environment, String jobName, String cronString, JobDetail detail) throws ParseException, SchedulerException { CronTrigger trigger = new CronTrigger(applicationName.toUpperCase() + "_" + environment + "_" + jobName.toUpperCase() + "_TRIG", null, cronString); scheduler.scheduleJob(detail, trigger); } public void scheduleJob (String handle, String cronString, JobDetail detail) throws ParseException, SchedulerException { CronTrigger trigger = new CronTrigger(handle, null, cronString); scheduler.scheduleJob(detail, trigger); } public void stopJob (String applicationName, int environment, String jobName) throws SchedulerException { scheduler.deleteJob(applicationName.toUpperCase() + "_" + environment + "_" + jobName.toUpperCase(), ""); } public synchronized long logTransaction(CodaConnection connection, long applicationId, String codaStatement, boolean refTableFlag, long userId) { long retval = -1; CodaResultSet rs = connection.runQuery("select max(revision_id) from transactions where application_id = " + connection.formatStringForSQL("transactions", "application_id", Long.toString(applicationId)), null); if (!rs.getErrorStatus() && rs.next()) { long revisionId = 1; if (rs.getData(0) != null) { revisionId = rs.getDataLong(0) + 1; } Hashtable<String, Object> values = new Hashtable(); values.put("application_id", applicationId); values.put("coda_statement", codaStatement); values.put("revision_id", revisionId); values.put("ref_table_flag", refTableFlag ? "1" : "0"); values.put("create_user_id", userId); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_id", userId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); retval = connection.insertRow("transactions", values); } return retval; } public boolean isArrayFieldNameInUse(CodaConnection connection, String prefix, String fieldName) { boolean retval = false; CodaResultSet rs = connection.runQuery("select count(id) from "+prefix+"tables where table_name = " + connection.formatStringForSQL(prefix+"tables", "table_name", fieldName.toUpperCase()), null); if (!rs.getErrorStatus() && rs.next()) { retval = rs.getDataInt(0) > 0; } if (!retval) { rs = connection.runQuery("select count(id) from "+prefix+"table_fields where array_flag = 1 and field_name = " + connection.formatStringForSQL(prefix+"table_fields", "field_name", fieldName.toUpperCase()), null); if (!rs.getErrorStatus() && rs.next()) { retval = rs.getDataInt(0) > 0; } } return retval; } public boolean isRefTable(String applicationName, String tableName) { Datasource datasource = deployedApplications.getDatasource(applicationName, 1); if (datasource != null && tableName != null) { CodaConnection connection = datasource.getDatabase().getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } CodaResultSet rs = connection.runQuery("select ref_table_flag from "+prefix+"tables where table_name = " + connection.formatStringForSQL(prefix+"tables", "table_name", tableName.toUpperCase()), null); if (!rs.getErrorStatus() && rs.next()) { return rs.getDataInt(0) == 1; } } return false; } public boolean isSoftDeleteTable(CodaConnection connection, String prefix, String tableName) { CodaResultSet rs = connection.runQuery("select soft_delete_flag from "+prefix+"tables where table_name = " + connection.formatStringForSQL(prefix+"tables", "table_name", tableName.toUpperCase()), null); if (!rs.getErrorStatus() && rs.next()) { return rs.getDataInt(0) == 1; } return false; } public boolean isGroupTable(CodaConnection connection, String prefix, String tableName) { CodaResultSet rs = connection.runQuery("select group_flag from "+prefix+"tables where table_name = " + connection.formatStringForSQL(prefix+"tables", "table_name", tableName.toUpperCase()), null); if (!rs.getErrorStatus() && rs.next()) { return rs.getDataInt(0) == 1; } return false; } public boolean isForm(CodaConnection connection, String prefix, String tableName) { CodaResultSet rs = connection.runQuery("select form_flag from "+prefix+"tables where table_name = " + connection.formatStringForSQL(prefix+"tables", "table_name", tableName.toUpperCase()), null); if (!rs.getErrorStatus() && rs.next()) { return rs.getDataInt(0) == 1; } return false; } public boolean isSubTable(CodaConnection connection, String prefix, String tableName) { CodaResultSet rs = connection.runQuery("select parent_table_id from "+prefix+"tables where table_name = " + connection.formatStringForSQL(prefix+"tables", "table_name", tableName.toUpperCase()), null); if (!rs.getErrorStatus() && rs.next()) { return (rs.getData(0) != null && !rs.getData(0).equals("")); } return false; } public boolean isInitialFormStatus(CodaConnection connection, String prefix, long formStatusId) { CodaResultSet rs = connection.runQuery("select fs.initial_flag from "+prefix+"form_statuses fs where fs.id = " + connection.formatStringForSQL(prefix+"form_statuses", "id", Long.toString(formStatusId)), null); if (!rs.getErrorStatus() && rs.next()) { return (rs.getData(0) != null && !rs.getData(0).equals("")); } return false; } public boolean isArrayField(CodaConnection connection, String prefix, String applicationName, long fieldId) { CodaResultSet rs = connection.runQuery("select array_flag from "+prefix+"table_fields where id = " + connection.formatStringForSQL(prefix+"table_fields", "id", Long.toString(fieldId)), null); if (!rs.getErrorStatus() && rs.next()) { return rs.getDataInt(0) == 1; } return false; } public boolean isBuiltInField(CodaConnection connection, String prefix, long fieldId) { CodaResultSet rs = connection.runQuery("select built_in_flag from "+prefix+"table_fields where id = " + connection.formatStringForSQL(prefix+"table_fields", "id", Long.toString(fieldId)), null); if (!rs.getErrorStatus() && rs.next()) { return rs.getDataInt(0) == 1; } return false; } public static String camelCapitalize(String s, boolean initCaps) { // I know this should be a regex StringBuffer retval = new StringBuffer(); char[] chars = s.toCharArray(); if (initCaps) { retval.append(Character.toUpperCase(chars[0])); } else { retval.append(Character.toLowerCase(chars[0])); } for (int i = 1; i < s.length(); i++) { if (chars[i] == '_') { if (i+1 < chars.length && chars[i+1] != '_') { retval.append(Character.toUpperCase(chars[i+1])); i++; } else { retval.append('_'); } } else { retval.append(Character.toLowerCase(chars[i])); } } return retval.toString(); } public CodaDatabase getDatabase() { return this.database; } public Hashtable<String, Vector<String>> getColumnsForTables(CodaConnection connection, Vector<String> tableNames) { Hashtable<String, Vector<String>> retval = new Hashtable(); for (String tableName : tableNames) { ColumnDefinition[] columnDefinitions = connection.getMetadata().getColumnsForTable(tableName); for (int i = 0 ; i < columnDefinitions.length; i++) { if (retval.containsKey(columnDefinitions[i].getName().toUpperCase())) { retval.get(columnDefinitions[i].getName().toUpperCase()).add(tableName); } else { Vector<String> temp = new Vector(); temp.add(tableName); retval.put(columnDefinitions[i].getName().toUpperCase(), temp); } } } return retval; } public int getIdForEnvironmentName(String environmentName) { if (environmentName.equalsIgnoreCase("DEV")) { return 1; } else if (environmentName.equalsIgnoreCase("TEST")) { return 2; } else { return 3; } } public int getIdForDatabaseOperation(String operationName) { if (operationName.equalsIgnoreCase("SELECT")) { return 1; } else if (operationName.equalsIgnoreCase("insert")) { return 2; } else if (operationName.equalsIgnoreCase("update")) { return 3; } else { return 4; } } public DeployedApplication getDeployedApplication(String applicationName) { return this.deployedApplications.get(applicationName); } public CodaDatabase getCodaDatabase(String datasourceName) throws ClassNotFoundException, InstantiationException, IllegalAccessException { CodaConnection connection = database.getConnection(); CodaResultSet rs = connection.runQuery("select id, driver_name, host_name, schema_name, user_name, pass_word from datasources where datasource_name = " + connection.formatStringForSQL("datasources", "datasource_name", datasourceName), null); if (!rs.getErrorStatus() && rs.next()) { long datasourceId = rs.getDataLong(0); Hashtable options = new Hashtable(); CodaResultSet rs2 = connection.runQuery("select option_name, option_value from datasource_options where datasource_id = " + connection.formatStringForSQL("datasource_options", "datasource_id", Long.toString(datasourceId)) ,null); if (!rs2.getErrorStatus()) { while (rs2.next()) { options.put(rs2.getData(0), rs2.getData(1)); } } CodaDatabase conn; Class.forName(rs.getData(1)); conn = (CodaDatabase) Class.forName(rs.getData(1)).newInstance(); conn.setLogger(logger); if (conn.connect(rs.getData(2), rs.getData(4), rs.getData(5), rs.getData(3), options)) { return conn; } else { return null; } } else { return null; } } public void reloadType(long typeId) { CodaConnection connection = database.getConnection(); this.useTypeCache = false; types.remove(typeId); CodaResultSet rs = connection.runQuery("select id, built_in_flag, type_name, validation_mask, save_mask, class_file from types where active_flag = 1 and id = " + connection.formatStringForSQL("types", "id", Long.toString(typeId)), null); if (!rs.getErrorStatus() && rs.next()) { if (rs.getDataInt(1) == 1) { types.put(rs.getDataLong(0), new TypeParser(rs.getDataLong(0), rs.getData(2).toUpperCase())); } else { types.put(rs.getDataLong(0), new TypeParser(rs.getDataLong(0), rs.getData(2).toUpperCase(), rs.getData(3), rs.getData(4))); } try { Class groovyClass = classLoader.parseClass(rs.getData(5)); classLoader.linkClass(groovyClass); try { Class.forName("org.codalang.codaserver.language.types.user." + this.camelCapitalize(rs.getData(2), true), true, classLoader); } catch (ClassFormatError ex) { logger.log(Level.WARNING, "Class '" + "org.codalang.codaserver.language.types.user." + this.camelCapitalize(rs.getData(2), true) + "' was not found in the classloader."); } catch (Exception ex) { logger.log(Level.WARNING, "Class '" + "org.codalang.codaserver.language.types.user." + this.camelCapitalize(rs.getData(2), true) + "' was not found in the classloader."); } } catch (Exception e) { logger.log(Level.SEVERE, "Unable to deploy type " + rs.getData(2)); } } this.useTypeCache = true; } public TypeParser getTypeParser(long typeId) { return types.get(typeId); } public Hashtable<Long,TypeParser> getTypes() { return (Hashtable<Long,TypeParser>)types.clone(); } public CodaDatabase getApplicationDatabase (String applicationName, int environment) { if (applicationName != null) { return deployedApplications.getDatasource(applicationName, environment).getDatabase(); } return null; } public Datasource getApplicationDatasource (String applicationName, int environment) { if (applicationName != null) { return deployedApplications.getDatasource(applicationName, environment); } return null; } public String getApplicationDatasourceName (String applicationName, int environment) { if (applicationName != null) { return deployedApplications.getDatasourceName(applicationName, environment); } return null; } public GroovyClassLoader getClassLoader() { return this.classLoader; } // Commands start here public boolean shutdown() { webServer.stop(); if (this.getClustedFlag()) { CodaConnection connection = database.getConnection(); connection.runStatement("delete from cluster where ip_address = " +connection.formatStringForSQL("cluster", "ip_address", this.getIpAddress()) + " amd port = " + connection.formatStringForSQL("cluster", "port", Integer.toString(this.getPort()))); connection.commit(); } database.disconnect(); System.out.println("CodaServer Server is now closed. Have a nice day!"); System.exit(0); return true; } public void expireSessions () { CodaConnection connection = database.getConnection(); if (this.configuration.getSessionTimeout() > 0) { long timeInMillis = new GregorianCalendar().getTimeInMillis(); timeInMillis = timeInMillis - (1000 * 60 * this.configuration.getSessionTimeout()); CodaResultSet rs = connection.runQuery("select session_key from sessions where session_timestamp < " + connection.formatStringForSQL("sessions", "session_timestamp", Long.toString(timeInMillis)), null); while (rs.next()) { sessions.remove(rs.getData(0)); } connection.runStatement("delete from sessions where session_timestamp < " + connection.formatStringForSQL("sessions", "session_timestamp", Long.toString(timeInMillis))); } } public String login(String username, String password) { CodaConnection connection = database.getConnection(); String sql = "select id from users where active_flag = 1 and user_name = " + connection.formatStringForSQL("users", "user_name", username.toUpperCase()) + " and pass_word = " + connection.formatStringForSQL("users", "pass_word", encrypt(password)) + " "; CodaResultSet rs = connection.runQuery(sql, null); if (!rs.getErrorStatus() && rs.getRowsReturned() > 0) { if (rs.next()) { String sessionKey = sessions.createSession(rs.getDataLong(0)); this.sendSessionUpdateToCluster(sessionKey); return sessionKey; } else { return null; } } else { return null; } } public String login(long userId) { CodaConnection connection = database.getConnection(); String sql = "select id from users where active_flag = 1 and id = " +connection.formatStringForSQL("users", "id", Long.toString(userId)); CodaResultSet rs = connection.runQuery(sql, null); if (!rs.getErrorStatus() && rs.getRowsReturned() > 0) { if (rs.next()) { String sessionKey = sessions.createSession(rs.getDataLong(0)); this.sendSessionUpdateToCluster(sessionKey); return sessionKey; } } return null; } public void logout(String sessionKey) { sessions.remove(sessionKey); this.sendSessionUpdateToCluster(sessionKey); } public void log(Level level, String message) { this.logger.log(level, message); } public boolean touchSession(String sessionKey) { return sessions.touchSession(sessionKey); } public boolean setSessionApplication(String sessionKey, String applicationName, int environment, String groupName) { long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return false; } CodaConnection connection = database.getConnection(); if (deployedApplications.get(applicationName) != null && deployedApplications.get(applicationName).isGroupFlag()) { long applicationId = this.getIdForObjectName(connection, applicationName, CodaServer.OBJECT_TYPE_APPLICATION); long groupId = groupName == null ? -1 : this.getIdForObjectName(connection, groupName, CodaServer.OBJECT_TYPE_GROUP); if (userId > 0 && deployedApplications.canUserUseApplication(applicationName, userId, environment, groupId)) { sessions.setSessionApplication(sessionKey, applicationId, applicationName, environment); if (groupId > 0) { sessions.setSessionGroup(sessionKey, groupId, groupName); } this.sendSessionUpdateToCluster(sessionKey); return true; } } else { long applicationId = this.getIdForObjectName(connection, applicationName, CodaServer.OBJECT_TYPE_APPLICATION); if (userId > 0 && deployedApplications.canUserUseApplication(applicationName, userId, environment)) { sessions.setSessionApplication(sessionKey, applicationId, applicationName, environment); this.sendSessionUpdateToCluster(sessionKey); return true; } } return false; } public CodaResponse createDatasource(String sessionKey, String datasourceName, String displayName, Hashtable properties, Hashtable options, String username, String password) { if (sessions.hasServerPermission(sessionKey, "MANAGE_DATASOURCES")) { CodaConnection connection = database.getConnection(); long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } // make sure the properties hashtable is complete if (!properties.containsKey("HOSTNAME")) { return new CodaResponse(true, null, 2001, "Missing datasource parameter HOSTNAME"); } else if(!properties.containsKey("USERNAME")) { return new CodaResponse(true, null, 2002, "Missing datasource parameter USERNAME"); } else if (!properties.containsKey("PASSWORD")) { return new CodaResponse(true, null, 2003, "Missing datasource parameter PASSWORD"); } else if (!properties.containsKey("SCHEMA")) { return new CodaResponse(true, null, 2004, "Missing datasource parameter SCHEMA"); } else if (!properties.containsKey("DRIVER")) { return new CodaResponse(true, null, 2005, "Missing datasource parameter DRIVER"); } // make sure the datasource name isn't taken if (this.getIdForObjectName(connection, datasourceName.toUpperCase(), OBJECT_TYPE_DATASOURCE) > 0) { return new CodaResponse(true, null, 2007, "Datasource name already in use"); } // test that the class is in the classpath try { Class.forName((String)properties.get("DRIVER")); } catch (ClassNotFoundException e) { return new CodaResponse(true, null, 2006, "Driver '" + (String)properties.get("DRIVER") + "' not found"); } // attempt to create the schema if asked to try { if (username != null && password != null) { CodaDatabase temp = (CodaDatabase)Class.forName((String)properties.get("DRIVER")).newInstance(); if (!temp.createSchema((String)properties.get("HOSTNAME"),(String)properties.get("USERNAME"),(String)properties.get("PASSWORD"),(String)properties.get("SCHEMA"),options,username,password)) { return new CodaResponse(true, null, 2008, "Could not create new schema on database host"); } } } catch (ClassNotFoundException e) { return new CodaResponse(true, null, 2006, "Driver '" + (String)properties.get("DRIVER") + "' not found"); } catch (InstantiationException e) { return new CodaResponse(true, null, 2006, "Driver '" + (String)properties.get("DRIVER") + "' not found"); } catch (IllegalAccessException e) { return new CodaResponse(true, null, 2006, "Driver '" + (String)properties.get("DRIVER") + "' not found"); } // insert the datasource Hashtable values = new Hashtable(); values.put("datasource_name", datasourceName.toUpperCase()); values.put("host_name", (String)properties.get("HOSTNAME")); values.put("driver_name", (String)properties.get("DRIVER")); values.put("user_name", (String)properties.get("USERNAME")); values.put("pass_word", (String)properties.get("PASSWORD")); values.put("schema_name", (String)properties.get("SCHEMA")); values.put("display_name", (displayName == null ? datasourceName : displayName)); values.put("create_user_id", userId); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_id", userId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); long datasourceId = connection.insertRow("datasources", values); Enumeration en = options.keys(); while (en.hasMoreElements()) { String key = (String)en.nextElement(); values = new Hashtable(); values.put("datasource_id", datasourceId); values.put("option_name", key.toUpperCase()); values.put("option_value", options.get(key)); connection.insertRow("datasource_options", values); } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9001, "Do not have permission to manage datasources"); } } public CodaResponse alterDatasource(String sessionKey, String datasourceName, int operation, String newDatasourceName, String displayName, Hashtable properties, Hashtable options) { if (sessions.hasServerPermission(sessionKey, "MANAGE_DATASOURCES")) { CodaConnection connection = database.getConnection(); long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } long datasourceId = this.getIdForObjectName(connection, datasourceName.toUpperCase(), OBJECT_TYPE_DATASOURCE); if (datasourceId < 0) { return new CodaResponse(true, null, 2009, "Datasource name is invalid"); } Hashtable values = new Hashtable(); switch (operation) { // set display case 1: values = new Hashtable(); values.put("display_name", displayName); values.put("mod_user_id", userId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow("datasources", "id", datasourceId, values); break; // rename case 2: if (this.getIdForObjectName(connection, newDatasourceName.toUpperCase(), OBJECT_TYPE_DATASOURCE) > 0) { return new CodaResponse(true, null, 2007, "Datasource name already in use"); } else { values = new Hashtable(); values.put("datasource_name", newDatasourceName.toUpperCase()); values.put("mod_user_id", userId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow("datasources", "id", datasourceId, values); } break; // set properties case 3: if (properties.containsKey("DRIVER")) { try { Class.forName((String)properties.get("DRIVER")); } catch (ClassNotFoundException e) { return new CodaResponse(true, null, 2006, "Driver '" + (String)properties.get("DRIVER") + "' not found"); } } values = new Hashtable(); if (properties.containsKey("HOSTNAME")) values.put("host_name", (String)properties.get("HOSTNAME")); if (properties.containsKey("DRIVER")) values.put("driver_name", (String)properties.get("DRIVER")); if (properties.containsKey("USERNAME")) values.put("user_name", (String)properties.get("USERNAME")); if (properties.containsKey("PASSWORD")) values.put("pass_word", (String)properties.get("PASSWORD")); if (properties.containsKey("SCHEMA")) values.put("schema_name", (String)properties.get("SCHEMA")); connection.updateRow("datasources", "id", datasourceId, values); break; // set options case 4: Enumeration en = options.keys(); while (en.hasMoreElements()) { String key = (String)en.nextElement(); connection.runStatement("delete from datasource_options where datasource_id = "+connection.formatStringForSQL("datasource_options", "datasource_id", Long.toString(datasourceId)) +" and option_name = " + connection.formatStringForSQL("datasource_options", "option_name", key.toUpperCase())); values = new Hashtable(); values.put("datasource_id", datasourceId); values.put("option_name", key.toUpperCase()); values.put("option_value", options.get(key)); connection.insertRow("datasource_options", values); } break; } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9001, "Do not have permission to manage datasources"); } } public CodaResponse dropDatasource(String sessionKey, String datasourceName) { if (sessions.hasServerPermission(sessionKey, "MANAGE_DATASOURCES")) { CodaConnection connection = database.getConnection(); long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } long datasourceId = this.getIdForObjectName(connection, datasourceName.toUpperCase(), OBJECT_TYPE_DATASOURCE); if (datasourceId < 0) { return new CodaResponse(true, null, 2009, "Datasource name is invalid"); } CodaResultSet rs = connection.runQuery("select count(*) from applications where active_flag = 1 and dev_datasource_id = " + connection.formatStringForSQL("applications", "dev_datasource_id", Long.toString(datasourceId)),null); if (!rs.getErrorStatus() && rs.next()) { if(rs.getDataLong(0) > 0) { return new CodaResponse(true, null, 2010, "Datasource in use as a development database"); } else { connection.runStatement("update applications set test_datasource_id = null where test_datasource_id = " + connection.formatStringForSQL("applications", "test_datasource_id", Long.toString(datasourceId))); connection.runStatement("update applications set prod_datasource_id = null where prod_datasource_id = " + connection.formatStringForSQL("applications", "prod_datasource_id", Long.toString(datasourceId))); connection.deleteRow("datasources", "id", datasourceId); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } } else { return new CodaResponse(true, null, 8001, "Unspecified magical database error. Is the CodaServer database up?"); } } else { return new CodaResponse(true, null, 9001, "Do not have permission to manage datasources"); } } public CodaResponse createApplication(String sessionKey, String applicationName, String displayName, boolean groupFlag, String datasourceName, String prefix) { if (sessions.hasServerPermission(sessionKey, "MANAGE_APPLICATIONS")) { CodaConnection connection = database.getConnection(); long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } if (this.getIdForObjectName(connection, applicationName.toUpperCase(), CodaServer.OBJECT_TYPE_APPLICATION) > 0) { return new CodaResponse(true, null, 2011, "Application name already in use"); } long datasourceId = this.getIdForObjectName(connection, datasourceName.toUpperCase(), OBJECT_TYPE_DATASOURCE); if (datasourceId < 0) { return new CodaResponse(true, null, 2009, "Datasource name is invalid"); } try { CodaDatabase conn = this.getCodaDatabase(datasourceName.toUpperCase()); CodaSystemTable systemInfo = conn.getConnection().getMetadata().getSystemTable(); if (systemInfo == null && prefix == null) { return new CodaResponse(true, null, 8009); } } catch (IllegalAccessException e) { return new CodaResponse(true, null, 8002); } catch (ClassNotFoundException e) { return new CodaResponse(true, null, 8002); } catch (InstantiationException e) { return new CodaResponse(true, null, 8002); } Hashtable<String,Object> values = new Hashtable(); values.put("application_name", applicationName.toUpperCase()); values.put("display_name", (displayName == null ? applicationName : displayName)); values.put("group_flag", (groupFlag ? "1" : "0")); values.put("active_flag", "1"); values.put("dev_datasource_id", datasourceId); values.put("create_user_id", userId); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_id", userId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); long applicationId = connection.insertRow("applications", values); // format the datasource CodaResponse formatResponse = this.formatDatasourceForApplication(sessionKey, datasourceName, applicationName, -1, prefix == null ? "" : prefix,true); if (formatResponse.getError()) { this.dropApplication(sessionKey, applicationName); return formatResponse; } // set up the deployed application deployedApplications.deployApplication(applicationName, true, classLoader); addRootPermissions(connection, applicationName); deployedApplications.get(applicationName.toUpperCase()).reloadUser(userId); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9002, "Do not have permission to manage applications"); } } public CodaResponse alterApplication(String sessionKey, String applicationName, int operation, String newApplicationName, String displayName, String environmentString, String datasourceName) { if (sessions.hasServerPermission(sessionKey, "MANAGE_APPLICATIONS")) { CodaConnection connection = database.getConnection(); long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } long applicationId = this.getIdForObjectName(connection, applicationName.toUpperCase(), CodaServer.OBJECT_TYPE_APPLICATION); if (applicationId < 0) { return new CodaResponse(true, null, 2012, "Application name is invalid"); } Hashtable values = new Hashtable(); switch (operation) { // display name case 1: values = new Hashtable(); values.put("display_name", displayName); values.put("mod_user_id", userId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow("applications", "id", applicationId, values); break; case 2: if (this.getIdForObjectName(connection, newApplicationName.toUpperCase(), CodaServer.OBJECT_TYPE_APPLICATION) > 0) { return new CodaResponse(true, null, 2011, "Application name already in use"); } values = new Hashtable(); values.put("application_name", newApplicationName.toUpperCase()); values.put("mod_user_id", userId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow("applications", "id", applicationId, values); break; case 3: String environmentColumn = ""; if (environmentString.equalsIgnoreCase("DEV")) { environmentColumn = "dev_datasource_id"; } else if (environmentString.equalsIgnoreCase("TEST")) { environmentColumn = "test_datasource_id"; } else if (environmentString.equalsIgnoreCase("PROD")) { environmentColumn = "prod_datasource_id"; } else { return new CodaResponse(true, null, 2013, "Invalid environment specified"); } long datasourceId = this.getIdForObjectName(connection, datasourceName.toUpperCase(), OBJECT_TYPE_DATASOURCE); if (datasourceId < 0) { return new CodaResponse(true, null, 2009, "Datasource name is invalid"); } try { CodaDatabase tempDb = this.getCodaDatabase(datasourceName.toUpperCase()); if (tempDb == null) { return new CodaResponse(true, null, 8002, "Cannot connect to datasource '"+datasourceName+"'. Check the connection settings and database."); } } catch (ClassNotFoundException e) { return new CodaResponse(true, null, 8002, "Cannot connect to datasource '"+datasourceName+"'. Check the connection settings and database."); } catch (InstantiationException e) { return new CodaResponse(true, null, 8002, "Cannot connect to datasource '"+datasourceName+"'. Check the connection settings and database."); } catch (IllegalAccessException e) { return new CodaResponse(true, null, 8002, "Cannot connect to datasource '"+datasourceName+"'. Check the connection settings and database."); } values = new Hashtable(); values.put(environmentColumn, datasourceId); values.put("mod_user_id", userId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow("applications", "id", applicationId, values); } deployedApplications.deployApplication(applicationName, true, classLoader); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9002, "Do not have permission to manage applications"); } } public CodaResponse dropApplication(String sessionKey, String applicationName) { if (sessions.hasServerPermission(sessionKey, "MANAGE_APPLICATIONS")) { CodaConnection connection = database.getConnection(); long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } long applicationId = this.getIdForObjectName(connection, applicationName.toUpperCase(), OBJECT_TYPE_APPLICATION); if (applicationId < 0) { return new CodaResponse(true, null, 2012, "Application name is invalid"); } Hashtable values = new Hashtable(); values.put("active_flag", "0"); values.put("mod_user_id", userId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow("applications", "id", applicationId, values); deployedApplications.removeApplication(applicationName); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9002, "Do not have permission to manage applications"); } } public CodaResponse createUser (String sessionKey, String username, String password, boolean robotFlag, Hashtable properties) { long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (sessions.hasServerPermission(sessionKey, "MANAGE_USERS")) { CodaConnection connection = database.getConnection(); if (this.getIdForObjectName(connection, username.toUpperCase(), CodaServer.OBJECT_TYPE_USER) > 0) { return new CodaResponse(true, null, 2014, "Username already in use"); } Hashtable values = new Hashtable(); values.put("user_name", username.toUpperCase()); values.put("pass_word", this.encrypt(password)); values.put("robot_flag", (robotFlag ? "1" : "0")); values.put("active_flag", "1"); values.put("create_user_id", modUserId); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_id", modUserId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); Enumeration en = properties.keys(); while (en.hasMoreElements()) { String key = (String)en.nextElement(); values.put(key.toLowerCase(), properties.get(key)); } connection.insertRow("users", values); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9003, "Do not have permission to manage users"); } } public CodaResponse alterUser (String sessionKey, String username, int operation, String password, Hashtable properties) { CodaConnection connection = database.getConnection(); if(username.equalsIgnoreCase("ROOT")) { if (operation == 2) { return new CodaResponse(true, null, 2018); } long userId = this.getIdForObjectName(connection, username.toUpperCase(), CodaServer.OBJECT_TYPE_USER); if (userId < 0) { return new CodaResponse(true, null, 2015, "Username is invalid"); } long modUserId = sessions.getSessionUserId(sessionKey); if(modUserId == userId) { Hashtable values = new Hashtable(); values.put("pass_word", this.encrypt(password)); values.put("mod_user_id", modUserId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow("users", "id", userId, values); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9004, "Do not have permission to manage ROOT account"); } } else { boolean userPerm = sessions.hasServerPermission(sessionKey, "MANAGE_USERS"); boolean dataPerm = sessions.hasServerPermission(sessionKey, "MANAGE_USER_DATA"); long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } long userId = this.getIdForObjectName(connection, username.toUpperCase(), CodaServer.OBJECT_TYPE_USER); if (userId < 0) { return new CodaResponse(true, null, 2015, "Username is invalid"); } if (userPerm || dataPerm || modUserId == userId) { Hashtable values = new Hashtable(); switch (operation) { case 1: if (userPerm) { values.put("pass_word", this.encrypt(password)); values.put("mod_user_id", modUserId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow("users", "id", userId, values); } else { return new CodaResponse(true, null, 9003, "Do not have permission to manage users"); } break; case 2: if (dataPerm) { Enumeration en = properties.keys(); while (en.hasMoreElements()) { String key = (String)en.nextElement(); values.put(key.toLowerCase(), properties.get(key)); } values.put("mod_user_id", modUserId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow("users", "id", userId, values); } else { return new CodaResponse(true, null, 9006); } break; } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9003, "Do not have permission to manage users"); } } } public CodaResponse dropUser(String sessionKey, String username) { if(username.equalsIgnoreCase("ROOT")) { return new CodaResponse(true, null, 9004, "Do not have permission to manage ROOT account"); } else { if (sessions.hasServerPermission(sessionKey, "MANAGE_USERS")) { CodaConnection connection = database.getConnection(); long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } long userId = this.getIdForObjectName(connection, username.toUpperCase(), CodaServer.OBJECT_TYPE_USER); if (userId < 0) { return new CodaResponse(true, null, 2015, "Username is invalid"); } Hashtable values = new Hashtable(); values.put("active_flag", "0"); values.put("mod_user_id", modUserId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow("users", "id", userId, values); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9003, "Do not have permission to manage users"); } } } public CodaResponse createGroup (String sessionKey, String groupName, String displayName) { if (sessions.hasServerPermission(sessionKey, "MANAGE_GROUPS")) { CodaConnection connection = database.getConnection(); long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } if (this.getIdForObjectName(connection, groupName.toUpperCase(), CodaServer.OBJECT_TYPE_GROUP) > 0) { return new CodaResponse(true, null, 2016, "Group name already in use"); } Hashtable values = new Hashtable(); values.put("group_name", groupName.toUpperCase()); values.put("display_name", displayName); values.put("active_flag", "1"); values.put("create_user_id", userId); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_id", userId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.insertRow("groups", values); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9005, "Do not have permission to manage groups"); } } public CodaResponse alterGroup (String sessionKey, String groupName, int operation, String newGroupName, String displayName, String username) { if (sessions.hasServerPermission(sessionKey, "MANAGE_GROUPS")) { CodaConnection connection = database.getConnection(); long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } long groupId = this.getIdForObjectName(connection, groupName.toUpperCase(), CodaServer.OBJECT_TYPE_GROUP); if (groupId < 0) { return new CodaResponse(true, null, 2017, "Group name is invalid"); } Hashtable values = new Hashtable(); switch (operation) { // displayname case 1: values.put("display_name", displayName); values.put("mod_user_id", userId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow("groups", "id", groupId, values); break; // case rename case 2: if (this.getIdForObjectName(connection, newGroupName, CodaServer.OBJECT_TYPE_GROUP) > 0) { return new CodaResponse(true, null, 2016, "Group name already in use"); } values.put("group_name", newGroupName.toUpperCase()); values.put("mod_user_id", userId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow("groups", "id", groupId, values); break; // add user case 3: long newUserId = this.getIdForObjectName(connection, username, CodaServer.OBJECT_TYPE_USER); if (newUserId > 0) { CodaResultSet rs = connection.runQuery("select count(ug.user_id) from user_groups ug where ug.group_id = " + connection.formatStringForSQL("user_groups", "group_id", Long.toString(groupId)) + " and ug.group_id = " + connection.formatStringForSQL("user_groups", "user_id", Long.toString(groupId)), null); if (!rs.getErrorStatus() && rs.next()) { if(rs.getDataInt(0) < 1) { connection.runStatement("insert into user_groups (user_id, group_id, create_user_id, create_date, mod_user_id, mod_date) values ("+connection.formatStringForSQL("user_groups", "user_id", Long.toString(newUserId))+", "+connection.formatStringForSQL("user_groups", "group_id", Long.toString(groupId))+","+connection.formatStringForSQL("user_groups", "create_user_id", Long.toString(userId))+", "+connection.formatStringForSQL("user_groups", "create_date", Long.toString(new GregorianCalendar().getTimeInMillis()))+", "+connection.formatStringForSQL("user_groups", "mod_user_id", Long.toString(userId))+", "+connection.formatStringForSQL("user_groups", "mod_date", Long.toString(new GregorianCalendar().getTimeInMillis()))+" )"); } } else { return new CodaResponse(true, null, 8001); } } else { return new CodaResponse(true, null, 2015); } break; // remove user case 4: newUserId = this.getIdForObjectName(connection, username, CodaServer.OBJECT_TYPE_USER); if (newUserId > 0) { connection.runStatement("delete from user_groups where user_id = "+connection.formatStringForSQL("user_groups", "user_id", Long.toString(newUserId))+" and group_id = "+connection.formatStringForSQL("user_groups", "group_id", Long.toString(groupId))); } else { return new CodaResponse(true, null, 2015); } break; } connection.commit(); return new CodaResponse(false, "Success!", -1); } else { return new CodaResponse(true, null, 9005); } } public CodaResponse dropGroup (String sessionKey, String groupName) { if (sessions.hasServerPermission(sessionKey, "MANAGE_GROUPS")) { CodaConnection connection = database.getConnection(); long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } long groupId = this.getIdForObjectName(connection, groupName.toUpperCase(), CodaServer.OBJECT_TYPE_GROUP); if (groupId < 0) { return new CodaResponse(true, null, 2017, "Group name is invalid"); } Hashtable values = new Hashtable(); values.put("active_flag", 0); values.put("mod_user_id", userId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow("groups", "id", groupId, values); connection.commit(); return new CodaResponse(false, "Success!", -1); } else { return new CodaResponse(true, null, 9005); } } public CodaResponse createType (String sessionKey, String typeName, String validationMask, String saveMask) { if (sessions.hasServerPermission(sessionKey, "MANAGE_TYPES")) { CodaConnection connection = database.getConnection(); long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } if (this.getIdForObjectName(connection, typeName.toUpperCase(), CodaServer.OBJECT_TYPE_TYPE) > 0) { return new CodaResponse(true, null, 2019); } try { Regex regex = new Regex(); regex.compile(validationMask); } catch (com.stevesoft.pat.RegSyntax e) { return new CodaResponse(true, null, 2022); } try { Regex regex = new Regex(); regex.compile(saveMask); } catch (com.stevesoft.pat.RegSyntax e) { return new CodaResponse(true, null, 2023); } try { String classFile = GroovyClassGenerator.getTypeClass(typeName, validationMask, saveMask); Hashtable values = new Hashtable(); values.put("type_name", typeName.toUpperCase()); values.put("built_in_flag", 0); values.put("validation_mask", validationMask); values.put("save_mask", saveMask); values.put("active_flag", "1"); values.put("class_file", classFile); values.put("create_user_id", userId); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_id", userId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); long typeId = connection.insertRow("types", values); this.reloadType(typeId); this.sendTypeUpdateToCluster(typeId); } catch (IOException ex) { return new CodaResponse(true, null, 2083); } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9007); } } public CodaResponse alterType (String sessionKey, String typeName, String validationMask, String saveMask) { if (sessions.hasServerPermission(sessionKey, "MANAGE_TYPES")) { CodaConnection connection = database.getConnection(); long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } long typeId = this.getIdForObjectName(connection, typeName.toUpperCase(), CodaServer.OBJECT_TYPE_TYPE); if (typeId < 0) { return new CodaResponse(true, null, 2020); } try { Regex regex = new Regex(); regex.compile(validationMask); } catch (com.stevesoft.pat.RegSyntax e) { return new CodaResponse(true, null, 2022); } try { Regex regex = new Regex(); regex.compile(saveMask); } catch (com.stevesoft.pat.RegSyntax e) { return new CodaResponse(true, null, 2023); } try { String classFile = GroovyClassGenerator.getTypeClass(typeName, validationMask, saveMask); Hashtable values = new Hashtable(); values.put("validation_mask", validationMask); values.put("save_mask", saveMask); values.put("class_file", classFile); values.put("mod_user_id", userId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow("types", "id", typeId, values); this.reloadType(typeId); this.sendTypeUpdateToCluster(typeId); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } catch (IOException e) { return new CodaResponse(true, null, 2084); } } else { return new CodaResponse(true, null, 9007); } } public CodaResponse dropType (String sessionKey, String typeName) { if (sessions.hasServerPermission(sessionKey, "MANAGE_TYPES")) { CodaConnection connection = database.getConnection(); long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } long typeId = this.getIdForObjectName(connection, typeName.toUpperCase(), CodaServer.OBJECT_TYPE_TYPE); if (typeId < 0) { return new CodaResponse(true, null, 2020); } Hashtable values = new Hashtable(); values.put("active_flag", "0"); values.put("mod_user_id", userId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow("types", "id", typeId, values); this.reloadType(typeId); this.sendTypeUpdateToCluster(typeId); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9007); } } public CodaResponse grantServerPermissions(String sessionKey, Vector permissions, String username) { if (username.toUpperCase().equals("ROOT")) { return new CodaResponse(true, null, 9018); } if (sessions.hasServerPermission(sessionKey, "MANAGE_USERS")) { CodaConnection connection = database.getConnection(); long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } long userId = this.getIdForObjectName(connection, username.toUpperCase(), CodaServer.OBJECT_TYPE_USER); if (userId < 0) { return new CodaResponse(true, null, 2015); } Enumeration en = permissions.elements(); while (en.hasMoreElements()) { String permission = (String)en.nextElement(); CodaResultSet rs = connection.runQuery("select count(*) from user_server_permissions where user_id = " + connection.formatStringForSQL("user_server_permissions", "user_id", Long.toString(userId)) + " and server_permission_name = " + connection.formatStringForSQL("user_server_permissions", "server_permission_name", permission.toUpperCase()), null); if (!rs.getErrorStatus() && rs.next()) { if (rs.getDataInt(0) == 0){ Hashtable values = new Hashtable(); values.put("user_id", userId); values.put("server_permission_name", permission.toUpperCase()); connection.insertRow("user_server_permissions", values); } } else { return new CodaResponse(true, null, 8001); } } //sessions.loadSession(sessionKey); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9003, "Do not have permission to manage users"); } } public CodaResponse revokeServerPermissions(String sessionKey, Vector permissions, String username) { if (username.toUpperCase().equals("ROOT")) { return new CodaResponse(true, null, 9018); } if (sessions.hasServerPermission(sessionKey, "MANAGE_USERS")) { CodaConnection connection = database.getConnection(); long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } long userId = this.getIdForObjectName(connection, username.toUpperCase(), CodaServer.OBJECT_TYPE_USER); if (userId < 0) { return new CodaResponse(true, null, 2015); } Enumeration en = permissions.elements(); while (en.hasMoreElements()) { String permission = (String)en.nextElement(); connection.runStatement("delete from user_server_permissions where user_id = " + connection.formatStringForSQL("user_server_permissions", "user_id", Long.toString(userId)) + " and server_permission_name = " + connection.formatStringForSQL("user_server_permissions", "server_permission_name", permission.toUpperCase())); //sessions.loadSession(sessionKey); } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9003, "Do not have permission to manage users"); } } public CodaResponse grantApplicationPermissions(String sessionKey, Vector<String> permissions, String applicationName, String environmentString, String groupName, String username) { if (username.toUpperCase().equals("ROOT")) { return new CodaResponse(true, null, 9018); } CodaConnection connection = database.getConnection(); long userId = this.getIdForObjectName(connection, username.toUpperCase(), CodaServer.OBJECT_TYPE_USER); if (userId < 0) { return new CodaResponse(true, null, 2015); } int environment = -1; if (environmentString != null) { if (environmentString.equalsIgnoreCase("DEV")) { environment = 1; } else if (environmentString.equalsIgnoreCase("TEST")) { environment = 2; } else if (environmentString.equalsIgnoreCase("PROD")) { environment = 3; } else { return new CodaResponse(true, null, 2013, "Invalid environment specified"); } } long groupId = -1; if (groupName != null) { groupId = this.getIdForObjectName(connection, groupName, CodaServer.OBJECT_TYPE_GROUP); } long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, environment, (deployedApplications.isGroupApplication(applicationName) && deployedApplications.canGroupUseApplication(applicationName, groupName) ? groupId : -1), "MANAGE_USERS")) { long applicationId = this.getIdForObjectName(connection, applicationName, CodaServer.OBJECT_TYPE_APPLICATION); for (String permission : permissions) { if (!deployedApplications.hasApplicationPermission(applicationName, userId, environment, groupId, permission)) { Hashtable values = new Hashtable(); values.put("user_id", userId); values.put("application_id", applicationId); if (environment > 0 && !permission.equalsIgnoreCase("developer")) { values.put("environment", environment); } if (groupId > 0 && !permission.equalsIgnoreCase("developer") && !permission.equalsIgnoreCase("manage_crons")) { values.put("group_id", groupId); } values.put("application_permission_name", permission.toUpperCase()); connection.insertRow("user_application_permissions", values); } } deployedApplications.get(applicationName).reloadUser(userId); this.sendApplicationUpdateToCluster(applicationName, environmentString); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9003, "Do not have permission to manage users"); } } public CodaResponse revokeApplicationPermissions(String sessionKey, Vector permissions, String applicationName, String environmentString, String groupName, String username) { if (username.toUpperCase().equals("ROOT")) { return new CodaResponse(true, null, 9018); } CodaConnection connection = database.getConnection(); long userId = this.getIdForObjectName(connection, username.toUpperCase(), CodaServer.OBJECT_TYPE_USER); if (userId < 0) { return new CodaResponse(true, null, 2015); } int environment = -1; if (environmentString != null) { if (environmentString.equalsIgnoreCase("DEV")) { environment = 1; } else if (environmentString.equalsIgnoreCase("TEST")) { environment = 2; } else if (environmentString.equalsIgnoreCase("PROD")) { environment = 3; } else { return new CodaResponse(true, null, 2013, "Invalid environment specified"); } } long groupId = -1; if (groupName != null) { groupId = this.getIdForObjectName(connection, groupName, CodaServer.OBJECT_TYPE_GROUP); } long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, environment, groupId, "MANAGE_USERS")) { Enumeration en = permissions.elements(); long applicationId = this.getIdForObjectName(connection, applicationName, CodaServer.OBJECT_TYPE_APPLICATION); while (en.hasMoreElements()) { String permission = (String)en.nextElement(); connection.runStatement("delete from user_application_permissions where user_id = " + connection.formatStringForSQL("user_application_permissions", "user_id", Long.toString(userId)) + " and application_id = " + connection.formatStringForSQL("user_application_permissions", "application_id", Long.toString(applicationId)) + (environment > 0 && !permission.equalsIgnoreCase("developer") ? " and environment = " + connection.formatStringForSQL("user_application_permissions", "environment", Integer.toString(environment)) : "") + (groupId > 0 && !permission.equalsIgnoreCase("developer") && !permission.equalsIgnoreCase("manage_crons") ? " and group_id = " + connection.formatStringForSQL("user_application_permissions", "group_id", Long.toString(groupId)) : "") + " and application_permission_name = " + connection.formatStringForSQL("user_application_permissions", "application_permission_name", permission.toUpperCase())); } deployedApplications.get(applicationName).reloadUser(userId); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9003, "Do not have permission to manage users"); } } public CodaResponse grantApplicationToGroup(String sessionKey, String applicationName, String groupName) { if (sessions.hasServerPermission(sessionKey, "MANAGE_APPLICATIONS")) { CodaConnection connection = database.getConnection(); long groupId = -1; groupId = this.getIdForObjectName(connection, groupName, CodaServer.OBJECT_TYPE_GROUP); if (groupId < 0) { return new CodaResponse(true, null, 2017); } long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } long applicationId = this.getIdForObjectName(connection, applicationName, CodaServer.OBJECT_TYPE_APPLICATION); if (groupId < 0) { return new CodaResponse(true, null, 2012); } CodaResultSet rs = connection.runQuery("select count(*) from group_applications where group_id = " + connection.formatStringForSQL("group_applications", "group_id", Long.toString(groupId)) + " and application_id = " + connection.formatStringForSQL("group_applications", "application_id", Long.toString(applicationId)), null); if (!rs.getErrorStatus() && rs.next()) { if (rs.getDataLong(0) == 0) { Hashtable values = new Hashtable(); values.put("application_id", applicationId); values.put("group_id", groupId); values.put("create_user_id", modUserId); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_id", modUserId); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.insertRow("group_applications", values); } } connection.commit(); this.sendApplicationUpdateToCluster(applicationName, "PROD"); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9002, "Do not have permission to manage applications"); } } public CodaResponse revokeApplicationFromGroup(String sessionKey, String applicationName, String groupName) { if (sessions.hasServerPermission(sessionKey, "MANAGE_APPLICATIONS")) { CodaConnection connection = database.getConnection(); long groupId = -1; groupId = this.getIdForObjectName(connection, groupName, CodaServer.OBJECT_TYPE_GROUP); if (groupId < 0) { return new CodaResponse(true, null, 2017); } long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } long applicationId = this.getIdForObjectName(connection, applicationName, CodaServer.OBJECT_TYPE_APPLICATION); if (groupId < 0) { return new CodaResponse(true, null, 2012); } CodaResultSet rs = connection.runQuery("select count(*) from group_applications where group_id = " + connection.formatStringForSQL("group_applications", "group_id", Long.toString(groupId)) + " and application_id = " + connection.formatStringForSQL("group_applications", "application_id", Long.toString(applicationId)), null); if (!rs.getErrorStatus() && rs.next()) { if (rs.getDataLong(0) > 0) { connection.runStatement("delete from group_applications where group_id = " + connection.formatStringForSQL("group_applications", "group_id", Long.toString(groupId)) + " and application_id = " + connection.formatStringForSQL("group_applications", "application_id", Long.toString(applicationId)) ); CodaResultSet rs2 = connection.runQuery("select distinct user_id from user_application_permissions where group_id = " + connection.formatStringForSQL("group_applications", "group_id", Long.toString(groupId)) + " and application_id = " + connection.formatStringForSQL("group_applications", "application_id", Long.toString(applicationId)) ,null); if (!rs2.getErrorStatus() && rs2.getRowsReturned() > 0) { connection.runStatement("delete from user_application_permissions where group_id = " + connection.formatStringForSQL("group_applications", "group_id", Long.toString(groupId)) + " and application_id = " + connection.formatStringForSQL("group_applications", "application_id", Long.toString(applicationId)) ); DeployedApplication depApp = deployedApplications.get(applicationName); while (rs2.next()) { if (depApp != null) { depApp.reloadUser(rs.getDataLong(0)); } } } } } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9002, "Do not have permission to manage applications"); } } public CodaResponse formatDatasourceForCoda(String sessionKey, String datasourceName, String rootPassword) { if (sessions.hasServerPermission(sessionKey, "MANAGE_DATASOURCES")) { try { CodaDatabase connection = this.getCodaDatabase(datasourceName.toUpperCase()); DatabaseFormatter.formatCodaDatabase(connection, rootPassword, false); } catch (ClassNotFoundException e) { return new CodaResponse(true, null, 8002); } catch (InstantiationException e) { return new CodaResponse(true, null, 8002); } catch (IllegalAccessException e) { return new CodaResponse(true, null, 8002); } return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9001); } } public boolean formatConfigDatabase(String adminUsername, String adminPassword, String rootPassword, boolean echo) { boolean retval = false; if (echo) { System.out.println("Formatting Config Database..."); } if (this.configuration.getDatabaseConfiguration()[0].configurationComplete()) { try { Class.forName(this.configuration.getDatabaseConfiguration()[0].getDriverClass()); } catch (ClassNotFoundException e) { System.out.println("The specified driver class, \"" + this.configuration.getDatabaseConfiguration()[0].getDriverClass() + "\", is not in the classpath."); System.exit(0); } try { database = (CodaDatabase) Class.forName(this.configuration.getDatabaseConfiguration()[0].getDriverClass()).newInstance(); Hashtable options = new Hashtable(); for (int i =0; i < this.configuration.getDatabaseConfiguration()[0].getOptions().length; i++) { options.put(this.configuration.getDatabaseConfiguration()[0].getOptions()[i].getSetting(), this.configuration.getDatabaseConfiguration()[0].getOptions()[i].getValue()); } retval = database.createSchema(configuration.getDatabaseConfiguration()[0].getHostname(), configuration.getDatabaseConfiguration()[0].getUsername(), configuration.getDatabaseConfiguration()[0].getPassword(), configuration.getDatabaseConfiguration()[0].getSchema(), options, adminUsername, adminPassword); if (echo) { System.out.println("...Schema created"); } database.connect(configuration.getDatabaseConfiguration()[0].getHostname(), configuration.getDatabaseConfiguration()[0].getUsername(), configuration.getDatabaseConfiguration()[0].getPassword(), configuration.getDatabaseConfiguration()[0].getSchema(), options); if (echo) { System.out.println("...Connected as new user"); } if (retval) { DatabaseFormatter.formatCodaDatabase(database, rootPassword, echo); } else { if (echo) { System.out.println("Could not connect to database with new user."); } retval = false; } } catch (ClassNotFoundException e) { if (echo) { System.out.println("The following error was reported: " + e.getMessage()); } retval = false; } catch (InstantiationException e) { if (echo) { System.out.println("The following error was reported: " + e.getMessage()); } retval = false; } catch (IllegalAccessException e) { if (echo) { System.out.println("The following error was reported: " + e.getMessage()); } retval = false; } } else { retval = false; } return retval; } private void setRevisionSystemInfo(CodaDatabase database, long revisionId, long refTableRevisionId) { CodaConnection connection = database.getConnection(); connection.runStatement("update coda_system_information set system_value = " + connection.formatStringForSQL("coda_system_information", "system_value", Long.toString(revisionId)) + " where system_property = " + connection.formatStringForSQL("coda_system_information", "system_property", "REVISION_ID")); connection.runStatement("update coda_system_information set system_value = " + connection.formatStringForSQL("coda_system_information", "system_value", Long.toString(refTableRevisionId)) + " where system_property = " + connection.formatStringForSQL("coda_system_information", "system_property", "REF_TABLE_REVISION_ID")); connection.commit(); } public CodaResponse formatDatasourceForApplication(String sessionKey, String datasourceName, String applicationName, long revisionId, String prefix, boolean overwriteFlag) { if (sessions.hasServerPermission(sessionKey, "MANAGE_DATASOURCES")) { CodaConnection connection = database.getConnection(); long applicationId = this.getIdForObjectName(connection, applicationName, CodaServer.OBJECT_TYPE_APPLICATION); if (applicationId < 0) { return new CodaResponse(true, null, 2012, "Application name is invalid"); } if (revisionId < 0) { CodaResultSet rs = connection.runQuery("select max(revision_id) from transactions where application_id = " +connection.formatStringForSQL("transactions", "application_id", Long.toString(applicationId)), null); if (!rs.getErrorStatus() && rs.next()) { if (rs.getData(0) != null) { revisionId = rs.getDataLong(0); } else { revisionId = -1; } } else { return new CodaResponse(true, null, 8001); } } try { CodaDatabase localConn = this.getCodaDatabase(datasourceName.toUpperCase()); try { CodaConnection conn = localConn.getConnection(); CodaSystemTable systemInfo = conn.getMetadata().getSystemTable(); if (systemInfo != null && !systemInfo.isCodaServerFlag() && systemInfo.getApplicationName().equalsIgnoreCase(applicationName) && revisionId > systemInfo.getRevisionId()) { long lastRevisionId = systemInfo.getRevisionId(), lastRefTableRevisionId = systemInfo.getRefTableRevisionId(); CodaResultSet rs = connection.runQuery("select coda_statement, revision_id, ref_table_flag from transactions where application_id = " +connection.formatStringForSQL("transactions", "application_id", Long.toString(applicationId)) + " and ref_table_flag = 0 and revision_id > " + connection.formatStringForSQL("transactions", "revision_id", Long.toString(systemInfo.getRevisionId())) + " and revision_id "+ (systemInfo.getRefTableRevisionId() > revisionId ? "< " + connection.formatStringForSQL("transactions", "revision_id", Long.toString(systemInfo.getRefTableRevisionId())) : " <= " + connection.formatStringForSQL("transactions", "revision_id", Long.toString(revisionId))), null); if (!rs.getErrorStatus()) { while (rs.next()) { CodaParser parser = new CodaParser(new CommonTokenStream(new CodaLexer(new CaseInsensitiveStringStream(rs.getData(0)))), this, sessionKey, localConn); CodaResponse resp = parser.stat().response; if (resp.getError()) { setRevisionSystemInfo(localConn, lastRevisionId, lastRefTableRevisionId); return new CodaResponse(true, null, 2081, "There was an error while formatting the application database. Last update: Revision " + lastRevisionId); } else { lastRevisionId = rs.getDataLong(1); if (rs.getDataInt(2) == 1) { lastRefTableRevisionId = rs.getDataLong(1); } } } } else { setRevisionSystemInfo(localConn, lastRevisionId, lastRefTableRevisionId); return new CodaResponse(true, null, 2081, "There was an error while formatting the application database. Last update: Revision " + lastRevisionId); } if (lastRevisionId != revisionId && revisionId != systemInfo.getRefTableRevisionId()) { rs = connection.runQuery("select coda_statement, revision_id, ref_table_flag from transactions where application_id = " +connection.formatStringForSQL("transactions", "application_id", Long.toString(applicationId)) + " and revision_id > " + connection.formatStringForSQL("transactions", "revision_id", Long.toString(systemInfo.getRefTableRevisionId())) + " and revision_id <= " + connection.formatStringForSQL("transactions", "revision_id", Long.toString(revisionId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { CodaParser parser = new CodaParser(new CommonTokenStream(new CodaLexer(new CaseInsensitiveStringStream(rs.getData(0)))), this, sessionKey, localConn); CodaResponse resp = parser.stat().response; if (resp.getError()) { setRevisionSystemInfo(localConn, lastRevisionId, lastRefTableRevisionId); return new CodaResponse(true, null, 2081, "There was an error while formatting the application database. Last update: Revision " + lastRevisionId); } else { lastRevisionId = rs.getDataLong(1); if (rs.getDataInt(2) == 1) { lastRefTableRevisionId = rs.getDataLong(1); } } } } else { setRevisionSystemInfo(localConn, lastRevisionId, lastRefTableRevisionId); return new CodaResponse(true, null, 2081, "There was an error while formatting the application database. Last update: Revision " + lastRevisionId); } } if (revisionId == systemInfo.getRefTableRevisionId()) { lastRevisionId = systemInfo.getRefTableRevisionId(); } setRevisionSystemInfo(localConn, lastRevisionId, lastRefTableRevisionId); return new CodaResponse(false, "Success!", -1, null); } else if (overwriteFlag) { DatabaseFormatter.formatApplicationDatabase(localConn, applicationName, prefix); //return formatDatasourceForApplication(sessionKey, datasourceName, applicationName, revisionId, prefix, false); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 2082); } } catch (RecognitionException e) { return new CodaResponse(true, null, 8002); } catch (NullPointerException e) { return new CodaResponse(true, null, 8002); } } catch (ClassNotFoundException e) { return new CodaResponse(true, null, 8002); } catch (IllegalAccessException e) { return new CodaResponse(true, null, 8002); } catch (InstantiationException e) { return new CodaResponse(true, null, 8002); } catch (NullPointerException e) { return new CodaResponse(true, null, 8002); } } else { return new CodaResponse(true, null, 9001); } } public CodaResponse grantRoleToUser(String sessionKey, String roleName, String applicationName, String environmentString, String groupName, String username) { if (username.toUpperCase().equals("ROOT")) { return new CodaResponse(true, null, 9004); } CodaConnection connection = database.getConnection(); long userId = this.getIdForObjectName(connection, username.toUpperCase(), CodaServer.OBJECT_TYPE_USER); if (userId < 0) { return new CodaResponse(true, null, 2015); } int environment = 1; if (environmentString.equalsIgnoreCase("DEV")) { environment = 1; } else if (environmentString.equalsIgnoreCase("TEST")) { environment = 2; } else if (environmentString.equalsIgnoreCase("PROD")) { environment = 3; } else { return new CodaResponse(true, null, 2013, "Invalid environment specified"); } long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } long groupId = -1; if (deployedApplications.get(applicationName).isGroupFlag() && groupName != null) { groupId = this.getIdForObjectName(connection, groupName, CodaServer.OBJECT_TYPE_GROUP); } else if (deployedApplications.get(applicationName).isGroupFlag() && groupName == null) { return new CodaResponse(true, null, 2026); } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, environment, groupId, "MANAGE_USERS")) { Datasource datasource = deployedApplications.get(applicationName).getEnvironmentDatasource(environment); if (datasource != null) { CodaConnection connection2 = datasource.getDatabase().getConnection(); long roleId = this.getIdForObjectName(roleName, CodaServer.OBJECT_TYPE_ROLE, connection2); if (roleId < 0) { return new CodaResponse(true, null, 2029); } if (!datasource.hasRole(userId, groupId, roleName)) { Hashtable values = new Hashtable(); if (groupId > 0) { values.put("group_id", groupId); } values.put("user_id", userId); values.put("role_id", roleId); values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection2.insertRow(datasource.getPrefix() + "user_roles", values); deployedApplications.get(applicationName).getEnvironmentDatasource(environment).reloadUser(userId, groupId); connection2.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 2024); } } else { return new CodaResponse(true, null, 8003); } } else { return new CodaResponse(true, null, 9008); } } public CodaResponse revokeRoleFromUser(String sessionKey, String roleName, String applicationName, String environmentString, String groupName, String username) { if (username.toUpperCase().equals("ROOT")) { return new CodaResponse(true, null, 9004); } CodaConnection connection = database.getConnection(); long userId = this.getIdForObjectName(connection, username.toUpperCase(), CodaServer.OBJECT_TYPE_USER); if (userId < 0) { return new CodaResponse(true, null, 2015); } int environment = 1; if (environmentString.equalsIgnoreCase("DEV")) { environment = 1; } else if (environmentString.equalsIgnoreCase("TEST")) { environment = 2; } else if (environmentString.equalsIgnoreCase("PROD")) { environment = 3; } else { return new CodaResponse(true, null, 2013, "Invalid environment specified"); } long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } long groupId = -1; if (deployedApplications.get(applicationName).isGroupFlag() && groupName != null) { groupId = this.getIdForObjectName(connection, groupName, CodaServer.OBJECT_TYPE_GROUP); } else if (deployedApplications.get(applicationName).isGroupFlag() && groupName == null) { return new CodaResponse(true, null, 2026); } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, environment, groupId, "MANAGE_USERS")) { Datasource datasource = deployedApplications.get(applicationName).getEnvironmentDatasource(environment); if (datasource != null) { CodaConnection connection2 = datasource.getDatabase().getConnection(); long roleId = this.getIdForObjectName(roleName, CodaServer.OBJECT_TYPE_ROLE, connection2); if (roleId < 0) { return new CodaResponse(true, null, 2029); } if (datasource.hasRole(userId, groupId, roleName)) { connection2.runStatement("delete from " + datasource.getPrefix() + "user_roles where user_id = " + connection.formatStringForSQL(datasource.getPrefix() + "user_roles", "user_id", Long.toString(userId)) + " and role_id = " + connection.formatStringForSQL(datasource.getPrefix() + "user_roles", "role_id", Long.toString(roleId)) + " and group_id " + (groupId < 0 ? " is null " : " = " + connection.formatStringForSQL("user_roles", "group_id", Long.toString(groupId)) )); deployedApplications.get(applicationName).getEnvironmentDatasource(environment).reloadUser(userId, groupId); connection2.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 2025); } } else { return new CodaResponse(true, null, 8003); } } else { return new CodaResponse(true, null, 9008); } } public CodaResponse grantPermissionsToRole (String sessionKey, CodaDatabase database, Vector<String> permissions, String applicationName, String roleName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag){ CodaConnection connection = database.getConnection(); long roleId = this.getIdForObjectName(roleName, CodaServer.OBJECT_TYPE_ROLE, connection); if (roleId < 0) { return new CodaResponse(true, null, 2029); } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } // Test the input permissions Vector<Long> permissionIds = new Vector(); for (String permission : permissions) { long permissionId = this.getIdForObjectName(permission, CodaServer.OBJECT_TYPE_PERMISSION, connection); if (permissionId < 0) { return new CodaResponse(true, null, 2030, "Permission '" + permission.toUpperCase() + "' does not exist"); } else { permissionIds.add(permissionId); } } // get the current permissions CodaResultSet rs = connection.runQuery("select permission_id from "+ prefix +"role_permissions where role_id = " + connection.formatStringForSQL(prefix+"role_permissions", "role_id", Long.toString(roleId)),null); if (!rs.getErrorStatus()) { while (rs.next()) { if (permissionIds.contains(rs.getDataLong(0))) { permissionIds.remove(rs.getDataLong(0)); } } } // insert each new permission Hashtable values = new Hashtable(); values.put("role_id", roleId); for (Long permissionId : permissionIds) { values.put("permission_id", permissionId); connection.insertRow(prefix + "role_permissions", values); } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse revokePermissionsFromRole (String sessionKey, CodaDatabase database, Vector<String> permissions, String applicationName, String roleName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag){ CodaConnection connection = database.getConnection(); long roleId = this.getIdForObjectName(roleName, CodaServer.OBJECT_TYPE_ROLE, connection); if (roleId < 0) { return new CodaResponse(true, null, 2029); } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } // Test the input permissions Vector<Long> permissionIds = new Vector(); for (String permission : permissions) { long permissionId = this.getIdForObjectName(permission, CodaServer.OBJECT_TYPE_PERMISSION, connection); if (permissionId < 0) { return new CodaResponse(true, null, 2030, "Permission '" + permission.toUpperCase() + "' does not exist"); } else { permissionIds.add(permissionId); } } for (Long permissionId : permissionIds) { connection.runStatement("delete from "+prefix+"role_permissions where role_id = " + connection.formatStringForSQL(prefix+"role_permissions", "role_id", Long.toString(roleId)) + " and permission_id = "+ connection.formatStringForSQL(prefix+"role_permissions", "permission_id", permissionId.toString())); } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse grantTablePermissionsToRole (String sessionKey, CodaDatabase database, Vector<String> permissions, String applicationName, String tableName, String roleName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag){ CodaConnection connection = database.getConnection(); long tableId = this.getIdForObjectName(tableName, CodaServer.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2028); } long roleId = this.getIdForObjectName(roleName, CodaServer.OBJECT_TYPE_ROLE, connection); if (roleId < 0) { return new CodaResponse(true, null, 2029); } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } boolean selectPermission = false, insertPermission = false, updatePermission = false, deletePermission = false; for (String permission : permissions) { if (permission.equalsIgnoreCase("SELECT")) { selectPermission = true; } else if (permission.equalsIgnoreCase("INSERT")) { insertPermission = true; } else if (permission.equalsIgnoreCase("UPDATE")) { updatePermission = true; } else if (permission.equalsIgnoreCase("DELETE")) { deletePermission = true; } } // get the current permissions CodaResultSet rs = connection.runQuery("select select_flag, insert_flag, update_flag, delete_flag from "+ prefix +"role_tables where role_id = " + connection.formatStringForSQL(prefix+"role_tables", "role_id", Long.toString(roleId)) + " and table_id = "+ connection.formatStringForSQL(prefix+"role_tables", "table_id", Long.toString(tableId)),null); if (!rs.getErrorStatus() && rs.next()) { selectPermission = selectPermission || rs.getDataInt(0) == 1; insertPermission = insertPermission || rs.getDataInt(1) == 1; updatePermission = updatePermission || rs.getDataInt(2) == 1; deletePermission = deletePermission || rs.getDataInt(3) == 1; connection.runStatement("update "+prefix+"role_tables set select_flag = "+connection.formatStringForSQL(prefix+"role_tables", "select_flag", (selectPermission ? "1" : "0"))+", insert_flag = "+connection.formatStringForSQL(prefix+"role_tables", "insert_flag", (insertPermission ? "1" : "0"))+", update_flag = "+connection.formatStringForSQL(prefix+"role_tables", "update_flag", (updatePermission ? "1" : "0"))+", delete_flag = "+connection.formatStringForSQL(prefix+"role_tables", "delete_flag", (deletePermission ? "1" : "0"))+" where role_id = " + connection.formatStringForSQL(prefix+"role_tables", "role_id", Long.toString(roleId)) + " and table_id = "+ connection.formatStringForSQL("role_tables", "table_id", Long.toString(tableId))); } else { Hashtable values = new Hashtable(); values.put("role_id", roleId); values.put("table_id", tableId); values.put("select_flag", selectPermission ? "1" : "0"); values.put("insert_flag", insertPermission ? "1" : "0"); values.put("update_flag", updatePermission ? "1" : "0"); values.put("delete_flag", deletePermission ? "1" : "0"); connection.insertRow(prefix+"role_tables", values); } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse revokeTablePermissionsFromRole(String sessionKey, CodaDatabase database, Vector<String> permissions, String applicationName, String tableName, String roleName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag){ CodaConnection connection = database.getConnection(); long tableId = this.getIdForObjectName(tableName, CodaServer.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2028); } long roleId = this.getIdForObjectName(roleName, CodaServer.OBJECT_TYPE_ROLE, connection); if (roleId < 0) { return new CodaResponse(true, null, 2029); } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } boolean selectPermission = false, insertPermission = false, updatePermission = false, deletePermission = false; for (String permission : permissions) { if (permission.equalsIgnoreCase("SELECT")) { selectPermission = true; } else if (permission.equalsIgnoreCase("INSERT")) { insertPermission = true; } else if (permission.equalsIgnoreCase("UPDATE")) { updatePermission = true; } else if (permission.equalsIgnoreCase("DELETE")) { deletePermission = true; } } // get the current permissions CodaResultSet rs = connection.runQuery("select select_flag, insert_flag, update_flag, delete_flag from "+prefix+"role_tables where role_id = " + connection.formatStringForSQL(prefix+"role_tables", "role_id", Long.toString(roleId)) + " and table_id = "+ connection.formatStringForSQL(prefix+"role_tables", "table_id", Long.toString(tableId)),null); if (!rs.getErrorStatus() && rs.next()) { selectPermission = selectPermission ? false : rs.getDataInt(0) == 1; insertPermission = insertPermission ? false : rs.getDataInt(1) == 1; updatePermission = updatePermission ? false : rs.getDataInt(2) == 1; deletePermission = deletePermission ? false : rs.getDataInt(3) == 1; connection.runStatement("update "+prefix+"role_tables set select_flag = "+connection.formatStringForSQL(prefix+"role_tables", "select_flag", (selectPermission ? "1" : "0"))+", insert_flag = "+connection.formatStringForSQL(prefix+"role_tables", "insert_flag", (insertPermission ? "1" : "0"))+", update_flag = "+connection.formatStringForSQL(prefix+"role_tables", "update_flag", (updatePermission ? "1" : "0"))+", delete_flag = "+connection.formatStringForSQL(prefix+"role_tables", "delete_flag", (deletePermission ? "1" : "0"))+" where role_id = " + connection.formatStringForSQL(prefix+"role_tables", "role_id", Long.toString(roleId)) + " and table_id = "+ connection.formatStringForSQL(prefix+"role_tables", "table_id", Long.toString(tableId))); } else { Hashtable values = new Hashtable(); values.put("role_id", roleId); values.put("table_id", tableId); values.put("select_flag", "0"); values.put("insert_flag", "0"); values.put("update_flag", "0"); values.put("delete_flag", "0"); connection.insertRow(prefix+"role_tables", values); } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse grantFormStatusPermissionsToRole (String sessionKey, CodaDatabase database, Vector<String> permissions, String applicationName, String formName, String formStatusVerb, String roleName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag){ CodaConnection connection = database.getConnection(); long tableId = this.getIdForObjectName(formName, CodaServer.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2032); } long formStatusId = this.getIdForObjectName(Long.toString(tableId) + "." + formStatusVerb, CodaServer.OBJECT_TYPE_FORM_STATUS_ADJ, connection); if (formStatusId < 0) { return new CodaResponse(true, null, 2031); } long roleId = this.getIdForObjectName(roleName, CodaServer.OBJECT_TYPE_ROLE, connection); if (roleId < 0) { return new CodaResponse(true, null, 2029); } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } boolean viewFlag = false, callFlag = false, updateFlag = false; for (String permission : permissions) { if (permission.equalsIgnoreCase("VIEW")) { viewFlag = true; } else if (permission.equalsIgnoreCase("CALL")) { callFlag = true; } else if (permission.equalsIgnoreCase("UPDATE")) { updateFlag = true; } } // get the current permissions CodaResultSet rs = connection.runQuery("select view_flag, call_flag, update_flag from "+prefix+"role_form_statuses where role_id = " + connection.formatStringForSQL(prefix+"role_form_statuses", "role_id", Long.toString(roleId)) + " and form_status_id = "+ connection.formatStringForSQL(prefix+"role_form_statuses", "form_status_id", Long.toString(formStatusId)),null); if (!rs.getErrorStatus() && rs.next()) { viewFlag = viewFlag || rs.getDataInt(0) == 1; callFlag = callFlag || rs.getDataInt(1) == 1; updateFlag = updateFlag || rs.getDataInt(2) == 1; connection.runStatement("update "+prefix+"role_form_statuses set view_flag = "+connection.formatStringForSQL(prefix+"role_form_statuses", "view_flag", (viewFlag ? "1" : "0"))+", call_flag = "+connection.formatStringForSQL(prefix+"role_form_statuses", "call_flag", (callFlag ? "1" : "0"))+", update_flag = "+connection.formatStringForSQL(prefix+"role_form_statuses", "update_flag", (updateFlag ? "1" : "0"))+" where role_id = " + connection.formatStringForSQL(prefix+"role_form_statuses", "role_id", Long.toString(roleId)) + " and form_status_id = "+ connection.formatStringForSQL(prefix+"role_form_statuses", "form_status_id", Long.toString(formStatusId))); } else { Hashtable values = new Hashtable(); values.put("role_id", roleId); values.put("form_status_id", formStatusId); values.put("view_flag", viewFlag ? "1" : "0"); values.put("call_flag", callFlag ? "1" : "0"); values.put("update_flag", updateFlag ? "1" : "0"); connection.insertRow(prefix+"role_form_statuses", values); } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse revokeFormStatusPermissionsFromRole (String sessionKey, CodaDatabase database, Vector<String> permissions, String applicationName, String formName, String formStatusVerb, String roleName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag){ CodaConnection connection = database.getConnection(); long tableId = this.getIdForObjectName(formName, CodaServer.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2032); } long formStatusId = this.getIdForObjectName(Long.toString(tableId) + "." + formStatusVerb, CodaServer.OBJECT_TYPE_FORM_STATUS_ADJ, connection); if (formStatusId < 0) { return new CodaResponse(true, null, 2031); } long roleId = this.getIdForObjectName(roleName, CodaServer.OBJECT_TYPE_ROLE, connection); if (roleId < 0) { return new CodaResponse(true, null, 2029); } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } boolean viewFlag = false, callFlag = false, updateFlag = false; for (String permission : permissions) { if (permission.equalsIgnoreCase("VIEW")) { viewFlag = true; } else if (permission.equalsIgnoreCase("CALL")) { callFlag = true; } else if (permission.equalsIgnoreCase("UPDATE")) { updateFlag = true; } } // get the current permissions CodaResultSet rs = connection.runQuery("select view_flag, call_flag, update_flag from "+prefix+"role_form_statuses where role_id = " + connection.formatStringForSQL(prefix+"role_form_statuses", "role_id", Long.toString(roleId)) + " and form_status_id = "+ connection.formatStringForSQL(prefix+"role_form_statuses", "form_status_id", Long.toString(formStatusId)),null); if (!rs.getErrorStatus() && rs.next()) { viewFlag = viewFlag ? false : rs.getDataInt(0) == 1; callFlag = callFlag ? false : rs.getDataInt(1) == 1; updateFlag = updateFlag ? false : rs.getDataInt(2) == 1; connection.runStatement("update "+prefix+"role_form_statuses set view_flag = "+connection.formatStringForSQL(prefix+"role_form_statuses", "view_flag", (viewFlag ? "1" : "0"))+", call_flag = "+connection.formatStringForSQL(prefix+"role_form_statuses", "call_flag", (callFlag ? "1" : "0"))+", update_flag = "+connection.formatStringForSQL(prefix+"role_form_statuses", "update_flag", (updateFlag ? "1" : "0"))+" where role_id = " + connection.formatStringForSQL(prefix+"role_form_statuses", "role_id", Long.toString(roleId)) + " and form_status_id = "+ connection.formatStringForSQL(prefix+"role_form_statuses", "form_status_id", Long.toString(formStatusId))); } else { Hashtable values = new Hashtable(); values.put("role_id", roleId); values.put("form_status_id", formStatusId); values.put("view_flag", "0"); values.put("call_flag", "0"); values.put("update_flag", "0"); connection.insertRow(prefix + "role_form_statuses", values); } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse grantProcedurePermissionsToRole (String sessionKey, CodaDatabase database, Vector<String> permissions, String applicationName, String procedureName, String roleName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag){ CodaConnection connection = database.getConnection(); long procedureId = this.getIdForObjectName(procedureName, CodaServer.OBJECT_TYPE_PROCEDURE, connection); if (procedureId < 0) { return new CodaResponse(true, null, 2033); } long roleId = this.getIdForObjectName(roleName, CodaServer.OBJECT_TYPE_ROLE, connection); if (roleId < 0) { return new CodaResponse(true, null, 2029); } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } boolean executeFlag = false; for (String permission : permissions) { if (permission.equalsIgnoreCase("EXECUTE")) { executeFlag = true; } } // get the current permissions CodaResultSet rs = connection.runQuery("select execute_flag from "+prefix+"role_procedures where role_id = " + connection.formatStringForSQL(prefix+"role_procedures", "role_id", Long.toString(roleId)) + " and procedure_id = "+ connection.formatStringForSQL(prefix+"role_procedures", "procedure_id", Long.toString(procedureId)),null); if (!rs.getErrorStatus() && rs.next()) { executeFlag = executeFlag || rs.getDataInt(0) == 1; connection.runStatement("update "+prefix+"role_procedures set execute_flag = "+connection.formatStringForSQL(prefix+"role_procedures", "execute_flag", (executeFlag ? "1" : "0"))+" where role_id = " + connection.formatStringForSQL(prefix+"role_procedures", "role_id", Long.toString(roleId)) + " and procedure_id = "+ connection.formatStringForSQL(prefix+"role_procedures", "procedure_id", Long.toString(procedureId))); } else { Hashtable values = new Hashtable(); values.put("role_id", roleId); values.put("procedure_id", procedureId); values.put("execute_flag", executeFlag ? "1" : "0"); connection.insertRow(prefix+"role_procedures", values); } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse revokeProcedurePermissionsFromRole (String sessionKey, CodaDatabase database, Vector<String> permissions, String applicationName, String procedureName, String roleName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag){ CodaConnection connection = database.getConnection(); long procedureId = this.getIdForObjectName(procedureName, CodaServer.OBJECT_TYPE_PROCEDURE, connection); if (procedureId < 0) { return new CodaResponse(true, null, 2033); } long roleId = this.getIdForObjectName(roleName, CodaServer.OBJECT_TYPE_ROLE, connection); if (roleId < 0) { return new CodaResponse(true, null, 2029); } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } boolean executeFlag = false; for (String permission : permissions) { if (permission.equalsIgnoreCase("EXECUTE")) { executeFlag = true; } } // get the current permissions CodaResultSet rs = connection.runQuery("select execute_flag from "+prefix+"role_procedures where role_id = " + connection.formatStringForSQL(prefix+"role_procedures", "role_id", Long.toString(roleId)) + " and procedure_id = "+ connection.formatStringForSQL(prefix+"role_procedures", "procedure_id", Long.toString(procedureId)),null); if (!rs.getErrorStatus() && rs.next()) { executeFlag = executeFlag ? false : rs.getDataInt(0) == 1; connection.runStatement("update "+prefix+"role_procedures set execute_flag = "+connection.formatStringForSQL(prefix+"role_procedures", "execute_flag", (executeFlag ? "1" : "0"))+" where role_id = " + connection.formatStringForSQL(prefix+"role_procedures", "role_id", Long.toString(roleId)) + " and procedure_id = "+ connection.formatStringForSQL(prefix+"role_procedures", "procedure_id", Long.toString(procedureId))); } else { Hashtable<String, Object> values = new Hashtable(); values.put("role_id", roleId); values.put("procedure_id", procedureId); values.put("execute_flag", "0"); connection.insertRow(prefix+"role_procedures", values); } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse createRole(String sessionKey, CodaDatabase database, String applicationName, String roleName, String displayName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag){ CodaConnection connection = database.getConnection(); // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (this.getIdForObjectName(roleName, CodaServer.OBJECT_TYPE_ROLE, connection) > 0) { return new CodaResponse(true, null, 2034); } if (displayName == null) { displayName = roleName; } Hashtable<String, Object> values = new Hashtable(); values.put("role_name", roleName.toUpperCase()); values.put("display_name", displayName); values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.insertRow(prefix+"roles", values); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse alterRole(String sessionKey, CodaDatabase database, String applicationName, String roleName, int operation, String newRoleName, String displayName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag){ CodaConnection connection = database.getConnection(); long roleId = this.getIdForObjectName(roleName, CodaServer.OBJECT_TYPE_ROLE, connection); if (roleId < 0) { return new CodaResponse(true, null, 2029); } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } Hashtable values; switch (operation) { case 1: values = new Hashtable(); values.put("display_name", displayName); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow(prefix+"roles", "id", roleId, values); break; case 2: if (this.getIdForObjectName(newRoleName, CodaServer.OBJECT_TYPE_ROLE, connection) > 0) { return new CodaResponse(true, null, 2034); } values = new Hashtable(); values.put("role_name", newRoleName.toUpperCase()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow(prefix+"roles", "id", roleId, values); break; } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse dropRole(String sessionKey, CodaDatabase database, String applicationName, String roleName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag){ CodaConnection connection = database.getConnection(); long roleId = this.getIdForObjectName(roleName, CodaServer.OBJECT_TYPE_ROLE, connection); if (roleId < 0) { return new CodaResponse(true, null, 2029); } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } // remove all user_roles connection.runStatement("delete from "+prefix+"user_roles where role_id = " + connection.formatStringForSQL(prefix+"user_roles", "role_id", Long.toString(roleId))); // remove all role permissions, role table permissions, role form status permissions, and role procedure permissions connection.runStatement("delete from "+prefix+"role_permissions where role_id = " + connection.formatStringForSQL(prefix+"role_permissions", "role_id", Long.toString(roleId))); connection.runStatement("delete from "+prefix+"role_tables where role_id = " + connection.formatStringForSQL(prefix+"role_tables", "role_id", Long.toString(roleId))); connection.runStatement("delete from "+prefix+"role_form_statuses where role_id = " + connection.formatStringForSQL(prefix+"role_form_statuses", "role_id", Long.toString(roleId))); connection.runStatement("delete from "+prefix+"role_procedures where role_id = " + connection.formatStringForSQL(prefix+"role_procedures", "role_id", Long.toString(roleId))); // remove the role itself connection.deleteRow(prefix+"roles", "id", roleId); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse createPermission(String sessionKey, CodaDatabase database, String applicationName, String permissionName, String displayName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag){ CodaConnection connection = database.getConnection(); if (this.getIdForObjectName(permissionName, CodaServer.OBJECT_TYPE_PERMISSION, connection) > 0) { return new CodaResponse(true, null, 2035); } if (displayName == null) { displayName = permissionName; } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } Hashtable values = new Hashtable(); values.put("permission_name", permissionName.toUpperCase()); values.put("display_name", displayName); values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.insertRow(prefix+"permissions", values); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse alterPermission(String sessionKey, CodaDatabase database, String applicationName, String permissionName, int operation, String newPermissionName, String displayName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag){ CodaConnection connection = database.getConnection(); long permissionId = this.getIdForObjectName(permissionName, CodaServer.OBJECT_TYPE_PERMISSION, connection); if (permissionId < 0) { return new CodaResponse(true, null, 2030); } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } Hashtable<String,Object> values; switch (operation) { case 1: values = new Hashtable(); values.put("display_name", displayName); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow(prefix + "permissions", "id", permissionId, values); break; case 2: if (this.getIdForObjectName(newPermissionName, CodaServer.OBJECT_TYPE_PERMISSION, connection) > 0) { return new CodaResponse(true, null, 2035); } values = new Hashtable(); values.put("permission_name", newPermissionName.toUpperCase()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow(prefix+"permissions", "id", permissionId, values); break; } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse dropPermission(String sessionKey, CodaDatabase database, String applicationName, String permissionName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag){ CodaConnection connection = database.getConnection(); // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } long permissionId = this.getIdForObjectName(permissionName, CodaServer.OBJECT_TYPE_PERMISSION, connection); if (permissionId < 0) { return new CodaResponse(true, null, 2030); } // remove all role permissions connection.runStatement("delete from "+prefix+"role_permissions where permission_id = " + connection.formatStringForSQL(prefix+"role_permissions", "permission_id", Long.toString(permissionId))); // remove the role itself connection.deleteRow(prefix+"permissions", "id", permissionId); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } private boolean isSubtableName(CodaDatabase database, String prefix, long tableId, String tableName) { CodaConnection connection = database.getConnection(); CodaResultSet rs = connection.runQuery("select count(*) from "+prefix+"tables where table_name = " + connection.formatStringForSQL(prefix+"tables", "table_name", tableName.toUpperCase()) + " and parent_table_id = " + connection.formatStringForSQL(prefix+"tables", "parent_table_id", Long.toString(tableId)),null); if (!rs.getErrorStatus() && rs.next()) { return rs.getDataInt(0) == 1; } else { return false; } } // index 0 is the previous hashtable, index 1 is the next private Vector<Hashtable> prepareHashtablesForTrigger(ExecutionContext context, CodaConnection connection, Hashtable<String, TableFieldDefinition> fields, Hashtable prev, Hashtable next) { Vector retval = new Vector(); Hashtable newPrev = new Hashtable(); if (prev != null) { for (Object key : prev.keySet()) { try { newPrev.put(((String)key).toLowerCase(), context.parse(this.getIdForObjectName(connection, fields.get((String)key).getTypeName(), CodaServer.OBJECT_TYPE_TYPE), prev.get((String)key).toString())); } catch (CodaException e) { // do nothing } } } retval.add(prev != null ? newPrev.clone() : null); newPrev = new Hashtable(); if (next != null) { for (Object key : next.keySet()) { try { newPrev.put(((String)key).toLowerCase(), context.parse(this.getIdForObjectName(connection, fields.get((String)key).getTypeName(), CodaServer.OBJECT_TYPE_TYPE), next.get((String)key).toString())); } catch (CodaException e) { // do nothing } } } retval.add(newPrev); return retval; } private Vector<String> getReservedObjectNames() { Vector<String> retval = new Vector(); retval.add("GRANT"); retval.add("REVOKE"); retval.add("EXECUTE"); retval.add("CONNECT"); retval.add("CREATE"); retval.add("SELECT"); retval.add("UPDATE"); retval.add("DELETE"); retval.add("NULL"); retval.add("PROCEDURE"); retval.add("CURRENT_TIMESTAMP"); retval.add("TABLE"); retval.add("FORM"); retval.add("TRIGGER"); retval.add("FROM"); retval.add("WHERE"); retval.add("HAVING"); retval.add("CURRENT_USER_ID"); retval.add("CURRENT_USERNAME"); retval.add("CURRENT_GROUP_NAME"); retval.add("USER"); retval.add("APPLICATION"); retval.add("GROUP"); retval.add("CRON"); retval.add("ALTER"); retval.add("DROP"); return retval; } private Vector<String> getReservedColumnNames() { Vector<String> retval = this.getReservedObjectNames(); retval.add("ID"); retval.add("CREATE_USER_ID"); retval.add("CREATE_USER_NAME"); retval.add("CREATE_DATE"); retval.add("MOD_USER_ID"); retval.add("MOD_USER_NAME"); retval.add("MOD_DATE"); retval.add("PARENT_TABLE_ID"); retval.add("GROUP_ID"); retval.add("ACTIVE_FLAG"); retval.add("STATUS_ID"); return retval; } private Hashtable<String,TableFieldDefinition> getFieldsForTable(CodaConnection connection, String prefix, long tableId) { Hashtable<String,TableFieldDefinition> retval = new Hashtable(); CodaResultSet rs = connection.runQuery("select tf.id, tf.field_name, tf.display_name, tf.type_name, tf.array_flag, tf.nullable_flag, tf.ref_table_id, tf.default_variable_id, tf.default_value, tf.create_user_name, tf.create_date, tf.mod_user_name, tf.mod_date from "+prefix+"table_fields tf where tf.table_id = " + connection.formatStringForSQL(prefix+"table_fields", "table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while(rs.next()) { TableFieldDefinition temp = new TableFieldDefinition(rs.getDataLong(0), rs.getData(1), this.getIdForObjectName(connection, rs.getData(3), CodaServer.OBJECT_TYPE_TYPE), rs.getData(3), rs.getData(2), (rs.getDataInt(4) == 1), (rs.getData(6) != null && !rs.getData(6).equals("")), (rs.getData(6) != null && !rs.getData(6).equals("") ? rs.getDataLong(6) : -1), rs.getData(7) != null ? rs.getDataInt(7) : -1, rs.getData(8), rs.getData(9), rs.getDataDate(10), rs.getData(11), rs.getDataDate(12)); temp.setNullableFlag(rs.getDataInt(5) == 1); retval.put(rs.getData(1), temp); } } return retval; } private CodaResponse alterColumn(CodaConnection connection, boolean formFlag, String applicationName, long tableId, String tableName, String fieldName, TableFieldDefinition field, int operation, long modUserId, String sessionKey, boolean loadClass) { // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (operation == 1 || operation == 2) { long columnId = this.getIdForObjectName(Long.toString(tableId) + "." + field.getFieldName(), CodaServer.OBJECT_TYPE_TABLE_COLUMN, connection); if ((operation == 1 && columnId > -1) || (operation == 2 && !fieldName.equalsIgnoreCase(field.getFieldName()) && columnId > -1)) { return new CodaResponse(true, null, 2037); } if (this.isSubtableName(database, prefix, tableId, field.getFieldName())) { return new CodaResponse(true, null, (formFlag ? 2066 : 2065)); } long typeId = this.getIdForObjectName(this.database.getConnection(), field.getTypeName(), CodaServer.OBJECT_TYPE_TYPE); if (typeId < 0) { return new CodaResponse(true, null, 2020, "Type '" + field.getTypeName() + "' is invalid"); } if (field.isRefFlag()) { if (this.getIdForObjectName(field.getRefTableName(), CodaServer.OBJECT_TYPE_TABLE, connection) < 0) { return new CodaResponse(true, null, 2028, "Table '" + field.getRefTableName() + "' is invalid"); } } if (field.getDefaultValue() != null || field.getDefaultVariableId() != -1) { // Get an execution context to test the values of the default parameters ExecutionContext context = new ExecutionContext(this, database); if (!field.isArrayFlag()) { if (field.getDefaultVariableId() != -1) { if (field.getDefaultVariableId() == CodaConstant.SYSVAR_CURRENT_TIMESTAMP && !field.getTypeName().equalsIgnoreCase("TIMESTAMP")) { return new CodaResponse(true, null, 3001, "Default value '" + field.getDefaultValue() + "' does not match the correct type for column '" + field.getFieldName() + "'"); } else if (field.getDefaultVariableId() != CodaConstant.SYSVAR_CURRENT_TIMESTAMP && !field.getTypeName().equalsIgnoreCase("STRING") && !field.getTypeName().equalsIgnoreCase("LONGSTRING")) { return new CodaResponse(true, null, 3001, "Default value '" + field.getDefaultValue() + "' does not match the correct type for column '" + field.getFieldName() + "'"); } } else if (!context.validate(typeId, field.getDefaultValue())) { return new CodaResponse(true, null, 3001, "Default value '" + field.getDefaultValue() + "' does not match the correct type for column '" + field.getFieldName() + "'"); } } else if (field.isArrayFlag()) { if (field.getDefaultVariableId() != -1) { return new CodaResponse(true, null, 3001, "Default value '" + field.getDefaultValue() + "' does not match the correct type for array column '" + field.getFieldName() + "'"); } else if (!TypeParser.isArray(field.getDefaultValue())) { return new CodaResponse(true, null, 3001, "Default value for column '" + field.getFieldName() + "' should be an array"); } else { Vector<String> tokens = TypeParser.explodeArray(field.getDefaultValue()); for (String token : tokens) { if(!context.validate(typeId, token)) { return new CodaResponse(true, null, 3001, "Default value '" + field.getDefaultValue() + "' does not match the correct type for column '" + field.getFieldName() + "'"); } } } } } if (operation == 1) { if (field.isArrayFlag()) { if (this.isArrayFieldNameInUse(connection, prefix, field.getFieldName().toUpperCase())) { return new CodaResponse(true, null, 2038, "Column '" + field.getFieldName() + "' must have a globally unique name"); } } if (field.isArrayFlag()) { ColumnDefinition[] cols = new ColumnDefinition[2]; cols[0] = new ColumnDefinition("id", Types.BIGINT, false); cols[1] = new ColumnDefinition("value", CodaTypeConverter.getSQLTypeFromCodaType(field.getTypeName()), false); try { connection.createTable(field.getFieldName().toUpperCase(), new Vector(Arrays.asList(cols))); connection.addColumn(tableName.toUpperCase(), new ColumnDefinition(field.getFieldName().toUpperCase(), Types.CLOB, false)); } catch (SQLException e) { return new CodaResponse(true, null, 8004, "The following error was reported by the database:" + e.getMessage()); } } else { try { connection.addColumn(tableName.toUpperCase(), new ColumnDefinition(field.getFieldName(), CodaTypeConverter.getSQLTypeFromCodaType(field.getTypeName()), field.isNullableFlag())); } catch (SQLException e) { return new CodaResponse(true, null, 8004, "The following error was reported by the database:" + e.getMessage()); } } Hashtable values = new Hashtable(); values.put("table_id", tableId); values.put("field_name", field.getFieldName().toUpperCase()); values.put("display_name", field.getDisplayedAs() == null ? field.getFieldName() : field.getDisplayedAs()); values.put("type_name", field.getTypeName().toUpperCase()); values.put("array_flag", field.isArrayFlag() ? 1 : 0); values.put("nullable_flag", field.isNullableFlag() ? 1 : 0); values.put("built_in_flag", field.isBuiltInFlag() ? 1 : 0); if (field.isRefFlag()) { values.put("ref_table_id", this.getIdForObjectName(field.getRefTableName(), CodaServer.OBJECT_TYPE_TABLE, connection)); } if ( field.getDefaultVariableId() != -1) { values.put("default_variable_id", field.getDefaultVariableId()); } if (field.getDefaultValue() != null) { values.put("default_value", field.getDefaultValue()); } values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.insertRow(prefix+ "table_fields", values); } else { long fieldId = this.getIdForObjectName(Long.toString(tableId) + "." + fieldName.toUpperCase(), CodaServer.OBJECT_TYPE_TABLE_COLUMN, connection); if (fieldId < 0) { return new CodaResponse(true, null, 2040); } if (this.isBuiltInField(connection, prefix, fieldId)) { return new CodaResponse(true, null, 2096); } boolean arrayField = this.isArrayField(connection, prefix, applicationName, fieldId); try { if (field.isArrayFlag()) { if (arrayField) { if (!fieldName.equalsIgnoreCase(field.getFieldName())) { if (this.isArrayFieldNameInUse(connection, prefix, field.getFieldName().toUpperCase())) { return new CodaResponse(true, null, 2038, "Column '" + field.getFieldName() + "' must have a globally unique name"); } connection.alterColumn(tableName.toUpperCase(), fieldName.toUpperCase(), new ColumnDefinition(field.getFieldName().toUpperCase(), Types.CLOB, false)); connection.alterTable(fieldName.toUpperCase(), field.getFieldName().toUpperCase()); } connection.alterColumn(field.getFieldName().toUpperCase(), "VALUE", new ColumnDefinition("VALUE", CodaTypeConverter.getSQLTypeFromCodaType(field.getTypeName()), false)); } else { // alter the old column connection.alterColumn(tableName.toUpperCase(), fieldName.toUpperCase(), new ColumnDefinition(field.getFieldName(), Types.CLOB, false)); // create the new table ColumnDefinition[] cols = new ColumnDefinition[2]; cols[0] = new ColumnDefinition("ID", Types.BIGINT, false); cols[1] = new ColumnDefinition("VALUE", CodaTypeConverter.getSQLTypeFromCodaType(field.getTypeName()), false); connection.createTable(field.getFieldName(), new Vector(Arrays.asList(cols))); } } else { if (arrayField) { connection.dropTable(fieldName.toUpperCase()); connection.alterColumn(tableName.toUpperCase(), fieldName.toUpperCase(), new ColumnDefinition(field.getFieldName(), CodaTypeConverter.getSQLTypeFromCodaType(field.getTypeName()), field.isNullableFlag())); } else { connection.alterColumn(tableName.toUpperCase(), fieldName, new ColumnDefinition(field.getFieldName(), CodaTypeConverter.getSQLTypeFromCodaType(field.getTypeName()), field.isNullableFlag())); } } } catch (SQLException e) { return new CodaResponse(true, null, 8004, "The following error was reported by the database:" + e.getMessage()); } Hashtable values = new Hashtable(); values.put("field_name", field.getFieldName().toUpperCase()); values.put("display_name", field.getDisplayedAs() == null ? field.getFieldName() : field.getDisplayedAs()); values.put("type_name", field.getTypeName().toUpperCase()); values.put("nullable_flag", field.isNullableFlag() ? 1 : 0); values.put("built_in_flag", field.isBuiltInFlag() ? 1 : 0); values.put("array_flag", field.isArrayFlag() ? 1 : 0); if (field.isRefFlag()) { values.put("ref_table_id", this.getIdForObjectName(field.getRefTableName(), CodaServer.OBJECT_TYPE_TABLE, connection)); } if ( field.getDefaultVariableId() != -1) { values.put("default_variable_id", field.getDefaultVariableId()); } else { connection.runStatement("update "+prefix + "table_fields set default_variable_id = null where id = " + fieldId); } if (field.getDefaultValue() != null) { values.put("default_value", field.getDefaultValue()); } else { connection.runStatement("update "+prefix + "table_fields set default_value = null where id = " + fieldId); } values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow(prefix + "table_fields", "id", fieldId, values); } } else { long fieldId = this.getIdForObjectName(Long.toString(tableId) + "." + fieldName.toUpperCase(), CodaServer.OBJECT_TYPE_TABLE_COLUMN, connection); if (fieldId < 0) { return new CodaResponse(true, null, 2040); } if (this.isBuiltInField(connection, prefix, fieldId)) { return new CodaResponse(true, null, 2095); } boolean arrayField = this.isArrayField(connection, prefix, applicationName, fieldId); Vector<Hashtable> indexes = new Vector(); CodaResultSet rs = connection.runQuery("select i.id, i.index_name from "+prefix+"indexes i inner join "+prefix+"index_fields f on f.index_id = i.id where f.table_field_id = " + connection.formatStringForSQL(prefix+"index_fields", "table_field_id", Long.toString(fieldId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { Hashtable<String,String> temp = new Hashtable(); temp.put("id", rs.getData(0)); temp.put("index_name", rs.getData(1)); indexes.add(temp); } } try { for (Hashtable<String,String> h : indexes) { connection.dropIndex(h.get("index_name")); } if(arrayField) { connection.dropTable(fieldName.toUpperCase()); connection.dropColumn(tableName.toUpperCase(), fieldName.toUpperCase()); } else { connection.dropColumn(tableName.toUpperCase(), fieldName.toUpperCase()); } } catch (SQLException e) { return new CodaResponse(true, null, 8004, "The following error was reported by the database:" + e.getMessage()); } for (Hashtable<String,String> h : indexes) { connection.runStatement("delete from "+prefix+"index_fields where index_id = " + connection.formatStringForSQL(prefix+"index_fields", "index_id", h.get("id"))); connection.deleteRow(prefix+"indexes", "id", Long.parseLong(h.get("id"))); } connection.deleteRow(prefix+"table_fields", "id", fieldId); } try { String classFile = GroovyClassGenerator.getTableClass(tableName, new Vector(this.getFieldsForTable(connection, prefix, tableId).values())); Hashtable values = new Hashtable(); values.put("class_file", classFile); connection.updateRow(prefix+"tables", "id", tableId, values); if (loadClass) { this.deployedApplications.get(applicationName).loadClass(1, "org.codalang.codaserver.language.tables." + CodaServer.camelCapitalize(tableName, true),classFile); } } catch (IOException ex) { logger.log(Level.WARNING, "Cannot create class for table '" + tableName + "'"); } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } public synchronized CodaResponse createTable (String sessionKey, CodaDatabase database, String applicationName, String tableName, String displayName, boolean groupFlag, boolean refTableFlag, String parentTableName, boolean softDeleteFlag, Vector<TableFieldDefinition> fields, boolean loadClass) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag){ CodaConnection connection = database.getConnection(); if (this.getIdForObjectName(tableName, CodaServer.OBJECT_TYPE_TABLE, connection) > 0) { return new CodaResponse(true, null, 2036); } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } long parentTableId = -1; if (parentTableName != null) { parentTableId = this.getIdForObjectName(parentTableName, CodaServer.OBJECT_TYPE_TABLE, connection); if(parentTableId < 0) { return new CodaResponse(true, null, 2028, "Table '" + parentTableName + "' is invalid"); } if (this.getIdForObjectName(Long.toString(parentTableId) + "." + tableName.toUpperCase(), CodaServer.OBJECT_TYPE_TABLE_COLUMN, connection) > 0) { return new CodaResponse(true, null, 2063); } if(this.isForm(connection, prefix, parentTableName)) { return new CodaResponse(true, null, 2045); } } Vector<String> fieldNames = new Vector(); Vector<String> identityFieldNames = new Vector(); Vector<Long> identityFieldIds = new Vector(); // Get an execution context to test the default values ExecutionContext context = new ExecutionContext(this, database); // get reserved column names Vector<String> reservedColumns = this.getReservedColumnNames(); for (TableFieldDefinition field : fields) { if (reservedColumns.contains(field.getFieldName().toUpperCase())) { return new CodaResponse(true, null, 2075, "The column name '" + field.getFieldName() + "' is reserved"); } if (fieldNames.contains(field.getFieldName().toUpperCase())) { return new CodaResponse(true, null, 2037, "Column '" + field.getFieldName() + "' defined multiple times"); } else { fieldNames.add(field.getFieldName().toUpperCase()); } long typeId = this.getIdForObjectName(this.database.getConnection(), field.getTypeName().toUpperCase(), CodaServer.OBJECT_TYPE_TYPE); if (typeId < 0) { return new CodaResponse(true, null, 2020, "Type '" + field.getTypeName() + "' is invalid"); } if (field.isRefFlag()) { if (this.getIdForObjectName(field.getRefTableName().toUpperCase(), CodaServer.OBJECT_TYPE_TABLE, connection) < 0) { return new CodaResponse(true, null, 2028, "Table/form '" + field.getRefTableName() + "' is invalid"); } } if (field.isArrayFlag()) { if (this.isArrayFieldNameInUse(connection, prefix, field.getFieldName().toUpperCase())) { return new CodaResponse(true, null, 2038, "Column '" + field.getFieldName() + "' must have a globally unique name"); } } if (field.getDefaultValue() != null || field.getDefaultVariableId() != -1) { if (!field.isArrayFlag()) { if (field.getDefaultVariableId() != -1) { if (field.getDefaultVariableId() == CodaConstant.SYSVAR_CURRENT_TIMESTAMP && !field.getTypeName().equalsIgnoreCase("TIMESTAMP")) { return new CodaResponse(true, null, 3001, "Default value '" + field.getDefaultValue() + "' does not match the correct type for column '" + field.getFieldName() + "'"); } else if (field.getDefaultVariableId() != CodaConstant.SYSVAR_CURRENT_TIMESTAMP && !field.getTypeName().equalsIgnoreCase("STRING") && !field.getTypeName().equalsIgnoreCase("LONGSTRING")) { return new CodaResponse(true, null, 3001, "Default value '" + field.getDefaultValue() + "' does not match the correct type for column '" + field.getFieldName() + "'"); } } else if (!context.validate(typeId, field.getDefaultValue())) { return new CodaResponse(true, null, 3001, "Default value '" + field.getDefaultValue() + "' does not match the correct type for column '" + field.getFieldName() + "'"); } } else if (field.isArrayFlag()) { if (field.getDefaultVariableId() != -1) { return new CodaResponse(true, null, 3001, "Default value '" + field.getDefaultValue() + "' does not match the correct type for array column '" + field.getFieldName() + "'"); } else if (!TypeParser.isArray(field.getDefaultValue())) { return new CodaResponse(true, null, 3001, "Default value for column '" + field.getFieldName() + "' should be an array"); } else { Vector<String> tokens = TypeParser.explodeArray(field.getDefaultValue()); for (String token : tokens) { if(!context.validate(typeId, token)) { return new CodaResponse(true, null, 3001, "Default value '" + field.getDefaultValue() + "' does not match the correct type for column '" + field.getFieldName() + "'"); } } } } } if (field.isIdentityFlag()) { identityFieldNames.add(field.getFieldName()); } } if (displayName == null) { displayName = tableName; } // Insert table try { // add the built-in columns to the columnDefinitions and fields vectors if (softDeleteFlag) { fields.add(new TableFieldDefinition("ACTIVE_FLAG", "INTEGER", "Active Flag", false, false, null, null, true)); } if (groupFlag) { fields.add(new TableFieldDefinition("GROUP_NAME", "STRING", "Group Name", false, false, null, null, true)); } fields.add(new TableFieldDefinition("ID", "INTEGER", "ID", false, false, null, null, true)); fields.add(new TableFieldDefinition("CREATE_USER_NAME", "STRING", "Creating Username", false, false, null, null, true)); fields.add(new TableFieldDefinition("CREATE_DATE", "TIMESTAMP", "Created Date", false, false, null, null, true)); fields.add(new TableFieldDefinition("MOD_USER_NAME", "STRING", "Last Modifying Username", false, false, null, null, true)); fields.add(new TableFieldDefinition("MOD_DATE", "TIMESTAMP", "Modified Date", false, false, null, null, true)); if (parentTableId > 0) { fields.add(new TableFieldDefinition("PARENT_TABLE_ID", "INTEGER", "Parent Table ID", false, false, null, null, true)); } String classFile = GroovyClassGenerator.getTableClass(tableName, fields); Hashtable values = new Hashtable(); values.put("table_name", tableName.toUpperCase()); values.put("display_name", displayName); values.put("group_flag", groupFlag ? 1 : 0); values.put("form_flag", 0); values.put("class_file", classFile); values.put("ref_table_flag", refTableFlag ? 1 : 0); if (parentTableId >= 0) { values.put("parent_table_id", parentTableId); } values.put("soft_delete_flag", softDeleteFlag ? 1 : 0); values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); long tableId = connection.insertRow(prefix+"tables", values); //load the class if needed if (loadClass) { this.deployedApplications.get(applicationName).loadClass(1, "org.codalang.codaserver.language.tables." + CodaServer.camelCapitalize(tableName, true),classFile); } ArrayList<ColumnDefinition> columnDefinitions = new ArrayList(); ArrayList<CodaTable> arrayTables = new ArrayList(); for (TableFieldDefinition field : fields) { values = new Hashtable(); values.put("table_id", tableId); values.put("field_name", field.getFieldName().toUpperCase()); values.put("display_name", field.getDisplayedAs() == null ? field.getFieldName() : field.getDisplayedAs()); values.put("type_name", field.getTypeName().toUpperCase()); values.put("array_flag", field.isArrayFlag() ? 1 : 0); values.put("nullable_flag", field.isNullableFlag() ? 1 : 0); values.put("built_in_flag", field.isBuiltInFlag() ? 1 : 0); if (field.isRefFlag()) { values.put("ref_table_id", this.getIdForObjectName(field.getRefTableName(), CodaServer.OBJECT_TYPE_TABLE, connection)); } if (field.getDefaultVariableId() != -1) { values.put("default_variable_id", field.getDefaultVariableId()); } if (field.getDefaultValue() != null) { values.put("default_value", field.getDefaultValue()); } values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); long fieldId = connection.insertRow(prefix+"table_fields", values); if (identityFieldNames.contains(field.getFieldName())) { identityFieldIds.add(fieldId); } if (field.isArrayFlag()) { ColumnDefinition[] cols = new ColumnDefinition[2]; cols[0] = new ColumnDefinition("id", Types.BIGINT, false); cols[1] = new ColumnDefinition("value", CodaTypeConverter.getSQLTypeFromCodaType(field.getTypeName()), false); arrayTables.add(new CodaTable(field.getFieldName(), cols)); columnDefinitions.add(new ColumnDefinition(field.getFieldName().toUpperCase(), Types.CLOB, false)); } else { columnDefinitions.add(new ColumnDefinition(field.getFieldName().toUpperCase(), CodaTypeConverter.getSQLTypeFromCodaType(field.getTypeName()), field.isNullableFlag())); } } try { connection.createTable(tableName, new Vector(columnDefinitions)); connection.setPrimaryKey(tableName, "ID"); for (CodaTable table : arrayTables) { connection.createTable(table.getTableName(), new Vector(Arrays.asList(table.getColumnDefinitions()))); } } catch (SQLException e) { connection.deleteRow("tables", "id", tableId); return new CodaResponse(true, null, 8004, "The following error was reported by the database:" + e.getMessage()); } if (identityFieldNames.size() > 0) { try { connection.setIdentityColumns("ID_" + tableName.toUpperCase(), tableName, identityFieldNames); } catch (SQLException e) { return new CodaResponse(true, null, 8004, "The following error was reported by the database:" + e.getMessage()); } values = new Hashtable(); values.put("index_name", "ID_" + tableName.toUpperCase()); values.put("table_id", tableId); values.put("index_type_id", 2); values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); long indexId = connection.insertRow(prefix+"indexes", values); for (Long fieldId : identityFieldIds) { values = new Hashtable(); values.put("index_id", indexId); values.put("table_field_id", fieldId); connection.insertRow(prefix+"index_fields", values); } } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } catch (IOException e) { return new CodaResponse(true, null, 2085); } } else { return new CodaResponse(true, null, 9009); } } public synchronized CodaResponse alterTable (String sessionKey, CodaDatabase database, String applicationName, String tableName, int operation, String newTableName, String displayName, TableFieldDefinition field, String fieldName, Vector<String> identityFields, boolean loadClass) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } CodaConnection connection = database.getConnection(); // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } boolean formFlag = this.isForm(connection, prefix, tableName); if (formFlag) { return new CodaResponse(true, null, 2039); } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag) { long tableId = this.getIdForObjectName(tableName.toUpperCase(), CodaServer.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2028); } Hashtable values = new Hashtable(); switch (operation) { case 1: values = new Hashtable(); values.put("display_name", displayName); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow(prefix+"tables", "id", tableId, values); connection.commit(); return new CodaResponse(false, "Success!", -1, null); case 2: if (this.getIdForObjectName(newTableName, CodaServer.OBJECT_TYPE_TABLE, connection) > 0) { return new CodaResponse(true, null, 2036); } try { connection.alterTable(tableName.toUpperCase(), newTableName.toUpperCase()); } catch (SQLException e) { return new CodaResponse(true, null, 8004, "The following error was reported by the database:" + e.getMessage()); } values = new Hashtable(); values.put("table_name", newTableName.toUpperCase()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow(prefix+"tables", "id", tableId, values); connection.commit(); return new CodaResponse(false, "Success!", -1, null); case 3: //add column return this.alterColumn(connection, formFlag, applicationName, tableId, tableName, fieldName, field, 1 , modUserId, sessionKey, loadClass); case 4: //alter column return this.alterColumn(connection, formFlag, applicationName, tableId, tableName, fieldName, field, 2 , modUserId, sessionKey, loadClass); case 5: //drop column return this.alterColumn(connection, formFlag, applicationName, tableId, tableName, fieldName, null, 3, modUserId, sessionKey, loadClass); case 6: //set identity long indexId = this.getIdForObjectName("ID_" + tableName.toUpperCase(), CodaServer.OBJECT_TYPE_INDEX, connection); if (indexId > 0 ) { try { connection.dropIndex("ID_" + tableName.toUpperCase()); } catch (SQLException e) { return new CodaResponse(true, null, 8004, "The following error was reported by the database:" + e.getMessage()); } connection.runStatement("delete from "+prefix+"index_fields where index_id = " + connection.formatStringForSQL(prefix+"index_fields", "index_id", Long.toString(indexId))); connection.deleteRow(prefix+"indexes", "id", indexId); } Vector<Long> identityFieldIds = new Vector(); for (String idFieldName : identityFields) { long tempFieldId = this.getIdForObjectName(Long.toString(tableId) + "." + idFieldName, CodaServer.OBJECT_TYPE_TABLE_COLUMN, connection); if (tempFieldId < 0) { return new CodaResponse(true, null, 2040, "Column name '" + idFieldName + "' not valid"); } else { identityFieldIds.add(tempFieldId); } } try { connection.setIdentityColumns("ID_" + tableName.toUpperCase(), tableName, identityFields); } catch (SQLException e) { return new CodaResponse(true, null, 8004, "The following error was reported by the database:" + e.getMessage()); } values = new Hashtable(); values.put("index_name", "ID_" + tableName.toUpperCase()); values.put("table_id", tableId); values.put("index_type_id", 2); values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); indexId = connection.insertRow(prefix+"indexes", values); for (Long tempFieldId : identityFieldIds) { values = new Hashtable(); values.put("index_id", indexId); values.put("table_field_id", tempFieldId); connection.insertRow(prefix+"index_fields", values); } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public synchronized CodaResponse dropTable (String sessionKey, CodaDatabase database, String applicationName, String tableName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } CodaConnection connection = database.getConnection(); // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (this.isForm(connection, prefix, tableName)) { return new CodaResponse(true, null, 2039); } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag) { long tableId = this.getIdForObjectName(tableName.toUpperCase(), CodaServer.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2028); } try { // Remove all indexes on reference columns on other tables that point to subtables of this table. Phew. CodaResultSet rs = connection.runQuery("select i.id, i.index_name from "+prefix+"indexes i inner join "+prefix+"index_fields inf on inf.index_id = i.id inner join "+prefix+"table_fields tf on tf.id = inf.table_field_id inner join "+prefix+"tables t on tf.ref_table_id = t.id where t.parent_table_id = " + connection.formatStringForSQL(prefix+"tables", "parent_table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { connection.dropIndex(rs.getData(1)); connection.runStatement("delete from "+prefix+"index_fields where index_id = " + connection.formatStringForSQL(prefix+"index_fields", "index_id", rs.getData(0))); connection.deleteRow(prefix+"indexes", "id", rs.getDataLong(0)); } } else { return new CodaResponse(true, null, 8002); } // Remove all reference columns to subtables of this table rs = connection.runQuery("select f.id, f.field_name, f.array_flag, t.table_name from "+prefix+"table_fields f inner join "+prefix+"tables t on t.id = f.ref_table_id where t.parent_table_id = " + connection.formatStringForSQL(prefix+"tables", "parent_table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { if (rs.getDataInt(2) == 1) { connection.dropTable(rs.getData(1)); } connection.dropColumn(rs.getData(3), rs.getData(1)); connection.deleteRow(prefix+"table_fields", "id", rs.getDataLong(0)); } } // Remove all indexes on reference columns on other tables. Phew. rs = connection.runQuery("select i.id, i.index_name from "+prefix+"indexes i inner join "+prefix+"index_fields inf on inf.index_id = i.id inner join "+prefix+"table_fields tf on tf.id = inf.table_field_id where tf.ref_table_id = " + connection.formatStringForSQL(prefix+"table_fields", "ref_table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { connection.dropIndex(rs.getData(1)); connection.runStatement("delete from "+prefix+"index_fields where index_id = " + connection.formatStringForSQL(prefix+"index_fields", "index_id", rs.getData(0))); connection.deleteRow(prefix+"indexes", "id", rs.getDataLong(0)); } } else { return new CodaResponse(true, null, 8002); } // Remove all reference columns to this table rs = connection.runQuery("select f.id, f.field_name, f.array_flag, t.table_name from "+prefix+"table_fields f where f.ref_table_id = " + connection.formatStringForSQL(prefix+"table_fields", "ref_table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { if (rs.getDataInt(2) == 1) { connection.dropTable(rs.getData(1)); } connection.dropColumn(rs.getData(3), rs.getData(1)); connection.deleteRow(prefix+"table_fields", "id", rs.getDataLong(0)); } } // Remove all indexes on subtables to this table. rs = connection.runQuery("select i.id, i.index_name from "+prefix+"indexes i inner join "+prefix+"tables t on t.id = i.table_id where t.parent_table_id = " + connection.formatStringForSQL(prefix+"tables", "parent_table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { connection.dropIndex(rs.getData(1)); connection.runStatement("delete from "+prefix+"index_fields where index_id = " + connection.formatStringForSQL(prefix+"index_fields", "index_id", rs.getData(0))); connection.deleteRow(prefix+"indexes", "id", rs.getDataLong(0)); } } // Remove all array columns from subtables to this query rs = connection.runQuery("select f.field_name from "+prefix+"table_fields f inner join "+prefix+"tables t on t.id = f.table_id where f.array_flag = 1 and t.parent_table_id = " + connection.formatStringForSQL(prefix+"tables", "parent_table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { connection.dropTable(rs.getData(0)); } } // Remove all subtables to this table rs = connection.runQuery("select t.id, t.table_name from "+prefix+"tables t where parent_table_id = " + connection.formatStringForSQL(prefix+"tables", "parent_table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { connection.dropTable(rs.getData(1)); connection.runStatement("delete from "+prefix+"table_fields where table_id = " + connection.formatStringForSQL(prefix+"table_fields", "table_id", rs.getData(0))); connection.deleteRow(prefix+"tables", "id", rs.getDataLong(0)); } } // Remove all array columns for this table rs = connection.runQuery("select f.field_name from "+prefix+"table_fields f where f.array_flag = 1 and f.table_id = " + connection.formatStringForSQL(prefix+"table_fields", "table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { connection.dropTable(rs.getData(0)); } } // Remove the indexes for this table rs = connection.runQuery("select i.id, i.index_name from "+prefix+"indexes i where i.table_id = " + connection.formatStringForSQL(prefix+"indexes", "table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { connection.dropIndex(rs.getData(1)); connection.runStatement("delete from "+prefix+"index_fields where index_id = " + connection.formatStringForSQL(prefix+"index_fields", "index_id", rs.getData(0))); connection.deleteRow(prefix+"indexes", "id", rs.getDataLong(0)); } } // Remove all triggers for this table connection.runStatement("delete from "+prefix+"triggers where table_id = " + connection.formatStringForSQL(prefix+"triggers", "table_id", Long.toString(tableId))); /** TODO: reload triggers */ // Remove all permissions for this table connection.runStatement("delete from "+prefix+"role_tables where table_id = " + connection.formatStringForSQL(prefix+"role_tables", "table_id", Long.toString(tableId))); // Remove the table itself connection.dropTable(tableName); connection.runStatement("delete from "+prefix+"table_fields where table_id = " + connection.formatStringForSQL(prefix+"table_fields", "table_id", Long.toString(tableId))); connection.deleteRow(prefix+"tables", "id", tableId); connection.commit(); } catch (SQLException e) { connection.rollback(); return new CodaResponse(true, null, 8004, "The following error was reported by the database:" + e.getMessage()); } return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public synchronized CodaResponse createForm (String sessionKey, CodaDatabase database, String applicationName, String tableName, String displayName, boolean groupFlag, String parentTableName, Vector<TableFieldDefinition> fields, Vector<FormStatusDefinition> statuses, boolean loadClass) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } CodaConnection connection = database.getConnection(); // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag){ if (this.getIdForObjectName(tableName, CodaServer.OBJECT_TYPE_TABLE, connection) > 0) { return new CodaResponse(true, null, 2042); } long parentTableId = -1; if (parentTableName != null) { parentTableId = this.getIdForObjectName(parentTableName, CodaServer.OBJECT_TYPE_TABLE, connection); if(parentTableId < 0) { return new CodaResponse(true, null, 2041, "Form '" + parentTableName + "' is invalid"); } if (this.getIdForObjectName(Long.toString(parentTableId) + "." + tableName.toUpperCase(), CodaServer.OBJECT_TYPE_TABLE_COLUMN, connection) > 0) { return new CodaResponse(true, null, 2064); } if (!this.isForm(connection, prefix, parentTableName)) { return new CodaResponse(true, null, 2044); } } Vector<String> fieldNames = new Vector(); Vector<String> identityFieldNames = new Vector(); Vector<Long> identityFieldIds = new Vector(); // Get an execution context to test the default values ExecutionContext context = new ExecutionContext(this, database); Vector<String> reservedColumns = this.getReservedColumnNames(); for (TableFieldDefinition field : fields) { if (reservedColumns.contains(field.getFieldName().toUpperCase())) { return new CodaResponse(true, null, 2075, "The field name '" + field.getFieldName() + "' is reserved"); } if (fieldNames.contains(field.getFieldName().toUpperCase())) { return new CodaResponse(true, null, 2043, "Field '" + field.getFieldName() + "' defined multiple times"); } else { fieldNames.add(field.getFieldName().toUpperCase()); } long typeId = this.getIdForObjectName(this.database.getConnection(), field.getTypeName(), CodaServer.OBJECT_TYPE_TYPE); if (typeId < 0) { return new CodaResponse(true, null, 2020, "Type '" + field.getTypeName() + "' is invalid"); } if (field.isRefFlag()) { if (this.getIdForObjectName(field.getRefTableName(), CodaServer.OBJECT_TYPE_TABLE, connection) < 0) { return new CodaResponse(true, null, 2028, "Table/form '" + field.getRefTableName() + "' is invalid"); } } if (field.isArrayFlag()) { if (this.isArrayFieldNameInUse(connection, prefix, field.getFieldName().toUpperCase())) { return new CodaResponse(true, null, 2046, "Field '" + field.getFieldName() + "' must have a globally unique name"); } } if (field.getDefaultValue() != null || field.getDefaultVariableId() != -1) { if (!field.isArrayFlag()) { if (field.getDefaultVariableId() != -1) { if (field.getDefaultVariableId() == CodaConstant.SYSVAR_CURRENT_TIMESTAMP && !field.getTypeName().equalsIgnoreCase("TIMESTAMP")) { return new CodaResponse(true, null, 3001, "Default value '" + field.getDefaultValue() + "' does not match the correct type for column '" + field.getFieldName() + "'"); } else if (field.getDefaultVariableId() != CodaConstant.SYSVAR_CURRENT_TIMESTAMP && !field.getTypeName().equalsIgnoreCase("STRING") && !field.getTypeName().equalsIgnoreCase("LONGSTRING")) { return new CodaResponse(true, null, 3001, "Default value '" + field.getDefaultValue() + "' does not match the correct type for column '" + field.getFieldName() + "'"); } } else if (!context.validate(typeId, field.getDefaultValue())) { return new CodaResponse(true, null, 3001, "Default value '" + field.getDefaultValue() + "' does not match the correct type for column '" + field.getFieldName() + "'"); } } else if (field.isArrayFlag()) { if (field.getDefaultVariableId() != -1) { return new CodaResponse(true, null, 3001, "Default value '" + field.getDefaultValue() + "' does not match the correct type for array column '" + field.getFieldName() + "'"); } else if (!TypeParser.isArray(field.getDefaultValue())) { return new CodaResponse(true, null, 3001, "Default value for column '" + field.getFieldName() + "' should be an array"); } else { Vector<String> tokens = TypeParser.explodeArray(field.getDefaultValue()); for (String token : tokens) { if(!context.validate(typeId, token)) { return new CodaResponse(true, null, 3001, "Default value '" + field.getDefaultValue() + "' does not match the correct type for column '" + field.getFieldName() + "'"); } } } } } if (field.isIdentityFlag()) { identityFieldNames.add(field.getFieldName()); } } Vector<String> formStatusAdjs = new Vector(); Vector<String> formStatusVerbs = new Vector(); for(FormStatusDefinition status : statuses) { if (status.getFormStatusVerb().equalsIgnoreCase("UPDATE") || status.getFormStatusVerb().equalsIgnoreCase("INSERT") || status.getFormStatusVerb().equalsIgnoreCase("DELETE")) { return new CodaResponse(true, null, 2072); } if (formStatusAdjs.contains(status.getFormStatusAdj().toUpperCase())) { return new CodaResponse(true, null, 2047, "Form status adjective '" + status.getFormStatusAdj() + "' defined multiple times"); } else { formStatusAdjs.add(status.getFormStatusAdj().toUpperCase()); } if (formStatusVerbs.contains(status.getFormStatusVerb().toUpperCase())) { return new CodaResponse(true, null, 2048, "Form status verb '" + status.getFormStatusVerb() + "' defined multiple times"); } else { formStatusVerbs.add(status.getFormStatusVerb().toUpperCase()); } } if (displayName == null) { displayName = tableName; } // Insert table try { // add the built-in columns to the columnDefinitions and fields vectors fields.add(new TableFieldDefinition("ID", "INTEGER", "ID", false, false, null, null, true)); fields.add(new TableFieldDefinition("CREATE_USER_NAME", "STRING", "Creating Username", false, false, null, null, true)); fields.add(new TableFieldDefinition("CREATE_DATE", "TIMESTAMP", "Created Date", false, false, null, null, true)); fields.add(new TableFieldDefinition("MOD_USER_NAME", "STRING", "Last Modifying Username", false, false, null, null, true)); fields.add(new TableFieldDefinition("MOD_DATE", "TIMESTAMP", "Modified Date", false, false, null, null, true)); fields.add(new TableFieldDefinition("STATUS_ID", "INTEGER", "Status ID", false, false, null, null, true)); if (parentTableId > 0) { fields.add(new TableFieldDefinition("PARENT_TABLE_ID", "INTEGER", "Parent Table ID", false, false, null, null, true)); } if (groupFlag) { fields.add(new TableFieldDefinition("GROUP_NAME", "STRING", "Group Name", false, false, null, null, true)); } String classFile = GroovyClassGenerator.getTableClass(tableName, fields); Hashtable values = new Hashtable(); values.put("table_name", tableName.toUpperCase()); values.put("display_name", displayName); values.put("group_flag", groupFlag ? 1 : 0); values.put("form_flag", 1); values.put("class_file", classFile); values.put("soft_delete_flag", 0); values.put("ref_table_flag", 0); if (parentTableId >=0) { values.put("parent_table_id", parentTableId); } values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); long tableId = connection.insertRow(prefix+"tables", values); //load the class if needed if (loadClass) { this.deployedApplications.get(applicationName).loadClass(1, "org.codalang.codaserver.language.tables." + CodaServer.camelCapitalize(tableName, true),classFile); } ArrayList<ColumnDefinition> columnDefinitions = new ArrayList(); ArrayList<CodaTable> arrayTables = new ArrayList(); for (TableFieldDefinition field : fields) { values = new Hashtable(); values.put("table_id", tableId); values.put("field_name", field.getFieldName().toUpperCase()); values.put("display_name", field.getDisplayedAs() == null ? field.getFieldName() : field.getDisplayedAs()); values.put("type_name", field.getTypeName().toString().toUpperCase()); values.put("array_flag", field.isArrayFlag() ? 1 : 0); values.put("nullable_flag", field.isNullableFlag() ? 1 : 0); values.put("built_in_flag", field.isBuiltInFlag() ? 1 : 0); if (field.isRefFlag()) { values.put("ref_table_id", this.getIdForObjectName(field.getRefTableName(), CodaServer.OBJECT_TYPE_TABLE, connection)); } if (field.getDefaultVariableId() != -1) { values.put("default_variable_id", field.getDefaultVariableId()); } if (field.getDefaultValue() != null) { values.put("default_value", field.getDefaultValue()); } values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); long fieldId = connection.insertRow(prefix+"table_fields", values); if (identityFieldNames.contains(field.getFieldName())) { identityFieldIds.add(fieldId); } if (field.isArrayFlag()) { ColumnDefinition[] cols = new ColumnDefinition[2]; cols[0] = new ColumnDefinition("id", Types.BIGINT, false); cols[1] = new ColumnDefinition("value", CodaTypeConverter.getSQLTypeFromCodaType(field.getTypeName()), false); arrayTables.add(new CodaTable(field.getFieldName(), cols)); columnDefinitions.add(new ColumnDefinition(field.getFieldName().toUpperCase(), Types.CLOB, false)); } else { columnDefinitions.add(new ColumnDefinition(field.getFieldName().toUpperCase(), CodaTypeConverter.getSQLTypeFromCodaType(field.getTypeName()), field.isNullableFlag())); } } for (FormStatusDefinition status : statuses) { values = new Hashtable(); values.put("table_id", tableId); values.put("adj_status_name", status.getFormStatusAdj().toUpperCase()); values.put("adj_display_name", (status.getFormStatusAdjDisplayName() == null ? status.getFormStatusAdj() : status.getFormStatusAdjDisplayName())); values.put("verb_status_name", status.getFormStatusVerb().toUpperCase()); values.put("verb_display_name", (status.getFormStatusVerbDisplayName() == null ? status.getFormStatusVerb() : status.getFormStatusVerbDisplayName())); values.put("initial_flag", (status.isInitialFlag() ? "1" : "0")); values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.insertRow(prefix+"form_statuses", values); } try { connection.createTable(tableName, new Vector(columnDefinitions)); connection.setPrimaryKey(tableName, "ID"); for (CodaTable table : arrayTables) { connection.createTable(table.getTableName(), new Vector(Arrays.asList(table.getColumnDefinitions()))); } } catch (SQLException e) { connection.deleteRow(prefix+"tables", "id", tableId); return new CodaResponse(true, null, 8004, "The following error was reported by the database:" + e.getMessage()); } if (identityFieldNames.size() > 0) { try { connection.setIdentityColumns("ID_" + tableName.toUpperCase(), tableName, identityFieldNames); } catch (SQLException e) { return new CodaResponse(true, null, 8004, "The following error was reported by the database:" + e.getMessage()); } values = new Hashtable(); values.put("index_name", "ID_" + tableName.toUpperCase()); values.put("table_id", tableId); values.put("index_type_id", 2); values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); long indexId = connection.insertRow(prefix+"indexes", values); for (Long fieldId : identityFieldIds) { values = new Hashtable(); values.put("index_id", indexId); values.put("table_field_id", fieldId); connection.insertRow(prefix+"index_fields", values); } } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } catch (IOException e) { return new CodaResponse(true, null, 2085); } } else { return new CodaResponse(true, null, 9009); } } public synchronized CodaResponse alterForm (String sessionKey, CodaDatabase database, String applicationName, String tableName, int operation, String newTableName, String displayName, TableFieldDefinition field, String fieldName, Vector<String> identityFields, FormStatusDefinition status, String statusName, Vector<FormStatusLeadsTo> statuses, boolean loadClass) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } CodaConnection connection = database.getConnection(); // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } boolean formFlag = this.isForm(connection, prefix, tableName); if (!formFlag) { return new CodaResponse(true, null, 2092); } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag) { long tableId = this.getIdForObjectName(tableName, CodaServer.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2028); } Hashtable values = new Hashtable(); switch (operation) { case 1: values = new Hashtable(); values.put("display_name", displayName); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow(prefix+"tables", "id", tableId, values); connection.commit(); return new CodaResponse(false, "Success!", -1, null); case 2: if (this.getIdForObjectName(newTableName, CodaServer.OBJECT_TYPE_TABLE, connection) > 0) { return new CodaResponse(true, null, 2036); } try { connection.alterTable(tableName.toUpperCase(), newTableName.toUpperCase()); } catch (SQLException e) { return new CodaResponse(true, null, 8004, "The following error was reported by the database:" + e.getMessage()); } values = new Hashtable(); values.put("table_name", newTableName.toUpperCase()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow(prefix+"tables", "id", tableId, values); connection.commit(); return new CodaResponse(false, "Success!", -1, null); case 3: //add column return this.alterColumn(connection, formFlag, applicationName, tableId, tableName, fieldName, field, 1 , modUserId, sessionKey, loadClass); case 4: //alter column return this.alterColumn(connection, formFlag, applicationName, tableId, tableName, fieldName, field, 2 , modUserId, sessionKey, loadClass); case 5: //drop column return this.alterColumn(connection, formFlag, applicationName, tableId, tableName, fieldName, null, 3, modUserId, sessionKey, loadClass); case 6: //set identity long indexId = this.getIdForObjectName("ID_" + tableName.toUpperCase(), CodaServer.OBJECT_TYPE_INDEX, connection); if (indexId > 0 ) { try { connection.dropIndex("ID_" + tableName.toUpperCase()); } catch (SQLException e) { return new CodaResponse(true, null, 8004, "The following error was reported by the database:" + e.getMessage()); } connection.runStatement("delete from "+prefix+"index_fields where index_id = " + connection.formatStringForSQL(prefix+"index_fields", "index_id", Long.toString(indexId))); connection.deleteRow(prefix+"indexes", "id", indexId); } Vector<Long> identityFieldIds = new Vector(); for (String idFieldName : identityFields) { long tempFieldId = this.getIdForObjectName(Long.toString(tableId) + "." + idFieldName, CodaServer.OBJECT_TYPE_TABLE_COLUMN, connection); if (tempFieldId < 0) { return new CodaResponse(true, null, 2040, "Column name '" + idFieldName + "' not valid"); } else { identityFieldIds.add(tempFieldId); } } try { connection.setIdentityColumns("ID_" + tableName.toUpperCase(), tableName, identityFields); } catch (SQLException e) { return new CodaResponse(true, null, 8004, "The following error was reported by the database:" + e.getMessage()); } values = new Hashtable(); values.put("index_name", "ID_" + tableName.toUpperCase()); values.put("table_id", tableId); values.put("index_type_id", 2); values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); indexId = connection.insertRow(prefix+"indexes", values); for (Long tempFieldId : identityFieldIds) { values = new Hashtable(); values.put("index_id", indexId); values.put("table_field_id", tempFieldId); connection.insertRow(prefix+"index_fields", values); } connection.commit(); return new CodaResponse(false, "Success!", -1, null); case 7: //add status if (status.getFormStatusVerb().equalsIgnoreCase("UPDATE") || status.getFormStatusVerb().equalsIgnoreCase("INSERT") || status.getFormStatusVerb().equalsIgnoreCase("DELETE")) { return new CodaResponse(true, null, 2072); } if (this.getIdForObjectName(Long.toString(tableId) + "." + status.getFormStatusAdj().toUpperCase(), CodaServer.OBJECT_TYPE_FORM_STATUS_ADJ, connection) > 0) { return new CodaResponse(true, null, 2049); } if (this.getIdForObjectName(Long.toString(tableId) + "." + status.getFormStatusVerb().toUpperCase(), CodaServer.OBJECT_TYPE_FORM_STATUS_VERB, connection) > 0) { return new CodaResponse(true, null, 2050); } values = new Hashtable(); values.put("table_id", tableId); values.put("adj_status_name", status.getFormStatusAdj().toUpperCase()); values.put("adj_display_name", (status.getFormStatusAdjDisplayName() == null ? status.getFormStatusAdj() : status.getFormStatusAdjDisplayName())); values.put("verb_status_name", status.getFormStatusVerb().toUpperCase()); values.put("verb_display_name", (status.getFormStatusVerbDisplayName() == null ? status.getFormStatusVerb() : status.getFormStatusVerbDisplayName())); values.put("initial_flag", (status.isInitialFlag() ? 1 : 0)); values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.insertRow(prefix+"form_statuses", values); connection.commit(); return new CodaResponse(false, "Success!", -1, null); case 8: // alter status long formStatusId = this.getIdForObjectName(Long.toString(tableId) + "." + statusName.toUpperCase(), CodaServer.OBJECT_TYPE_FORM_STATUS_ADJ, connection); if (formStatusId < 0) { return new CodaResponse(true, null, 2051); } if (status.getFormStatusVerb().equalsIgnoreCase("UPDATE") || status.getFormStatusVerb().equalsIgnoreCase("INSERT") || status.getFormStatusVerb().equalsIgnoreCase("DELETE")) { return new CodaResponse(true, null, 2072); } long formStatusAdj = this.getIdForObjectName(Long.toString(tableId) + "." + status.getFormStatusAdj().toUpperCase(), CodaServer.OBJECT_TYPE_FORM_STATUS_ADJ, connection); if (formStatusAdj > 0 && formStatusAdj != formStatusId) { return new CodaResponse(true, null, 2049); } long formStatusVerb = this.getIdForObjectName(Long.toString(tableId) + "." + status.getFormStatusVerb().toUpperCase(), CodaServer.OBJECT_TYPE_FORM_STATUS_VERB, connection); if (formStatusVerb > 0 && formStatusVerb != formStatusId) { return new CodaResponse(true, null, 2050); } values = new Hashtable(); values.put("adj_status_name", status.getFormStatusAdj().toUpperCase()); values.put("adj_display_name", (status.getFormStatusAdjDisplayName() == null ? status.getFormStatusAdj() : status.getFormStatusAdjDisplayName())); values.put("verb_status_name", status.getFormStatusVerb().toUpperCase()); values.put("verb_display_name", (status.getFormStatusVerbDisplayName() == null ? status.getFormStatusVerb() : status.getFormStatusVerbDisplayName())); values.put("initial_flag", (status.isInitialFlag() ? 1 : 0)); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow(prefix+"form_statuses","id", formStatusId, values); connection.commit(); return new CodaResponse(false, "Success!", -1, null); case 9: // drop status formStatusId = this.getIdForObjectName(Long.toString(tableId) + "." + statusName.toUpperCase(), CodaServer.OBJECT_TYPE_FORM_STATUS_ADJ, connection); if (formStatusId < 0) { return new CodaResponse(true, null, 2051); } CodaResultSet rs = connection.runQuery("select count(*) from " + tableName + " where status_id = " + connection.formatStringForSQL(tableName, "status_id", Long.toString(formStatusId)), null); if (!rs.getErrorStatus() && rs.next()) { if (rs.getDataLong(0) > 0) { return new CodaResponse(true, null, 2052); } else { connection.runStatement("delete from "+prefix+"triggers where form_status_id = " + connection.formatStringForSQL(prefix+"triggers", "form_status_id", Long.toString(formStatusId))); connection.deleteRow(prefix+"form_statuses", "id", formStatusId); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } } else { return new CodaResponse(true, null, 8002); } case 10: Hashtable<String,Long> formStatusNames = new Hashtable(); for (FormStatusLeadsTo statusLead : statuses) { if (!formStatusNames.containsKey(statusLead.getStatusName().toUpperCase())) { long tempStatusId = this.getIdForObjectName(tableId + "." + statusLead.getStatusName().toUpperCase(), CodaServer.OBJECT_TYPE_FORM_STATUS_ADJ, connection); if (tempStatusId > 0) { formStatusNames.put(statusLead.getStatusName().toUpperCase(), tempStatusId); } else { return new CodaResponse(true, null, 2051, "Form status '" + statusLead.getStatusName() + "' is invalid"); } if (statusLead.getLeadsToList() != null) { for (String leadsTo : statusLead.getLeadsToList()) { if (!formStatusNames.containsKey(leadsTo.toUpperCase())) { tempStatusId = this.getIdForObjectName(tableId + "." + leadsTo.toUpperCase(), CodaServer.OBJECT_TYPE_FORM_STATUS_ADJ, connection); if (tempStatusId > 0) { formStatusNames.put(leadsTo.toUpperCase(), tempStatusId); } else { return new CodaResponse(true, null, 2051, "Form status '" + leadsTo + "' is invalid"); } } } } } else { if (statusLead.getLeadsToList() != null) { for (String leadsTo : statusLead.getLeadsToList()) { if (!formStatusNames.containsKey(leadsTo.toUpperCase())) { long tempStatusId = this.getIdForObjectName(tableId + "." + leadsTo.toUpperCase(), CodaServer.OBJECT_TYPE_FORM_STATUS_ADJ, connection); if (tempStatusId > 0) { formStatusNames.put(leadsTo.toUpperCase(), tempStatusId); } else { return new CodaResponse(true, null, 2051, "Form status '" + leadsTo + "' is invalid"); } } } } } } for (FormStatusLeadsTo statusLead : statuses) { connection.runStatement("delete from "+prefix+"form_status_relationships where form_status_id = " + connection.formatStringForSQL(prefix+"form_status_relationships", "form_status_id", Long.toString(formStatusNames.get(statusLead.getStatusName().toUpperCase())))); if (statusLead.getLeadsToList() != null && statusLead.getLeadsToList().size() > 0) { values = new Hashtable(); values.put("form_status_id", formStatusNames.get(statusLead.getStatusName().toUpperCase()).longValue()); values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); for(String leadsTo : statusLead.getLeadsToList()) { values.put("next_form_status_id", formStatusNames.get(leadsTo.toUpperCase()).longValue()); connection.insertRow(prefix+"form_status_relationships", values); } } } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public synchronized CodaResponse dropForm (String sessionKey, CodaDatabase database, String applicationName, String tableName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } CodaConnection connection = database.getConnection(); // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (!this.isForm(connection, prefix, tableName)) { return new CodaResponse(true, null, 2092); } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag) { long tableId = this.getIdForObjectName(tableName, CodaServer.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2028); } try { // Remove all indexes on reference columns on other tables that point to subtables of this table. Phew. CodaResultSet rs = connection.runQuery("select i.id, i.index_name from "+prefix+"indexes i inner join "+prefix+"index_fields inf on inf.index_id = i.id inner join "+prefix+"table_fields tf on tf.id = inf.table_field_id inner join "+prefix+"tables t on tf.ref_table_id = t.id where t.parent_table_id = " + connection.formatStringForSQL(prefix+"tables", "parent_table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { connection.dropIndex(rs.getData(1)); connection.runStatement("delete from "+prefix+"index_fields where index_id = " + connection.formatStringForSQL(prefix+"index_fields", "index_id", rs.getData(0))); connection.deleteRow(prefix+"indexes", "id", rs.getDataLong(0)); } } else { return new CodaResponse(true, null, 8002); } // Remove all reference columns to subtables of this table rs = connection.runQuery("select f.id, f.field_name, f.array_flag, t.table_name from "+prefix+"table_fields f inner join "+prefix+"tables t on t.id = f.ref_table_id where t.parent_table_id = " + connection.formatStringForSQL(prefix+"tables", "parent_table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { if (rs.getDataInt(2) == 1) { connection.dropTable(rs.getData(1)); } connection.dropColumn(rs.getData(3), rs.getData(1)); connection.deleteRow(prefix+"table_fields", "id", rs.getDataLong(0)); } } // Remove all indexes on reference columns on other tables. Phew. rs = connection.runQuery("select i.id, i.index_name from "+prefix+"indexes i inner join "+prefix+"index_fields inf on inf.index_id = i.id inner join "+prefix+"table_fields tf on tf.id = inf.table_field_id where tf.ref_table_id = " + connection.formatStringForSQL(prefix+"table_fields", "ref_table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { connection.dropIndex(rs.getData(1)); connection.runStatement("delete from "+prefix+"index_fields where index_id = " + connection.formatStringForSQL(prefix+"index_fields", "index_id", rs.getData(0))); connection.deleteRow(prefix+"indexes", "id", rs.getDataLong(0)); } } else { return new CodaResponse(true, null, 8002); } // Remove all reference columns to this table rs = connection.runQuery("select f.id, f.field_name, f.array_flag, t.table_name from "+prefix+"table_fields f where f.ref_table_id = " + connection.formatStringForSQL(prefix+"table_fields", "ref_table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { if (rs.getDataInt(2) == 1) { connection.dropTable(rs.getData(1)); } connection.dropColumn(rs.getData(3), rs.getData(1)); connection.deleteRow(prefix+"table_fields", "id", rs.getDataLong(0)); } } // Remove all indexes on subtables to this table. rs = connection.runQuery("select i.id, i.index_name from "+prefix+"indexes i inner join "+prefix+"tables t on t.id = i.table_id where t.parent_table_id = " + connection.formatStringForSQL(prefix+"tables", "parent_table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { connection.dropIndex(rs.getData(1)); connection.runStatement("delete from "+prefix+"index_fields where index_id = " + connection.formatStringForSQL(prefix+"index_fields", "index_id", rs.getData(0))); connection.deleteRow(prefix+"indexes", "id", rs.getDataLong(0)); } } // Remove all array columns from subtables to this query rs = connection.runQuery("select f.field_name from "+prefix+"table_fields f inner join "+prefix+"tables t on t.id = f.table_id where f.array_flag = 1 and t.parent_table_id = " + connection.formatStringForSQL(prefix+"tables", "parent_table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { connection.dropTable(rs.getData(0)); } } // Remove all form statuses for subforms of this table rs = connection.runQuery("select fs.id from "+prefix+"form_statuses fs inner join "+prefix+"tables t on fs.table_id = t.id where t.parent_table_id = " + connection.formatStringForSQL(prefix+"tables", "parent_table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { connection.runStatement("delete from "+prefix+"form_status_relationships where form_status_id = " + connection.formatStringForSQL(prefix+"form_status_relationships", "form_status_id", rs.getData(0))); connection.deleteRow(prefix+"form_statuses", "id", rs.getDataLong(0)); } } // Remove all subtables to this table rs = connection.runQuery("select t.id, t.table_name from "+prefix+"tables t where parent_table_id = " + connection.formatStringForSQL(prefix+"tables", "parent_table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { connection.dropTable(rs.getData(1)); connection.runStatement("delete from "+prefix+"table_fields where table_id = " + connection.formatStringForSQL(prefix+"table_fields", "table_id", rs.getData(0))); connection.deleteRow(prefix+"tables", "id", rs.getDataLong(0)); } } // Remove all array columns for this table rs = connection.runQuery("select f.field_name from "+prefix+"table_fields f where f.array_flag = 1 and f.table_id = " + connection.formatStringForSQL(prefix+"table_fields", "table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { connection.dropTable(rs.getData(0)); } } // Remove the indexes for this table rs = connection.runQuery("select i.id, i.index_name from "+prefix+"indexes i where i.table_id = " + connection.formatStringForSQL(prefix+"indexes", "table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { connection.dropIndex(rs.getData(1)); connection.runStatement("delete from "+prefix+"index_fields where index_id = " + connection.formatStringForSQL(prefix+"index_fields", "index_id", rs.getData(0))); connection.deleteRow(prefix+"indexes", "id", rs.getDataLong(0)); } } // Remove all triggers for this table connection.runStatement("delete from "+prefix+"triggers where table_id = " + connection.formatStringForSQL(prefix+"triggers", "table_id", Long.toString(tableId))); /** TODO: reload triggers */ // Remove all permissions for this table connection.runStatement("delete from "+prefix+"role_tables where table_id = " + connection.formatStringForSQL(prefix+"role_tables", "table_id", Long.toString(tableId))); // Remove the form statuses for this table rs = connection.runQuery("select fs.id from "+prefix+"form_statuses fs where fs.table_id = " + connection.formatStringForSQL(prefix+"form_statuses", "table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { connection.runStatement("delete from "+prefix+"form_status_relationships where form_status_id = " + connection.formatStringForSQL(prefix+"form_status_relationships", "form_status_id", rs.getData(0))); connection.deleteRow(prefix+"form_statuses", "id", rs.getDataLong(0)); } } // Remove the table itself connection.dropTable(tableName); connection.runStatement("delete from "+prefix+"table_fields where table_id = " + connection.formatStringForSQL(prefix+"table_fields", "table_id", Long.toString(tableId))); connection.deleteRow(prefix+"tables", "id", tableId); connection.commit(); } catch (SQLException e) { connection.rollback(); return new CodaResponse(true, null, 8004, "The following error was reported by the database:" + e.getMessage()); } return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse createIndex(String sessionKey, CodaDatabase database, String applicationName, String indexName, String tableName, Vector<String> fields, boolean uniqueFlag) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } CodaConnection connection = database.getConnection(); // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag) { if (indexName.startsWith("PK_") || indexName.startsWith("ID_")) { return new CodaResponse(true, null, 2054); } if (this.getIdForObjectName(indexName, CodaServer.OBJECT_TYPE_INDEX, connection) > 0) { return new CodaResponse(true, null, 2053); } long tableId = this.getIdForObjectName(tableName, CodaServer.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2028); } Vector<Long> fieldIds = new Vector(); for (String fieldName : fields) { long fieldId = this.getIdForObjectName(tableId + "." + fieldName, CodaServer.OBJECT_TYPE_TABLE_COLUMN, connection); if (fieldId < 0){ return new CodaResponse(true, null, 2040, (this.isForm(connection, prefix, tableName) ? "Field name '" + fieldName + "' is invalid" : "Column name '" + fieldName + "' is invalid")); } else { fieldIds.add(fieldId); } } try { connection.createIndex(indexName.toUpperCase(), tableName.toUpperCase(), fields, uniqueFlag); } catch (SQLException e) { return new CodaResponse(true, null, 8004, "The following error was reported by the database:" + e.getMessage()); } Hashtable values = new Hashtable(); values.put("index_name", indexName.toUpperCase()); values.put("table_id", tableId); values.put("index_type_id", (uniqueFlag ? 2 : 3)); values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); long indexId = connection.insertRow(prefix+"indexes", values); for (Long fieldId : fieldIds) { values = new Hashtable(); values.put("index_id", indexId); values.put("table_field_id", fieldId); connection.insertRow(prefix+"index_fields", values); } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse dropIndex(String sessionKey, CodaDatabase database, String applicationName, String indexName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } CodaConnection connection = database.getConnection(); // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag) { long indexId = this.getIdForObjectName(indexName, CodaServer.OBJECT_TYPE_INDEX, connection); if (indexId < 0) { return new CodaResponse(true, null, 2055); } try { connection.dropIndex(indexName.toUpperCase()); } catch (SQLException e) { return new CodaResponse(true, null, 8004, "The following error was reported by the database:" + e.getMessage()); } connection.runStatement("delete from " +prefix+"index_fields where index_id = " +connection.formatStringForSQL(prefix+"index_fields", "index_id", Long.toString(indexId))); connection.deleteRow(prefix+"indexes", "id", indexId); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse createCron(String sessionKey, String applicationName, String environmentString, String cronName, String minutePart, String hourPart, String dayOfMonth, String month, String dayOfWeek, String procedureName, Vector<String> parameters, String executeUsername, String executePassword) { int environment = 1; if (environmentString.equalsIgnoreCase("DEV")) { environment = 1; } else if (environmentString.equalsIgnoreCase("TEST")) { environment = 2; } else if (environmentString.equalsIgnoreCase("PROD")) { environment = 3; } else { return new CodaResponse(true, null, 2013, "Invalid environment specified"); } long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } long executeUserId = modUserId; if (executeUsername != null && executePassword != null) { CodaConnection connection = database.getConnection(); CodaResultSet rs = connection.runQuery("select id from users where active_flag = 1 and user_name = " + connection.formatStringForSQL("users", "user_name", executeUsername) + " and pass_word = " + connection.formatStringForSQL("users", "pass_word", encrypt(executePassword)) + " ", null); if (!rs.getErrorStatus() && rs.getRowsReturned() > 0) { if (!rs.next()) { return new CodaResponse(true, null, 1001); } } else { return new CodaResponse(true, null, 1001); } } else { executeUsername = this.getSessionUsername(sessionKey); } if (!deployedApplications.hasProcedurePermission(applicationName, executeUserId, -1, environment, Datasource.PROCEDURE_EXECUTE, procedureName.toUpperCase())) { return new CodaResponse(true, null, 9011); } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, environment, "MANAGE_CRONS" )) { CodaDatabase database = this.getApplicationDatabase(applicationName, environment); CodaConnection connection = database.getConnection(), serverConnection = this.database.getConnection(); // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (this.getIdForObjectName(cronName, CodaServer.OBJECT_TYPE_CRON, connection) > 0) { return new CodaResponse(true, null, 2057); } long procedureId = this.getIdForObjectName(procedureName, CodaServer.OBJECT_TYPE_PROCEDURE, connection); if (procedureId < 0) { return new CodaResponse(true, null, 2056); } ExecutionContext context = new ExecutionContext(this, database); Vector<Long> procedureParameterIds = new Vector(); Vector<String> procedureTypeNames = new Vector(); Vector<Boolean> procedureArrayFlags = new Vector(); CodaResultSet rs = connection.runQuery("select pp.type_name, pp.array_flag, pp.id from "+prefix+"procedure_parameters pp where pp.procedure_id = " + connection.formatStringForSQL(prefix+"procedure_parameters", "procedure_id", Long.toString(procedureId)) + " order by order_number asc",null); if (!rs.getErrorStatus()) { while (rs.next()) { procedureTypeNames.add(rs.getData(0)); procedureArrayFlags.add(rs.getData(1).equals("1")); procedureParameterIds.add(rs.getDataLong(2)); } } if (procedureTypeNames.size() != parameters.size()) { return new CodaResponse(true, null, 2058); } if (procedureTypeNames.size() > 0) { CodaResponse resp = new CodaResponse(); for(int i = 0; i < procedureTypeNames.size(); i++) { long typeId = this.getIdForObjectName(serverConnection, procedureTypeNames.get(i), this.OBJECT_TYPE_TYPE); if (procedureArrayFlags.get(i).booleanValue()) { if (TypeParser.isArray(parameters.get(i))) { Vector<String> arrayValues = TypeParser.explodeArray(parameters.get(i)); for (String arrayValue : arrayValues) { if (!context.validate(typeId, arrayValue)){ resp.addError(new CodaError(3001, "Parameter " + (i + 1) + " contains an invalid " + context.getDisplayName(typeId))); } } } } else { if (!context.validate(typeId, parameters.get(i))){ resp.addError(new CodaError(3001, "Parameter " + (i + 1) + " is not a valid " + context.getDisplayName(typeId))); } } } if (resp.getError()) { return resp; } } JobDetail detail = new JobDetail(applicationName.toUpperCase() + "_" + environment + "_" + cronName.toUpperCase(), null, ProcedureJob.class); JobDataMap map = new JobDataMap(); map.put("cronName", cronName); map.put("server", this); map.put("applicationName", applicationName); map.put("environment", environment); map.put("procedureName", procedureName.toUpperCase()); map.put("parameters", parameters); map.put("userId", executeUserId); detail.setJobDataMap(map); try { this.scheduleJob(applicationName, environment, cronName.toUpperCase(), "0 " + minutePart + " " + hourPart + " " + dayOfMonth + " " + month + " " + dayOfWeek, detail); } catch (ParseException pe) { return new CodaResponse(true, null, 2060); } catch (SchedulerException se) { return new CodaResponse(true, null, 2061); } Hashtable values = new Hashtable(); values.put("cron_name", cronName.toUpperCase()); values.put("procedure_id", procedureId); values.put("minute_part", minutePart); values.put("hour_part", hourPart); values.put("day_of_month_part", dayOfMonth); values.put("month_part", month); values.put("day_of_week_part", dayOfWeek); values.put("executing_user_name", executeUsername); values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); long cronId = connection.insertRow(prefix+"crons", values); int j = 0; for (String parameter : parameters) { values = new Hashtable(); values.put("cron_id", cronId); values.put("parameter_value", parameter); values.put("procedure_parameter_id", procedureParameterIds.get(j)); connection.insertRow(prefix+"cron_parameters", values); j++; } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9010); } } public CodaResponse dropCron(String sessionKey, String applicationName, String environmentString, String cronName) { int environment = 1; if (environmentString.equalsIgnoreCase("DEV")) { environment = 1; } else if (environmentString.equalsIgnoreCase("TEST")) { environment = 2; } else if (environmentString.equalsIgnoreCase("PROD")) { environment = 3; } else { return new CodaResponse(true, null, 2013, "Invalid environment specified"); } long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, environment, "MANAGE_CRONS")) { CodaDatabase database = this.getApplicationDatabase(applicationName, environment); CodaConnection connection = database.getConnection(); // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } long cronId = this.getIdForObjectName(cronName, CodaServer.OBJECT_TYPE_CRON, connection); if (cronId < 0) { return new CodaResponse(true, null, 2062); } try { this.stopJob(applicationName, environment, cronName.toUpperCase()); } catch (SchedulerException se) { return new CodaResponse(true, null, 2061); } connection.runStatement("delete from "+prefix+"cron_parameters where cron_id = " + connection.formatStringForSQL(prefix+"cron_parameters", "cron_id", Long.toString(cronId))); connection.deleteRow(prefix+"crons", "id", cronId); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9010); } } public CodaResponse selectObject(String sessionKey, String tableName, long objectId, boolean greedyFlag, CodaConnection procConnection) { long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } String applicationName = sessions.getSessionApplication(sessionKey); CodaConnection connection; CodaDatabase database = deployedApplications.getDatasource(applicationName, environmentId).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8003); } if (procConnection == null) { connection = database.getConnection(); } else { connection = procConnection; } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } long tableId = this.getIdForObjectName(tableName, CodaServer.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2028); } boolean formFlag = this.isForm(connection, prefix, tableName); boolean groupFlag = this.isGroupTable(connection, prefix, tableName); if (!formFlag && !deployedApplications.hasTablePermission(applicationName, userId, (groupFlag ? sessions.getSessionGroupId(sessionKey) : -1), environmentId, Datasource.TABLE_SELECT, tableName)) { return new CodaResponse(true, null, 9012); } Vector retval = new Vector(); CodaResultSet rs = connection.runQuery("select * from " + tableName + " where id = " + connection.formatStringForSQL(tableName, "id", Long.toString(objectId)), null); if (!rs.getErrorStatus() && rs.next()) { if (formFlag && !deployedApplications.hasFormStatusPermission(applicationName, userId, (groupFlag ? sessions.getSessionGroupId(sessionKey) : -1), environmentId, Datasource.FORM_STATUS_VIEW, tableName, rs.getDataLong("status") )) { return new CodaResponse(true, null, 9013); } if (!greedyFlag) { return new CodaResponse(rs); } else { retval.add(rs); } } else { return new CodaResponse(true, null, 2067); } if (greedyFlag) { rs = connection.runQuery("select table_name from "+prefix+"tables where parent_table_id = " + connection.formatStringForSQL(prefix+"tables", "parent_table_id", Long.toString(tableId)), null); if (!rs.getErrorStatus()) { while (rs.next()) { if ((!formFlag && deployedApplications.hasTablePermission(applicationName, userId, (groupFlag ? sessions.getSessionGroupId(sessionKey) : -1), environmentId, Datasource.TABLE_SELECT, rs.getData(0))) || formFlag) { Hashtable temp = new Hashtable(); CodaResultSet rs2 = connection.runQuery("select * from " + rs.getData(0) + " where parent_table_id = " + connection.formatStringForSQL(rs.getData(0), "parent_table_id", Long.toString(objectId)), null); if (!rs2.getErrorStatus() && rs2.next()) { if (!formFlag || (formFlag && deployedApplications.hasFormStatusPermission(applicationName, userId, (groupFlag ? sessions.getSessionGroupId(sessionKey) : -1), environmentId, Datasource.FORM_STATUS_VIEW, rs.getData(0), rs2.getDataLong("status") ))) { retval.add(rs2); } } } } } } return new CodaResponse(retval); } public CodaResponse insert (String sessionKey, String tableName, Vector<String> columns, Vector<Vector> rows, CodaConnection procConnection) { long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } String applicationName = sessions.getSessionApplication(sessionKey); CodaConnection connection, serverConnection; serverConnection = this.database.getConnection(); CodaDatabase database = deployedApplications.getDatasource(applicationName, environmentId).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8003); } if (procConnection == null) { connection = database.getConnection(); } else { connection = procConnection; } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } long tableId = this.getIdForObjectName(tableName.toUpperCase(), CodaServer.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2028); } boolean formFlag = this.isForm(connection, prefix, tableName); if (formFlag) { return new CodaResponse(true, null, 2071); } boolean subTableFlag = this.isSubTable(connection, prefix, tableName); boolean groupFlag = this.isGroupTable(connection, prefix, tableName); if (groupFlag && sessions.getSessionGroup(sessionKey) == null) { return new CodaResponse(true, null, 2074); } boolean softDeleteFlag = this.isSoftDeleteTable(connection, prefix, tableName); if (!deployedApplications.hasTablePermission(applicationName, userId, (groupFlag ? sessions.getSessionGroupId(sessionKey) : -1), environmentId, Datasource.TABLE_INSERT, tableName)) { return new CodaResponse(true, null, 9014); } ExecutionContext context = new ExecutionContext(this, database); Hashtable<String,TableFieldDefinition> fields = this.getFieldsForTable(connection, prefix, tableId); // get rid of the stray row if (rows.get(rows.size() - 1).size() == 0) { rows.remove(rows.size() - 1); } //capitalize the columns. This is just to make life easier for (int i = 0; i < columns.size(); i++) { columns.set(i, columns.get(i).toUpperCase()); } //verify all of the columns specified are valid for (String columnName : columns) { if (! fields.containsKey(columnName.toUpperCase()) ) { return new CodaResponse(true, null, 2068, "Column '" +columnName+ "' not found in table '"+ tableName +"'"); } } // check for the parent table id if needed if (subTableFlag && !columns.contains("PARENT_TABLE_ID")) { return new CodaResponse(true, null, 2073); } //verify that every non-nullable column without a default is included in the insert clause for (TableFieldDefinition field : fields.values()) { if (!field.isNullableFlag()) { if (!field.isBuiltInFlag() && field.getDefaultVariableId() == -1 && field.getDefaultValue() == null && !columns.contains(field.getFieldName())) { return new CodaResponse(true, null, 2070, "Must specify a value or default for NOT NULL column '" + field.getFieldName() + "'"); } } } //validate all of the data before inserting CodaResponse resp = new CodaResponse(); for (int j = 0; j < rows.size(); j++) { List<String> row = rows.get(j); for (int i = 0; i < row.size(); i++) { if (row.get(i) == null) { if (fields.get(columns.get(i)).getDefaultVariableId() > 0) { switch (fields.get(columns.get(i)).getDefaultVariableId()) { case CodaConstant.SYSVAR_CURRENT_TIMESTAMP: row.set(i, Long.toString(new GregorianCalendar().getTimeInMillis())); break; case CodaConstant.SYSVAR_CURRENT_USER_ID: row.set(i, Long.toString(sessions.getSessionUserId(sessionKey))); break; case CodaConstant.SYSVAR_CURRENT_USERNAME: row.set(i, sessions.getSessionUsername(sessionKey)); break; case CodaConstant.SYSVAR_CURRENT_GROUP_NAME: row.set(i, sessions.getSessionGroup(sessionKey)); break; } } else if (fields.get(columns.get(i)).getDefaultValue() != null) { row.set(i, fields.get(columns.get(i)).getDefaultValue()); } else { resp.addError(new CodaError(2070, (rows.size() > 1 ? "On row " + (j + 1) + ", p" : "P") +"lease specify a value for " + fields.get(columns.get(i)).getDisplayedAs())); } } else if (row.get(i).equalsIgnoreCase("CURRENT_TIMESTAMP")) { row.set(i, Long.toString(new GregorianCalendar().getTimeInMillis())); } else if (row.get(i).equalsIgnoreCase("CURRENT_USER_ID")) { row.set(i, Long.toString(sessions.getSessionUserId(sessionKey))); } else if (row.get(i).equalsIgnoreCase("CURRENT_USERNAME")) { row.set(i, sessions.getSessionUsername(sessionKey)); } else if (row.get(i).equalsIgnoreCase("CURRENT_GROUP_NAME")) { row.set(i, sessions.getSessionGroup(sessionKey)); } else if (fields.get(columns.get(i)).isArrayFlag()) { if (TypeParser.isArray(row.get(i))) { Vector<String> items = TypeParser.explodeArray(row.get(i)); for (String item : items) { if (!context.validate(fields.get(columns.get(i)).getTypeId(), item)) { resp.addError(new CodaError(2070, (rows.size() > 1 ? "On row " + (j + 1) + ", e" : "E") +"ach of the " + fields.get(columns.get(i)).getDisplayedAs() + " must be of type " + context.getDisplayName(fields.get(columns.get(i)).getTypeId()))); break; } } } else { resp.addError(new CodaError(2070, (rows.size() > 1 ? "On row " + (j + 1) + ", a" : "A") +"n array is expected for the " + fields.get(columns.get(i)).getDisplayedAs())); } } else { if (!context.validate(this.getIdForObjectName(serverConnection, fields.get(columns.get(i)).getTypeName(), CodaServer.OBJECT_TYPE_TYPE), row.get(i))) { resp.addError(new CodaError(2070, (rows.size() > 1 ? "On row " + (j + 1) + ", " : "") + fields.get(columns.get(i)).getDisplayedAs() + " must be of type " + context.getDisplayName(fields.get(columns.get(i)).getTypeId()))); } } } } // return if there are errors if (resp.getError()) { return resp; } // set the classloader for the execution context context.setClassLoader(deployedApplications.get(applicationName.toUpperCase()).getEnvironmentClassLoader(environmentId, context.getClassLoader())); CodaResultSetColumnHeading crsch = new CodaResultSetColumnHeading("id", Types.BIGINT); Vector retvalHeadings = new Vector(); retvalHeadings.add(crsch); CodaResultSet retval = new CodaResultSet(retvalHeadings); // Insert! for (int j = 0; j < rows.size(); j++) { List<String> row = rows.get(j); Hashtable values = new Hashtable(); Hashtable<String,Vector> arrayValues = new Hashtable(); for (int i = 0; i < row.size(); i++) { if (fields.get(columns.get(i)).isArrayFlag()) { values.put(fields.get(columns.get(i)).getFieldName(), row.get(i)); arrayValues.put(fields.get(columns.get(i)).getFieldName(), TypeParser.explodeArray(row.get(i))); } else { values.put(fields.get(columns.get(i)).getFieldName(), row.get(i)); } } if (groupFlag && !values.containsKey("GROUP_ID")) { values.put("GROUP_ID", sessions.getSessionGroupId(sessionKey)); } if (softDeleteFlag && !values.containsKey("ACTIVE_FLAG")) { values.put("ACTIVE_FLAG", 1); } if (!values.containsKey("CREATE_USER_NAME")) { values.put("CREATE_USER_NAME", sessions.getSessionUsername(sessionKey)); } if (!values.containsKey("CREATE_DATE")) { values.put("CREATE_DATE", new GregorianCalendar().getTimeInMillis()); } if (!values.containsKey("MOD_USER_NAME")) { values.put("MOD_USER_NAME", sessions.getSessionUsername(sessionKey)); } if (!values.containsKey("MOD_DATE")) { values.put("MOD_DATE", new GregorianCalendar().getTimeInMillis()); } // call before trigger Vector<Hashtable> triggerHashtables = this.prepareHashtablesForTrigger(context, serverConnection, fields, null, values); try { deployedApplications.get(applicationName).runTrigger(context, tableName, "insert", true, new Database(this, sessionKey, connection), triggerHashtables.get(1), triggerHashtables.get(0)); } catch (ClassNotFoundException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (IllegalAccessException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (InstantiationException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (CodaException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } long id = connection.insertRow(tableName.toUpperCase(), values); Vector rowVector = new Vector(); rowVector.add(id); retval.addRow(rowVector); if (id < 0) { if (procConnection == null) { connection.rollback(); } return new CodaResponse(true, null, 3005); } else { Enumeration enum1 = arrayValues.keys(); while (enum1.hasMoreElements()) { String key = (String)enum1.nextElement(); Vector<String> elts = arrayValues.get(key); for (String elt : elts) { Hashtable values2 = new Hashtable(); values2.put("id", id); values2.put("value", elt); connection.insertRow(key, values2); } } // call after trigger try { triggerHashtables.get(1).put("id", id); deployedApplications.get(applicationName).runTrigger(context, tableName, "insert", false, new Database(this, sessionKey, connection), triggerHashtables.get(1), triggerHashtables.get(0)); } catch (ClassNotFoundException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (IllegalAccessException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (InstantiationException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (CodaException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } } } if (procConnection == null) { connection.commit(); } return new CodaResponse(retval); } public CodaResponse update (String sessionKey, String tableName, Vector<String> columns, Vector<String> row, CodaSearchCondition whereClause, CodaConnection procConnection) { long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } String applicationName = sessions.getSessionApplication(sessionKey); CodaConnection connection, serverConnection; serverConnection = this.database.getConnection(); CodaDatabase database = deployedApplications.getDatasource(applicationName, environmentId).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8003); } if (procConnection == null) { connection = database.getConnection(); } else { connection = procConnection; } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } long tableId = this.getIdForObjectName(tableName, CodaServer.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2028); } boolean formFlag = this.isForm(connection, prefix, tableName); boolean subTableFlag = this.isSubTable(connection, prefix, tableName); boolean groupFlag = this.isGroupTable(connection, prefix, tableName); if (groupFlag && sessions.getSessionGroup(sessionKey) == null) { return new CodaResponse(true, null, 2074); } boolean softDeleteFlag = this.isSoftDeleteTable(connection, prefix, tableName); if (!deployedApplications.hasTablePermission(applicationName, userId, (groupFlag ? sessions.getSessionGroupId(sessionKey) : -1), environmentId, Datasource.TABLE_UPDATE, tableName)) { return new CodaResponse(true, null, 9014); } ExecutionContext context = new ExecutionContext(this, database); Hashtable<String,TableFieldDefinition> fields = this.getFieldsForTable(connection, prefix, tableId); //capitalize the columns. This is just to make life easier for (int i = 0; i < columns.size(); i++) { columns.set(i, columns.get(i).toUpperCase()); } //verify all of the columns specified are valid for (String columnName : columns) { if (! ( columnName.equalsIgnoreCase("ID") || columnName.equalsIgnoreCase("CREATE_USER_ID") || columnName.equalsIgnoreCase("CREATE_USER_NAME") || columnName.equalsIgnoreCase("CREATE_DATE") || columnName.equalsIgnoreCase("MOD_USER_ID") || columnName.equalsIgnoreCase("MOD_USER_NAME") || columnName.equalsIgnoreCase("MOD_DATE") || (softDeleteFlag && columnName.equalsIgnoreCase("ACTIVE_FLAG")) || (groupFlag && columnName.equalsIgnoreCase("GROUP_ID")) || (subTableFlag && ((!formFlag && columnName.equalsIgnoreCase("PARENT_TABLE_ID")) || (formFlag && columnName.equalsIgnoreCase("PARENT_FORM_ID")))) || fields.containsKey(columnName.toUpperCase()) ) ) { return new CodaResponse(true, null, 2068, "Column '" +columnName+ "' not found in table '"+ tableName +"'"); } } // check for the parent table id if needed if (subTableFlag && ((!formFlag && !columns.contains("PARENT_TABLE_ID")) || (formFlag && !columns.contains("PARENT_FORM_ID")))) { return new CodaResponse(true, null, 2073); } //verify that every non-nullable column without a default is included in the insert clause /* for (TableFieldDefinition field : fields.values()) { if (columns.contains(field.getFieldName()) && columns. && !field.isNullableFlag() && field.getDefaultVariableId() == -1 && field.getDefaultValue() == null) { return new CodaResponse(true, null, 2070, "Must specify a value or default for NOT NULL column '" + field.getFieldName() + "'"); } } */ //validate all of the data before inserting CodaResponse resp = new CodaResponse(); for (int i = 0; i < row.size(); i++) { if (row.get(i) == null) { if (fields.get(columns.get(i)).getDefaultVariableId() > 0) { switch (fields.get(columns.get(i)).getDefaultVariableId()) { case CodaConstant.SYSVAR_CURRENT_TIMESTAMP: row.set(i, Long.toString(new GregorianCalendar().getTimeInMillis())); break; case CodaConstant.SYSVAR_CURRENT_USER_ID: row.set(i, Long.toString(sessions.getSessionUserId(sessionKey))); break; case CodaConstant.SYSVAR_CURRENT_USERNAME: row.set(i, sessions.getSessionUsername(sessionKey)); break; case CodaConstant.SYSVAR_CURRENT_GROUP_NAME: row.set(i, sessions.getSessionGroup(sessionKey)); break; } } else if (fields.get(columns.get(i)).getDefaultValue() != null) { row.set(i, fields.get(columns.get(i)).getDefaultValue()); } else if (!fields.get(columns.get(i)).isNullableFlag()) { resp.addError(new CodaError(2070, "Please specify a value for " + fields.get(columns.get(i)).getDisplayedAs())); } } else if (row.get(i).equalsIgnoreCase("CURRENT_TIMESTAMP")) { row.set(i, Long.toString(new GregorianCalendar().getTimeInMillis())); } else if (row.get(i).equalsIgnoreCase("CURRENT_USER_ID")) { row.set(i, Long.toString(sessions.getSessionUserId(sessionKey))); } else if (row.get(i).equalsIgnoreCase("CURRENT_USERNAME")) { row.set(i, sessions.getSessionUsername(sessionKey)); } else if (row.get(i).equalsIgnoreCase("CURRENT_GROUP_NAME")) { row.set(i, sessions.getSessionGroup(sessionKey)); } else if (fields.get(columns.get(i)).isArrayFlag()) { if (TypeParser.isArray(row.get(i))) { Vector<String> items = TypeParser.explodeArray(row.get(i)); for (String item : items) { if (!context.validate(fields.get(columns.get(i)).getTypeId(), item)) { resp.addError(new CodaError(2070, "Each of the " + fields.get(columns.get(i)).getDisplayedAs() + " must be of type " + context.getDisplayName(fields.get(columns.get(i)).getTypeId()))); break; } } } else { resp.addError(new CodaError(2070, "An array is expected for the " + fields.get(columns.get(i)).getDisplayedAs())); } } else { if (!context.validate(this.getIdForObjectName(serverConnection, fields.get(columns.get(i)).getTypeName(), CodaServer.OBJECT_TYPE_TYPE), row.get(i))) { resp.addError(new CodaError(2070, fields.get(columns.get(i)).getDisplayedAs() + " must be of type " + context.getDisplayName(fields.get(columns.get(i)).getTypeId()))); } } } // return if there are errors if (resp.getError()) { return resp; } CodaResultSet rs = null; try { CodaFromClause fromClause = new CodaFromClause(tableName); fromClause.setDatabase(database); rs = connection.runQuery("select id from " + tableName + (whereClause != null ? " where " + whereClause.print(fromClause) : "" ), null); } catch (CodaException ex) { return new CodaResponse(true, null, 8004, "Something went wrong trying to figure out which records to update."); } if (rs == null || rs.getErrorStatus()) { return new CodaResponse(true, null, 8004, rs.getErrorString()); } else { // grab ids to insert Vector<Long> idsToUpdate = new Vector(); while (rs.next()) { idsToUpdate.add(rs.getDataLong(0)); } if (idsToUpdate.size() > 0) { // create values hashtable Hashtable values = new Hashtable(); Hashtable<String,Vector> arrayValues = new Hashtable(); for (int i = 0; i < row.size(); i++) { if (fields.get(columns.get(i)).isArrayFlag()) { values.put(fields.get(columns.get(i)).getFieldName(), row.get(i)); arrayValues.put(fields.get(columns.get(i)).getFieldName(), TypeParser.explodeArray(row.get(i))); } else { values.put(fields.get(columns.get(i)).getFieldName(), row.get(i)); } } if (groupFlag && !values.containsKey("GROUP_ID")) { values.put("GROUP_ID", sessions.getSessionGroupId(sessionKey)); } if (softDeleteFlag && !values.containsKey("ACTIVE_FLAG")) { values.put("ACTIVE_FLAG", 1); } if (!values.containsKey("MOD_USER_NAME")) { values.put("MOD_USER_NAME", sessions.getSessionUsername(sessionKey)); } if (!values.containsKey("MOD_DATE")) { values.put("MOD_DATE", new GregorianCalendar().getTimeInMillis()); } // set the classloader for the execution context context.setClassLoader(deployedApplications.get(applicationName.toUpperCase()).getEnvironmentClassLoader(environmentId, context.getClassLoader())); // call before trigger Vector<Vector> updatingRecords = new Vector(); CodaResultSet triggerResult = connection.runQuery("select id from "+prefix+"triggers where table_id = " +connection.formatStringForSQL(prefix+"triggers", "table_id", Long.toString(tableId)) + " and before_flag = 1 and operation_id = 1 ", null); if (!triggerResult.getErrorStatus() && triggerResult.next()) { CodaResultSet currentRows = connection.selectRows(tableName, "id", idsToUpdate); if (!currentRows.getErrorStatus()) { Vector<String> allColumnNames = currentRows.getColumnNames(); while (currentRows.next()) { Hashtable rowHashtable = new Hashtable(); for (int j = 0; j < allColumnNames.size(); j++) { rowHashtable.put(allColumnNames.get(j), currentRows.getData(j)); } updatingRecords.add(this.prepareHashtablesForTrigger(context, serverConnection, fields, rowHashtable, values)); } } for (Vector<Hashtable> i : updatingRecords) { try { deployedApplications.get(applicationName).runTrigger(context, tableName, "update", true, new Database(this, sessionKey, connection), i.get(1), i.get(0)); } catch (ClassNotFoundException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (IllegalAccessException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (InstantiationException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (CodaException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } } } // do update boolean success = connection.updateRows(tableName, "id", idsToUpdate, values); if(!success) { if (procConnection == null) { connection.rollback(); } return new CodaResponse(true, null, 3005); } else { Enumeration enum1 = arrayValues.keys(); for(Long id : idsToUpdate) { while (enum1.hasMoreElements()) { String key = (String)enum1.nextElement(); connection.runStatement("delete from " + key + " where id = " + connection.formatStringForSQL(key, "id", Long.toString(id))); Vector<String> elts = arrayValues.get(key); for (String elt : elts) { Hashtable values2 = new Hashtable(); values2.put("id", id); values2.put("value", elt); connection.insertRow(key, values2); } } } // call after trigger triggerResult = connection.runQuery("select id from "+prefix+"triggers where table_id = " +connection.formatStringForSQL(prefix+"triggers", "table_id", Long.toString(tableId)) + " and before_flag = 0 and operation_id = 1 ", null); if (!triggerResult.getErrorStatus() && triggerResult.next()) { if (updatingRecords.size() == 0) { CodaResultSet currentRows = connection.selectRows(tableName, "id", idsToUpdate); if (!currentRows.getErrorStatus()) { Vector<String> allColumnNames = currentRows.getColumnNames(); while (currentRows.next()) { Hashtable rowHashtable = new Hashtable(); for (int j = 0; j < allColumnNames.size(); j++) { rowHashtable.put(allColumnNames.get(j), currentRows.getData(j)); } updatingRecords.add(this.prepareHashtablesForTrigger(context, serverConnection, fields, rowHashtable, values)); } } } for (Vector<Hashtable> i : updatingRecords) { try { deployedApplications.get(applicationName).runTrigger(context, tableName, "update", false, new Database(this, sessionKey, connection), i.get(1), i.get(0)); } catch (ClassNotFoundException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (IllegalAccessException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (InstantiationException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (CodaException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } } } } } } if (procConnection == null) { connection.commit(); } return new CodaResponse(false, "Success!", -1, null); } public CodaResponse delete (String sessionKey, String tableName, CodaSearchCondition whereClause, CodaConnection procConnection) { long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } String applicationName = sessions.getSessionApplication(sessionKey); CodaConnection connection, serverConnection; serverConnection = this.database.getConnection(); CodaDatabase database = deployedApplications.getDatasource(applicationName, environmentId).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8003); } if (procConnection == null) { connection = database.getConnection(); } else { connection = procConnection; } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } long tableId = this.getIdForObjectName(tableName, CodaServer.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2028); } boolean formFlag = this.isForm(connection, prefix, tableName); boolean subTableFlag = this.isSubTable(connection, prefix, tableName); boolean groupFlag = this.isGroupTable(connection, prefix, tableName); if (groupFlag && sessions.getSessionGroup(sessionKey) == null) { return new CodaResponse(true, null, 2074); } boolean softDeleteFlag = this.isSoftDeleteTable(connection, prefix, tableName); if (!deployedApplications.hasTablePermission(applicationName, userId, (groupFlag ? sessions.getSessionGroupId(sessionKey) : -1), environmentId, Datasource.TABLE_DELETE, tableName)) { return new CodaResponse(true, null, 9014); } ExecutionContext context = new ExecutionContext(this, database); CodaResultSet rs = null; try { CodaFromClause fromClause = new CodaFromClause(tableName); fromClause.setDatabase(database); rs = connection.runQuery("select id from " + tableName + (whereClause != null ? " where " + whereClause.print(fromClause) : ""), null); } catch (CodaException ex) { return new CodaResponse(true, null, 8004, "Something went wrong trying to figure out which records to update."); } if (rs == null || rs.getErrorStatus()) { return new CodaResponse(true, null, 8004, rs.getErrorString()); } else { // grab ids to delete Vector<Long> idsToUpdate = new Vector(); while (rs.next()) { idsToUpdate.add(rs.getDataLong(0)); } if (idsToUpdate.size() > 0) { // set the classloader for the execution context context.setClassLoader(deployedApplications.get(applicationName.toUpperCase()).getEnvironmentClassLoader(environmentId, context.getClassLoader())); // call before trigger Vector<Vector> updatingRecords = new Vector(); CodaResultSet triggerResult = connection.runQuery("select id from "+prefix+"triggers where table_id = " +connection.formatStringForSQL(prefix+"triggers", "table_id", Long.toString(tableId)) + " and before_flag = 1 and operation_id = 3 ", null); if (!triggerResult.getErrorStatus() && triggerResult.next()) { CodaResultSet currentRows = connection.selectRows(tableName, "id", idsToUpdate); if (!currentRows.getErrorStatus()) { Vector<String> allColumnNames = currentRows.getColumnNames(); while (currentRows.next()) { Hashtable rowHashtable = new Hashtable(); for (int j = 0; j < allColumnNames.size(); j++) { rowHashtable.put(allColumnNames.get(j), currentRows.getData(j)); } updatingRecords.add(this.prepareHashtablesForTrigger(context, serverConnection, this.getFieldsForTable(connection, prefix, tableId), rowHashtable, null)); } } for (Vector<Hashtable> i : updatingRecords) { try { deployedApplications.get(applicationName).runTrigger(context, tableName, "delete", true, new Database(this, sessionKey, connection), i.get(1), i.get(0)); } catch (ClassNotFoundException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (IllegalAccessException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (InstantiationException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (CodaException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } } } if (!softDeleteFlag) { Hashtable<String,TableFieldDefinition> fields = this.getFieldsForTable(connection, prefix, tableId); Vector<String> arrayColumns = new Vector(); Enumeration<String> fieldNames = fields.keys(); while (fieldNames.hasMoreElements()) { String fieldName = fieldNames.nextElement(); if (fields.get(fieldName).isArrayFlag()) { arrayColumns.add(fieldName); } } for (String key : arrayColumns) { connection.deleteRows(key, "id", idsToUpdate); } } if (softDeleteFlag) { Hashtable values = new Hashtable(); values.put("active_flag", 0); connection.updateRows(tableName, "id", idsToUpdate, values); } else { connection.deleteRows(tableName, "id", idsToUpdate); } // call after trigger triggerResult = connection.runQuery("select id from "+prefix+"triggers where table_id = " +connection.formatStringForSQL(prefix+"triggers", "table_id", Long.toString(tableId)) + " and before_flag = 0 and operation_id = 3 ", null); if (!triggerResult.getErrorStatus() && triggerResult.next()) { if (updatingRecords.size() == 0) { CodaResultSet currentRows = connection.selectRows(tableName, "id", idsToUpdate); if (!currentRows.getErrorStatus()) { Vector<String> allColumnNames = currentRows.getColumnNames(); while (currentRows.next()) { Hashtable rowHashtable = new Hashtable(); for (int j = 0; j < allColumnNames.size(); j++) { rowHashtable.put(allColumnNames.get(j), currentRows.getData(j)); } updatingRecords.add(this.prepareHashtablesForTrigger(context, serverConnection, this.getFieldsForTable(connection, prefix, tableId), rowHashtable, null)); } } } for (Vector<Hashtable> i : updatingRecords) { try { deployedApplications.get(applicationName).runTrigger(context, tableName, "delete", false, new Database(this, sessionKey, connection), i.get(1), i.get(0)); } catch (ClassNotFoundException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (IllegalAccessException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (InstantiationException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (CodaException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } } } } } if (procConnection == null) { connection.commit(); } return new CodaResponse(false, "Success!", -1, null); } public CodaResponse formUpdate (String sessionKey, String formStatusVerb, String tableName, Vector<String> columns, Vector<String> row, boolean initialize, CodaSearchCondition whereClause, CodaConnection procConnection) { long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } String applicationName = sessions.getSessionApplication(sessionKey); CodaConnection connection, serverConnection; serverConnection = this.database.getConnection(); CodaDatabase database = deployedApplications.getDatasource(applicationName, environmentId).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8003); } if (procConnection == null) { connection = database.getConnection(); } else { connection = procConnection; } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } long tableId = this.getIdForObjectName(tableName, CodaServer.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2028); } long formStatusId = this.getIdForObjectName(Long.toString(tableId) + "." + formStatusVerb.toUpperCase(), CodaServer.OBJECT_TYPE_FORM_STATUS_VERB, connection); if (formStatusId < 0) { return new CodaResponse(true, null, 2076); } boolean initialFlag = this.isInitialFormStatus(connection, prefix, formStatusId); if (initialize && !initialFlag) { return new CodaResponse(true, null, 2077); } boolean formFlag = this.isForm(connection, prefix, tableName); boolean subTableFlag = this.isSubTable(connection, prefix, tableName); boolean groupFlag = this.isGroupTable(connection, prefix, tableName); if (groupFlag && sessions.getSessionGroup(sessionKey) == null) { return new CodaResponse(true, null, 2074); } if (!deployedApplications.hasFormStatusPermission(applicationName, userId, (groupFlag ? sessions.getSessionGroupId(sessionKey) : -1), environmentId, Datasource.FORM_STATUS_CALL, tableName, formStatusVerb, false)) { return new CodaResponse(true, null, 9015); } ExecutionContext context = new ExecutionContext(this, database); Hashtable<String,TableFieldDefinition> fields = this.getFieldsForTable(connection, prefix, tableId); //capitalize the columns. This is just to make life easier for (int i = 0; i < columns.size(); i++) { columns.set(i, columns.get(i).toUpperCase()); } //verify all of the columns specified are valid for (String columnName : columns) { if (! ( columnName.equalsIgnoreCase("ID") || columnName.equalsIgnoreCase("CREATE_USER_ID") || columnName.equalsIgnoreCase("CREATE_USER_NAME") || columnName.equalsIgnoreCase("CREATE_DATE") || columnName.equalsIgnoreCase("MOD_USER_ID") || columnName.equalsIgnoreCase("MOD_USER_NAME") || columnName.equalsIgnoreCase("MOD_DATE") || (groupFlag && columnName.equalsIgnoreCase("GROUP_ID")) || (subTableFlag && ((!formFlag && columnName.equalsIgnoreCase("PARENT_TABLE_ID")) || (formFlag && columnName.equalsIgnoreCase("PARENT_FORM_ID")))) || fields.containsKey(columnName.toUpperCase()) ) ) { return new CodaResponse(true, null, 2068, "Column '" +columnName+ "' not found in table '"+ tableName +"'"); } } // check for the parent table id if needed if (subTableFlag && ((!formFlag && !columns.contains("PARENT_TABLE_ID")) || (formFlag && !columns.contains("PARENT_FORM_ID")))) { return new CodaResponse(true, null, 2073); } //validate all of the data before inserting CodaResponse resp = new CodaResponse(); for (int i = 0; i < row.size(); i++) { if (row.get(i) == null) { if (fields.get(columns.get(i)).getDefaultVariableId() > 0) { switch (fields.get(columns.get(i)).getDefaultVariableId()) { case CodaConstant.SYSVAR_CURRENT_TIMESTAMP: row.set(i, Long.toString(new GregorianCalendar().getTimeInMillis())); break; case CodaConstant.SYSVAR_CURRENT_USER_ID: row.set(i, Long.toString(sessions.getSessionUserId(sessionKey))); break; case CodaConstant.SYSVAR_CURRENT_USERNAME: row.set(i, sessions.getSessionUsername(sessionKey)); break; case CodaConstant.SYSVAR_CURRENT_GROUP_NAME: row.set(i, sessions.getSessionGroup(sessionKey)); break; } } else if (fields.get(columns.get(i)).getDefaultValue() != null) { row.set(i, fields.get(columns.get(i)).getDefaultValue()); } else { resp.addError(new CodaError(2070, "Please specify a value for " + fields.get(columns.get(i)).getDisplayedAs())); } } else if (row.get(i).equalsIgnoreCase("CURRENT_TIMESTAMP")) { row.set(i, Long.toString(new GregorianCalendar().getTimeInMillis())); } else if (row.get(i).equalsIgnoreCase("CURRENT_USER_ID")) { row.set(i, Long.toString(sessions.getSessionUserId(sessionKey))); } else if (row.get(i).equalsIgnoreCase("CURRENT_USERNAME")) { row.set(i, sessions.getSessionUsername(sessionKey)); } else if (row.get(i).equalsIgnoreCase("CURRENT_GROUP_NAME")) { row.set(i, sessions.getSessionGroup(sessionKey)); } else if (fields.get(columns.get(i)).isArrayFlag()) { if (TypeParser.isArray(row.get(i))) { Vector<String> items = TypeParser.explodeArray(row.get(i)); for (String item : items) { if (!context.validate(fields.get(columns.get(i)).getTypeId(), item)) { resp.addError(new CodaError(2070, "Each of the " + fields.get(columns.get(i)).getDisplayedAs() + " must be of type " + context.getDisplayName(fields.get(columns.get(i)).getTypeId()))); break; } } } else { resp.addError(new CodaError(2070, "An array is expected for the " + fields.get(columns.get(i)).getDisplayedAs())); } } else { if (!context.validate(this.getIdForObjectName(serverConnection, fields.get(columns.get(i)).getTypeName(), CodaServer.OBJECT_TYPE_TYPE), row.get(i))) { resp.addError(new CodaError(2070, fields.get(columns.get(i)).getDisplayedAs() + " must be of type " + context.getDisplayName(fields.get(columns.get(i)).getTypeId()))); } } } // return if there are errors if (resp.getError()) { return resp; } // Check if we need to do an update or an insert if (initialize) { // initialize the return value CodaResultSetColumnHeading crsch = new CodaResultSetColumnHeading("id", Types.BIGINT); Vector retvalHeadings = new Vector(); retvalHeadings.add(crsch); CodaResultSet retval = new CodaResultSet(retvalHeadings); //verify that every non-nullable column without a default is included in the insert clause Hashtable values = new Hashtable(); Hashtable<String,Vector> arrayValues = new Hashtable(); for (int i = 0; i < row.size(); i++) { if (fields.get(columns.get(i)).isArrayFlag()) { values.put(fields.get(columns.get(i)).getFieldName(), row.get(i)); arrayValues.put(fields.get(columns.get(i)).getFieldName(), TypeParser.explodeArray(row.get(i))); } else { values.put(fields.get(columns.get(i)).getFieldName(), row.get(i)); } } values.put("STATUS_ID", formStatusId); if (groupFlag && !values.containsKey("GROUP_ID")) { values.put("GROUP_ID", sessions.getSessionGroupId(sessionKey)); } if (!values.containsKey("CREATE_USER_NAME")) { values.put("CREATE_USER_NAME", sessions.getSessionUsername(sessionKey)); } if (!values.containsKey("CREATE_DATE")) { values.put("CREATE_DATE", new GregorianCalendar().getTimeInMillis()); } if (!values.containsKey("MOD_USER_NAME")) { values.put("MOD_USER_NAME", sessions.getSessionUsername(sessionKey)); } if (!values.containsKey("MOD_DATE")) { values.put("MOD_DATE", new GregorianCalendar().getTimeInMillis()); } // set the classloader for the execution context context.setClassLoader(deployedApplications.get(applicationName.toUpperCase()).getEnvironmentClassLoader(environmentId, context.getClassLoader())); // call before trigger Vector<Hashtable> rowHashtables = this.prepareHashtablesForTrigger(context, serverConnection, fields, null, values); try { deployedApplications.get(applicationName).runTrigger(context, tableName, formStatusVerb, true, new Database(this, sessionKey, connection), rowHashtables.get(1), rowHashtables.get(0)); } catch (ClassNotFoundException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (IllegalAccessException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (InstantiationException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (CodaException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } long id = connection.insertRow(tableName.toUpperCase(), values); Vector rowVector = new Vector(); rowVector.add(id); retval.addRow(rowVector); if (id < 0) { if (procConnection == null) { connection.rollback(); } return new CodaResponse(true, null, 3005); } else { Enumeration enum1 = arrayValues.keys(); while (enum1.hasMoreElements()) { String key = (String)enum1.nextElement(); Vector<String> elts = arrayValues.get(key); for (String elt : elts) { Hashtable values2 = new Hashtable(); values2.put("id", id); values2.put("value", elt); connection.insertRow(key, values2); } } // call after trigger try { rowHashtables.get(1).put("id", id); deployedApplications.get(applicationName).runTrigger(context, tableName, formStatusVerb, false, new Database(this, sessionKey, connection), rowHashtables.get(1), rowHashtables.get(0)); } catch (ClassNotFoundException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (IllegalAccessException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (InstantiationException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (CodaException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } } if (procConnection == null) { connection.commit(); } return new CodaResponse(retval); } else { // Get the valid statuses that can lead to the requested status CodaResultSet rs = connection.runQuery("select form_status_id from "+prefix+"form_status_relationships where next_form_status_id = "+ connection.formatStringForSQL(prefix+"form_status_relationships", "next_form_status_id", Long.toString(formStatusId)), null); StringBuffer formStatusString = new StringBuffer(); if (rs.getErrorStatus()) { return new CodaResponse(true, null, 8004, rs.getErrorString()); } else { boolean first = true; while (rs.next()) { if (first) { first = false; } else { formStatusString.append(", "); } formStatusString.append(connection.formatStringForSQL(tableName, "status_id", rs.getData(0))); } } // Do the query to get all of the IDs to be updated try { CodaFromClause fromClause = new CodaFromClause(tableName); fromClause.setDatabase(database); rs = connection.runQuery("select id from " + tableName + " where " + (whereClause != null ? whereClause.print(fromClause) + " and " : "") + " status_id in (" + formStatusString.toString() + ")", null); } catch (CodaException ex) { return new CodaResponse(true, null, 8004, "Something went wrong trying to figure out which records to update."); } if (rs.getErrorStatus()) { return new CodaResponse(true, null, 8004, rs.getErrorString()); } else { // grab ids to insert Vector<Long> idsToUpdate = new Vector(); while (rs.next()) { idsToUpdate.add(rs.getDataLong(0)); } if (idsToUpdate.size() > 0) { // create values hashtable Hashtable values = new Hashtable(); Hashtable<String,Vector> arrayValues = new Hashtable(); for (int i = 0; i < row.size(); i++) { if (fields.get(columns.get(i)).isArrayFlag()) { values.put(fields.get(columns.get(i)).getFieldName(), row.get(i)); arrayValues.put(fields.get(columns.get(i)).getFieldName(), TypeParser.explodeArray(row.get(i))); } else { values.put(fields.get(columns.get(i)).getFieldName(), row.get(i)); } } values.put("STATUS_ID", formStatusId); if (groupFlag && !values.containsKey("GROUP_ID")) { values.put("GROUP_ID", sessions.getSessionGroupId(sessionKey)); } if (!values.containsKey("MOD_USER_NAME")) { values.put("MOD_USER_NAME", sessions.getSessionUsername(sessionKey)); } if (!values.containsKey("MOD_DATE")) { values.put("MOD_DATE", new GregorianCalendar().getTimeInMillis()); } // set the classloader for the execution context context.setClassLoader(deployedApplications.get(applicationName.toUpperCase()).getEnvironmentClassLoader(environmentId, context.getClassLoader())); // call before trigger Vector<Vector> updatingRecords = new Vector(); CodaResultSet triggerResult = connection.runQuery("select id from "+prefix+"triggers where table_id = " +connection.formatStringForSQL(prefix+"triggers", "table_id", Long.toString(tableId)) + " and before_flag = 1 and form_status_id = " + connection.formatStringForSQL(prefix+"triggers", "form_status_id", Long.toString(formStatusId)), null); if (!triggerResult.getErrorStatus() && triggerResult.next()) { CodaResultSet currentRows = connection.selectRows(tableName, "id", idsToUpdate); if (!currentRows.getErrorStatus()) { Vector<String> allColumnNames = currentRows.getColumnNames(); while (currentRows.next()) { Hashtable rowHashtable = new Hashtable(); for (int j = 0; j < allColumnNames.size(); j++) { rowHashtable.put(allColumnNames.get(j), currentRows.getData(j)); } updatingRecords.add(this.prepareHashtablesForTrigger(context, serverConnection, fields, rowHashtable, values)); } } for (Vector<Hashtable> i : updatingRecords) { try { deployedApplications.get(applicationName).runTrigger(context, tableName, formStatusVerb, true, new Database(this, sessionKey, connection), i.get(1), i.get(0)); } catch (ClassNotFoundException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (IllegalAccessException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (InstantiationException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } catch (CodaException e) { return new CodaResponse(true, null, 4002, e.getMessage()); } } } // do update boolean success = connection.updateRows(tableName, "id", idsToUpdate, values); if (!success) { if (procConnection == null) { connection.rollback(); } return new CodaResponse(true, null, 3005); } else { Enumeration enum1 = arrayValues.keys(); for(Long id : idsToUpdate) { while (enum1.hasMoreElements()) { String key = (String)enum1.nextElement(); connection.runStatement("delete from " + key + " where id = " + connection.formatStringForSQL(key, "id", Long.toString(id))); Vector<String> elts = arrayValues.get(key); for (String elt : elts) { Hashtable values2 = new Hashtable(); values2.put("id", id); values2.put("value", elt); connection.insertRow(key, values2); } } } triggerResult = connection.runQuery("select id from "+prefix+"triggers where table_id = " +connection.formatStringForSQL(prefix+"triggers", "table_id", Long.toString(tableId)) + " and before_flag = 0 and form_status_id = " + connection.formatStringForSQL(prefix+"triggers", "form_status_id", Long.toString(formStatusId)), null); if (!triggerResult.getErrorStatus() && triggerResult.next()) { if (updatingRecords.size() == 0) { CodaResultSet currentRows = connection.selectRows(tableName, "id", idsToUpdate); if (!currentRows.getErrorStatus()) { Vector<String> allColumnNames = currentRows.getColumnNames(); while (currentRows.next()) { Hashtable rowHashtable = new Hashtable(); for (int j = 0; j < allColumnNames.size(); j++) { rowHashtable.put(allColumnNames.get(j), currentRows.getData(j)); } updatingRecords.add(this.prepareHashtablesForTrigger(context, serverConnection, fields, rowHashtable, values)); } } } for (Vector<Hashtable> i : updatingRecords) { try { deployedApplications.get(applicationName).runTrigger(context, tableName, formStatusVerb, false, new Database(this, sessionKey, connection), i.get(1), i.get(0)); } catch (Exception e) { return new CodaResponse(true, null, 4002, e.getMessage()); } } } } } } } if (procConnection == null) { connection.commit(); } return new CodaResponse(false, "Success!", -1, null); } public CodaResponse commit (String sessionKey) { long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } String applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = deployedApplications.getDatasource(applicationName, environmentId).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } public CodaResponse rollback (String sessionKey) { long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } String applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = deployedApplications.getDatasource(applicationName, environmentId).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); connection.rollback(); return new CodaResponse(false, "Success!", -1, null); } public CodaResponse select (String sessionKey, String selectClause, CodaFromClause fromClause, CodaSearchCondition whereClause, String groupByClause, String havingClause, String orderByClause, long top, long startingAt, CodaConnection procConnection) { long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } String applicationName = sessions.getSessionApplication(sessionKey); CodaConnection connection; CodaDatabase database = deployedApplications.getDatasource(applicationName, environmentId).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8003); } if (procConnection == null) { connection = database.getConnection(); } else { connection = procConnection; } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } Hashtable<String,Vector> acceptableStatus = new Hashtable(); Vector<CodaTableNameAlias> tables = fromClause.getMappings(); for (CodaTableNameAlias tableName : tables) { if (!this.isForm(connection, prefix, tableName.getTableName())) { if (!deployedApplications.hasTablePermission(applicationName, userId, (this.isGroupTable(connection, prefix, tableName.getTableName()) ? sessions.getSessionGroupId(sessionKey) : -1), environmentId, Datasource.TABLE_SELECT, tableName.getTableName())) { return new CodaResponse(true, null, 9012); } } else { acceptableStatus.put(tableName.getAlias() == null ? tableName.getTableName() : tableName.getAlias(), deployedApplications.getFormStatusesForPermission(applicationName, userId, (this.isGroupTable(connection, prefix, tableName.getTableName()) ? sessions.getSessionGroupId(sessionKey) : -1), environmentId, Datasource.FORM_STATUS_VIEW, tableName.getTableName())); } } CodaResultSet rs = null; try { if (fromClause != null) { fromClause.setColumns(this, database); } String whereClauseAddition = ""; boolean first = true; for (String alias : acceptableStatus.keySet()) { if (first) { first = false; } else { whereClauseAddition += " and "; } if (acceptableStatus.get(alias).size() == 0) { whereClauseAddition += alias + ".status_id is null "; } else { whereClauseAddition += alias + ".status_id in ("; for (int i = 0; i < acceptableStatus.get(alias).size(); i++) { if (i != 0) { whereClauseAddition += ", "; } whereClauseAddition += acceptableStatus.get(alias).get(i).toString(); } whereClauseAddition += ") "; } } String sql = selectClause + (fromClause != null ? fromClause.print() : "") + (fromClause != null ? (whereClauseAddition != "" || whereClause != null ? " where " : "") + (whereClause != null ? whereClause.print(fromClause) + " and " + whereClauseAddition : whereClauseAddition) : "" ) + (groupByClause != null ? groupByClause : "") + (havingClause != null ? havingClause : "") + (orderByClause != null ? orderByClause : ""); rs = connection.runQuery(sql , null, top, startingAt); if (rs.getErrorStatus()) { return new CodaResponse(true, null, 8004, rs.getErrorString()); } else { return new CodaResponse(rs); } } catch (Exception e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } public CodaResponse sysSelect (String sessionKey, String selectClause, CodaFromClause fromClause, CodaSearchCondition whereClause, String groupByClause, String havingClause, String orderByClause, long top, long startingAt) { if (!sessions.hasServerPermission(sessionKey, "QUERY_SYSTEM_TABLES")) { return new CodaResponse(true, null, 9017); } CodaConnection connection = database.getConnection(); long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } CodaResultSet rs = null; try { if (fromClause != null) { fromClause.setColumns(this, database); } String sql = selectClause + " " + (fromClause != null ? fromClause.print() : "") + (fromClause != null && whereClause != null ? " where " + (whereClause != null ? whereClause.print(fromClause) : "") : "") + (groupByClause != null ? groupByClause : "") + (havingClause != null ? havingClause : "") + (orderByClause != null ? orderByClause : ""); rs = connection.runQuery(sql , null, top, startingAt); if (rs.getErrorStatus()) { return new CodaResponse(true, null, 8004, rs.getErrorString()); } else { return new CodaResponse(rs); } } catch (Exception e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } public CodaResponse rawSelect (String sessionKey, String selectStatement, CodaConnection procConnection) { long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } String applicationName = sessions.getSessionApplication(sessionKey); CodaConnection connection; CodaDatabase database = deployedApplications.getDatasource(applicationName, environmentId).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8003); } if (procConnection == null) { connection = database.getConnection(); } else { connection = procConnection; } CodaResultSet rs = connection.runQuery(selectStatement, null); if (rs.getErrorStatus()) { return new CodaResponse(true, null, 8004, rs.getErrorString()); } else { return new CodaResponse(rs); } } public CodaResponse rawStatement (String sessionKey, String sqlStatement, CodaConnection procConnection) { long userId = sessions.getSessionUserId(sessionKey); if (userId < 0) { return new CodaResponse(true, null, 1005); } int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } String applicationName = sessions.getSessionApplication(sessionKey); CodaConnection connection; if (procConnection == null) { CodaDatabase database = deployedApplications.getDatasource(applicationName, environmentId).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8003); } connection = database.getConnection(); } else { connection = procConnection; } try { connection.runStatementWithException(sqlStatement); if (procConnection == null) { connection.commit(); } return new CodaResponse(false, "Success!", -1, null); } catch (Exception e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } public CodaResponse createReplaceProcedure(String sessionKey, CodaDatabase database, String command, String applicationName, String procedureName, Vector<ProcedureParameter> parameters, String returnType, boolean returnsArrayFlag, String procedureBody, boolean loadClass) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } CodaConnection connection = database.getConnection(); // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag) { CodaConnection serverConnection = this.database.getConnection(); boolean insertFlag = true, resultSetFlag = false; long procedureId = this.getIdForObjectName(procedureName, CodaServer.OBJECT_TYPE_PROCEDURE, connection); if (procedureId > 0) { if (command.equalsIgnoreCase("create")) { return new CodaResponse(true, null, 2086); } else { insertFlag = false; } } long typeId = -1; if (returnType.equalsIgnoreCase("resultset")) { resultSetFlag = true; } else { typeId = this.getIdForObjectName(serverConnection, returnType.toUpperCase(), CodaServer.OBJECT_TYPE_TYPE); if (typeId < 0) { return new CodaResponse(true, null, 2020); } } // validate parameters Vector<String> parameterNames = new Vector(); for (ProcedureParameter parameter : parameters) { if (parameterNames.contains(parameter.getParameterName())) { return new CodaResponse(true, null, 2087, "Parameter '" + parameter.getParameterName() +"' declared multiple times"); } else { parameterNames.add(parameter.getParameterName()); } if (this.getIdForObjectName(serverConnection, parameter.getParameterType(), CodaServer.OBJECT_TYPE_TYPE) < 0) { return new CodaResponse(true, null, 2020, "Type name '" + parameter.getParameterType() + "' is invalid"); } } String classFile = null; try { classFile = GroovyClassGenerator.getProcedureClass(procedureName, parameters, procedureBody); } catch (Exception e) { return new CodaResponse(true, null, 8005, "There was a problem with your procedure syntax:" +e.getMessage()); } Hashtable values = new Hashtable(); values.put("procedure_name", procedureName.toUpperCase()); values.put("return_resultset_flag", resultSetFlag ? 1 : 0); values.put("return_type_name", returnType.toUpperCase()); values.put("return_array_flag", returnsArrayFlag ? 1 : 0); values.put("class_file", classFile); values.put("procedure_language", "GROOVY"); values.put("procedure_body", procedureBody); values.put("recompile_needed_flag", 0); if (procedureId < 0) { values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); } values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); if (procedureId < 0) { procedureId = connection.insertRow(prefix+"procedures", values); } else { connection.updateRow(prefix+"procedures", "id", procedureId, values); } connection.runStatement("delete from "+prefix+"procedure_parameters where procedure_id = " + connection.formatStringForSQL(prefix+"procedure_parameters", "procedure_id", Long.toString(procedureId))); values = new Hashtable(); values.put("procedure_id", procedureId); int orderNumber = 0; for (ProcedureParameter parameter : parameters) { values.put("parameter_name", parameter.getParameterName().toUpperCase()); values.put("order_number", orderNumber); values.put("type_name", parameter.getParameterType().toUpperCase()); values.put("array_flag", parameter.isArrayFlag() ? 1 : 0); connection.insertRow(prefix+"procedure_parameters", values); orderNumber++; } if (loadClass) { this.deployedApplications.get(applicationName).loadClass(1, "org.codalang.codaserver.language.procedures." + CodaServer.camelCapitalize(procedureName, true),classFile); } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse alterProcedure(String sessionKey, CodaDatabase database, String applicationName, String procedureName, String newProcedureName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } CodaConnection connection = database.getConnection(); // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag) { long procedureId = this.getIdForObjectName(procedureName, CodaServer.OBJECT_TYPE_PROCEDURE, connection); if (procedureId < 0) { return new CodaResponse(true, null, 2088); } if (this.getIdForObjectName(newProcedureName, CodaServer.OBJECT_TYPE_PROCEDURE, connection) > 0) { return new CodaResponse(true, null, 2086); } Hashtable values = new Hashtable(); values.put("procedure_name", newProcedureName.toUpperCase()); values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); connection.updateRow(prefix+"procedures", "id", procedureId, values); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse dropProcedure(String sessionKey, CodaDatabase database, String applicationName, String procedureName) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } CodaConnection connection = database.getConnection(); // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag) { long procedureId = this.getIdForObjectName(procedureName, CodaServer.OBJECT_TYPE_PROCEDURE, connection); if (procedureId < 0) { return new CodaResponse(true, null, 2088); } connection.runStatement("delete from "+prefix+"procedure_parameters where procedure_id = " + connection.formatStringForSQL(prefix+"procedure_parameters", "procedure_id", Long.toString(procedureId))); connection.deleteRow(prefix+"procedures", "id", procedureId); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse createReplaceTrigger(String sessionKey, CodaDatabase database, String command, String applicationName, String tableName, String operation, boolean beforeFlag, String triggerBody, boolean loadClass) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } CodaConnection connection = database.getConnection(); // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag) { boolean insertFlag = true, resultSetFlag = false; boolean formFlag = this.isForm(connection, prefix, tableName); long operationId = -1, formStatusId = -1; // get tableId long tableId = this.getIdForObjectName(tableName, CodaServer.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2028); } // get operation id if (formFlag) { formStatusId = this.getIdForObjectName(tableName + "." + operation, CodaServer.OBJECT_TYPE_FORM_STATUS_VERB, connection); if (formStatusId < 0 && !operation.equalsIgnoreCase("update")) { return new CodaResponse(true, null, 2051); } else if (formStatusId < 0) { operationId = 1; } } else { if (operation.equalsIgnoreCase("update")) { operationId = 1; } else if (operation.equalsIgnoreCase("insert")) { operationId = 2; } else if (operation.equalsIgnoreCase("delete")) { operationId = 3; } else { return new CodaResponse(true, null, 2094); } } long triggerId = this.getIdForObjectName(tableId + "." + operationId + "." + (formFlag ? formStatusId + "." : "") + (beforeFlag ? "1" : "0"), (formFlag ? CodaServer.OBJECT_TYPE_FORM_TRIGGER : CodaServer.OBJECT_TYPE_TABLE_TRIGGER), connection); if (triggerId > 0) { if (command.equalsIgnoreCase("insert")) { return new CodaResponse(true, null, 2086); } else { insertFlag = false; } } String classFile = null; try { classFile = GroovyClassGenerator.getTriggerClass(tableName, operation, (beforeFlag ? "before" : "after"), triggerBody); } catch (Exception e) { return new CodaResponse(true, null, 8006, "There was a problem with your trigger syntax:" +e.getMessage()); } Hashtable values = new Hashtable(); values.put("table_id", tableId); if (formStatusId > 0) { values.put("form_status_id", formStatusId); } if (operationId > 0) { values.put("operation_id", operationId); } values.put("before_flag", beforeFlag ? 1 : 0); values.put("class_file", classFile); values.put("procedure_language", "GROOVY"); values.put("procedure_body", triggerBody); values.put("recompile_needed_flag", 0); if (triggerId < 0) { values.put("create_user_name", sessions.getSessionUsername(sessionKey)); values.put("create_date", new GregorianCalendar().getTimeInMillis()); } values.put("mod_user_name", sessions.getSessionUsername(sessionKey)); values.put("mod_date", new GregorianCalendar().getTimeInMillis()); if (triggerId < 0) { triggerId = connection.insertRow(prefix+"triggers", values); } else { connection.updateRow(prefix+"triggers", "id", triggerId, values); } if (loadClass) { this.deployedApplications.get(applicationName).loadClass(1, "org.codalang.codaserver.language.triggers." + CodaServer.camelCapitalize(tableName, true) + CodaServer.camelCapitalize(beforeFlag ? "before" : "after", true) + CodaServer.camelCapitalize(operation, true),classFile); } connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse dropTrigger(String sessionKey, CodaDatabase database, String applicationName, String tableName, String operation, boolean beforeFlag) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } if (applicationName == null) { if (sessions.getSessionApplication(sessionKey) != null) { applicationName = sessions.getSessionApplication(sessionKey); } else { return new CodaResponse(true, null, 2027); } } if (database == null) { unlinkedDatabaseFlag = false; database = deployedApplications.getDatasource(applicationName, 1).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8002); } } CodaConnection connection = database.getConnection(); // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (deployedApplications.hasApplicationPermission(applicationName, modUserId, -1, -1, "DEVELOPER") || unlinkedDatabaseFlag) { boolean formFlag = this.isForm(connection, prefix, tableName); long operationId = -1, formStatusId = -1; // get tableId long tableId = this.getIdForObjectName(tableName, CodaServer.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2028); } // get operation id if (formFlag) { formStatusId = this.getIdForObjectName(tableName + "." + operation, CodaServer.OBJECT_TYPE_FORM_STATUS_VERB, connection); if (formStatusId < 0 && !operation.equalsIgnoreCase("update")) { return new CodaResponse(true, null, 2051); } else if (formStatusId < 0) { operationId = 1; } } else { if (operation.equalsIgnoreCase("update")) { operationId = 1; } else if (operation.equalsIgnoreCase("insert")) { operationId = 2; } else if (operation.equalsIgnoreCase("delete")) { operationId = 3; } else { return new CodaResponse(true, null, 2094); } } long triggerId = this.getIdForObjectName(tableId + "." + operationId + "." + (formFlag ? formStatusId + "." : "") + (beforeFlag ? "1" : "0"), (formFlag ? CodaServer.OBJECT_TYPE_FORM_TRIGGER : CodaServer.OBJECT_TYPE_TABLE_TRIGGER), connection); if (triggerId < 0) { return new CodaResponse(true, null, 2090); } connection.deleteRow(prefix+"triggers", "id", triggerId); connection.commit(); return new CodaResponse(false, "Success!", -1, null); } else { return new CodaResponse(true, null, 9009); } } public CodaResponse execProcedure(String sessionKey, String procedureName, Vector<String> parameters, CodaConnection procConnection) { boolean unlinkedDatabaseFlag = true; long modUserId = sessions.getSessionUserId(sessionKey); if (modUserId < 0) { return new CodaResponse(true, null, 1005); } int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } String applicationName = sessions.getSessionApplication(sessionKey); CodaConnection connection, serverConnection; CodaDatabase database = deployedApplications.getDatasource(applicationName, environmentId).getDatabase(); if (database == null) { return new CodaResponse(true, null, 8003); } serverConnection = this.database.getConnection(); if (procConnection == null) { connection = database.getConnection(); } else { connection = procConnection; } // get the prefix String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (!deployedApplications.hasProcedurePermission(applicationName, modUserId, -1, environmentId, Datasource.PROCEDURE_EXECUTE, procedureName.toUpperCase())) { return new CodaResponse(true, null, 9011); } long procedureId = this.getIdForObjectName(procedureName, CodaServer.OBJECT_TYPE_PROCEDURE, connection); if (procedureId < 0) { return new CodaResponse(true, null, 2088); } // figure out the return value boolean returnArrayFlag, returnResultSetFlag; long returnTypeId; CodaResultSet returnResult = connection.runQuery("select return_type_name, return_array_flag, return_resultset_flag from "+prefix+"procedures where id = " + connection.formatStringForSQL(prefix+"procedures", "id", Long.toString(procedureId)), null); if (!returnResult.getErrorStatus() && returnResult.next()) { returnTypeId = this.getIdForObjectName(serverConnection, returnResult.getData(0), this.OBJECT_TYPE_TYPE); returnArrayFlag = returnResult.getDataBoolean(1); returnResultSetFlag = returnResult.getDataBoolean(2); } else { return new CodaResponse(true, null, 2088); } // check the inputs ExecutionContext context = new ExecutionContext(this, applicationName, environmentId); Vector<Long> procedureParameterIds = new Vector(); Vector<Long> procedureTypeIds = new Vector(); Vector<Boolean> procedureArrayFlags = new Vector(); Vector<String> parameterNames = new Vector(); CodaResultSet rs = connection.runQuery("select pp.type_name, pp.array_flag, pp.id, pp.parameter_name from "+prefix+"procedure_parameters pp where pp.procedure_id = " + connection.formatStringForSQL(prefix+"procedure_parameters", "procedure_id", Long.toString(procedureId)) + " order by order_number asc",null); if (!rs.getErrorStatus()) { while (rs.next()) { procedureTypeIds.add(this.getIdForObjectName(serverConnection, rs.getData(0), this.OBJECT_TYPE_TYPE)); procedureArrayFlags.add(rs.getData(1).equals("1")); procedureParameterIds.add(rs.getDataLong(2)); parameterNames.add(rs.getData(3)); } } if (procedureTypeIds.size() != parameters.size()) { return new CodaResponse(true, null, 2058); } if (procedureTypeIds.size() > 0) { CodaResponse resp = new CodaResponse(); for(int i = 0; i < procedureTypeIds.size(); i++) { if (procedureArrayFlags.get(i).booleanValue()) { if (TypeParser.isArray(parameters.get(i))) { Vector<String> arrayValues = TypeParser.explodeArray(parameters.get(i)); for (String arrayValue : arrayValues) { if (!context.validate(procedureTypeIds.get(i), arrayValue)){ resp.addError(new CodaError(3001, "Parameter " + (i + 1) + " contains an invalid " + context.getDisplayName(procedureTypeIds.get(i)))); } } } } else { if (!context.validate(procedureTypeIds.get(i), parameters.get(i))){ resp.addError(new CodaError(3001, "Parameter " + (i + 1) + " is not a valid " + context.getDisplayName(procedureTypeIds.get(i)))); } } } if (resp.getError()) { return resp; } } GroovyClassLoader executingClassLoader = context.getClassLoader(); if (executingClassLoader == null) { return new CodaResponse(true, null, 8003); } else { try { Class procedureClass = executingClassLoader.loadClass("org.codalang.codaserver.language.procedures." + CodaServer.camelCapitalize(procedureName, true)); BaseCodaProcedure procedure = (BaseCodaProcedure) procedureClass.newInstance(); // create the parameter hashtable Hashtable parameterHashtable = new Hashtable(); for(int i = 0; i < parameterNames.size(); i++) { if (procedureArrayFlags.get(i).booleanValue()) { parameterHashtable.put(parameterNames.get(i), TypeParser.explodeArray(parameters.get(i))); } else { parameterHashtable.put(parameterNames.get(i), context.parse(procedureTypeIds.get(i), parameters.get(i))); } } Object returnValue = procedure.execute(new Database(this, sessionKey), parameterHashtable); if (returnArrayFlag) { try { Vector returnVector = new Vector(); List list = (List)returnValue; for (Object item : list) { if (returnResultSetFlag) { try { CodaResultSet temp = (CodaResultSet)item; returnVector.add(temp); } catch (ClassCastException e) { return new CodaResponse(true, null, 3003); } } else { try { if (!context.validate(returnTypeId, (String)item)) { return new CodaResponse(true, null, 3004); } else { returnVector.add((String)item); } } catch (ClassCastException e) { return new CodaResponse(true, null, 3004); } } } if (procConnection == null) { connection.commit(); } return new CodaResponse(returnVector); } catch (ClassCastException e) { return new CodaResponse(true, null, 3002); } } else { if (returnResultSetFlag) { try { CodaResultSet temp = (CodaResultSet)returnValue; if (procConnection == null) { connection.commit(); } return new CodaResponse(temp); } catch (ClassCastException e) { return new CodaResponse(true, null, 3003); } } else { try { if (!context.validate(returnTypeId, returnValue.toString())) { return new CodaResponse(true, null, 3004); } else { if (procConnection == null) { connection.commit(); } return new CodaResponse(returnValue.toString()); } } catch (ClassCastException e) { return new CodaResponse(true, null, 3004); } } } } catch (ClassNotFoundException ex) { logger.log(Level.SEVERE, "Classloader could not find 'org.codalang.codaserver.language.procedures." + CodaServer.camelCapitalize(procedureName, true)+"' in application " + applicationName + ":" +environmentId); return new CodaResponse(true, null, 2091); } catch (InstantiationException ex) { logger.log(Level.SEVERE, "Classloader could not find 'org.codalang.codaserver.language.procedures." + CodaServer.camelCapitalize(procedureName, true)+"' in application " + applicationName + ":" +environmentId); return new CodaResponse(true, null, 2091); } catch (IllegalAccessException ex) { logger.log(Level.SEVERE, "Classloader could not find 'org.codalang.codaserver.language.procedures." + CodaServer.camelCapitalize(procedureName, true)+"' in application " + applicationName + ":" +environmentId); return new CodaResponse(true, null, 2091); } catch (CodaException e) { return new CodaResponse(true, null, 4001, e.getMessage()); } } } public CodaResponse show (String sessionKey, String entityType, CodaSearchCondition whereClause, CodaOrderByClause orderByClause, String tableName, String userName, String groupName, String roleName, String applicationName, String environment) { CodaResultSet rs = null; String sql = ""; long groupId = -1, userId = -1, roleId = -1; CodaConnection serverConnection = database.getConnection(); if (groupName != null) { groupId = this.getIdForObjectName(serverConnection, groupName, this.OBJECT_TYPE_GROUP); if (groupId < 0) { return new CodaResponse(true, null, 2017); } } if (userName != null) { userId = this.getIdForObjectName(serverConnection, userName, this.OBJECT_TYPE_USER); if (userId < 0) { return new CodaResponse(true, null, 2015, "Username is invalid"); } } if (entityType.equalsIgnoreCase("users")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("users", "obj")); temp.add(new CodaTableNameAlias("users", "c")); temp.add(new CodaTableNameAlias("users", "m")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.user_name, obj.first_name, obj.middle_name, obj.last_name, obj.organization, obj.address, obj.city, obj.state_prov, obj.postal_code, obj.country, obj.phone, obj.alt_phone, obj.email, obj.robot_flag, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name from users obj inner join users c on c.id = obj.create_user_id inner join users m on m.id = obj.mod_user_id "; if (!sessions.hasServerPermission(sessionKey, "MANAGE_USERS") && !sessions.hasServerPermission(sessionKey, "MANAGE_USER_DATA") && !sessions.hasServerPermission(sessionKey, "MANAGE_GROUPS") && !sessions.hasServerPermission(sessionKey, "MANAGE_APPLICATIONS")) { applicationName = sessions.getSessionApplication(sessionKey); environment = sessions.getSessionEnvironment(sessionKey); if (environment == null) { return new CodaResponse(true, null, 9003); } } if (environment != null) { - sql += " inner join user_application_permissions uap on uap.user_id = obj.id and uap.application_permission_name = 'CONNECT' and uap.environment = "+ serverConnection.formatStringForSQL("user_application_permissions", "environment", Integer.toString(this.getIdForEnvironmentName(environment))) +" "+(groupId > 0 ? " and aup.group_id = " + serverConnection.formatStringForSQL("user_application_permissions", "group_id", Long.toString(groupId)) + " " : "")+" inner join applications a on uap.application_id = a.id and a.application_name = " + serverConnection.formatStringForSQL("applications", "application_name", applicationName.toUpperCase()) + " "; + sql += " inner join user_application_permissions uap on uap.user_id = obj.id and uap.application_permission_name = 'CONNECT' and (uap.environment = "+ serverConnection.formatStringForSQL("user_application_permissions", "environment", Integer.toString(this.getIdForEnvironmentName(environment))) +" OR uap.environment IS NULL) "+(groupId > 0 ? " and aup.group_id = " + serverConnection.formatStringForSQL("user_application_permissions", "group_id", Long.toString(groupId)) + " " : "")+" inner join applications a on uap.application_id = a.id and a.application_name = " + serverConnection.formatStringForSQL("applications", "application_name", applicationName.toUpperCase()) + " "; } if (environment == null && groupId > 0) { sql += " inner join user_groups g on obj.id = g.user_id and g.group_id = " + serverConnection.formatStringForSQL("user_groups", "id", Long.toString(groupId)) + " "; } sql += " where obj.active_flag = 1 " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("groups")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("groups", "obj")); temp.add(new CodaTableNameAlias("users", "c")); temp.add(new CodaTableNameAlias("users", "m")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.group_name, obj.display_name, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name from groups obj inner join users c on c.id = obj.create_user_id inner join users m on m.id = obj.mod_user_id "; if (!sessions.hasServerPermission(sessionKey, "MANAGE_GROUPS")) { applicationName = sessions.getSessionApplication(sessionKey); environment = sessions.getSessionEnvironment(sessionKey); if (environment == null) { return new CodaResponse(true, null, 1006); } } if (environment != null) { sql += " inner join group_applications ga on ga.group_id = obj.id inner join applications a on a.id = ga.application_id and a.application_name = " + serverConnection.formatStringForSQL("applications", "application_name", applicationName)+" "; } if (userName != null) { sql += " inner join user_groups ug on ug.group_id = obj.id inner join users u on u.id = ug.user_id and u.user_name = " + serverConnection.formatStringForSQL("users", "user_name", userName)+" "; } sql += " where obj.active_flag = 1 " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("types")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("types", "obj")); temp.add(new CodaTableNameAlias("users", "c")); temp.add(new CodaTableNameAlias("users", "m")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.type_name, obj.built_in_flag, obj.validation_mask, obj.save_mask, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name from types obj left outer join users c on c.id = obj.create_user_id left outer join users m on m.id = obj.mod_user_id "; sql += " where obj.active_flag = 1 " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("datasources")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("datasources", "obj")); temp.add(new CodaTableNameAlias("users", "c")); temp.add(new CodaTableNameAlias("users", "m")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.datasource_name, obj.display_name, obj.driver_name, obj.host_name, obj.schema_name, obj.user_name, obj.pass_word, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name from datasources obj inner join users c on c.id = obj.create_user_id inner join users m on m.id = obj.mod_user_id "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("sessions")) { if (!sessions.hasServerPermission(sessionKey, "MANAGE_SESSIONS")) { return new CodaResponse(true, null, 9016); } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("sessions", "obj")); temp.add(new CodaTableNameAlias("users", "c")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.session_key, u.user_name, obj.application_name, obj.group_name, obj.environment, obj.session_timestamp from sessions obj inner join users u on u.id = obj.user_id "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.id asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("applications")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("applications", "obj")); temp.add(new CodaTableNameAlias("datasources", "dev")); temp.add(new CodaTableNameAlias("datasources", "test")); temp.add(new CodaTableNameAlias("datasources", "prod")); temp.add(new CodaTableNameAlias("users", "c")); temp.add(new CodaTableNameAlias("users", "m")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.application_name, obj.display_name, obj.group_flag, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name, dev.datasource_name, test.datasource_name, prod.datasource_name from applications obj inner join users c on c.id = obj.create_user_id inner join users m on m.id = obj.mod_user_id left outer join datasources dev on dev.id = obj.dev_datasource_id left outer join datasources test on test.id = obj.test_datasource_id left outer join datasources prod on prod.id = obj.prod_datasource_id "; if (groupId > 0) { sql += " inner join group_applications g on obj.id = g.application_id and g.group_id = " + serverConnection.formatStringForSQL("user_groups", "id", Long.toString(groupId)) + " "; } sql += " where obj.active_flag = 1 " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("server")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("user_system_permissions", "obj")); temp.add(new CodaTableNameAlias("users", "u")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select u.user_name, obj.server_permission_name from user_server_permissions obj inner join users u on u.id = obj.user_id and u.id = "+ serverConnection.formatStringForSQL("users", "id", Long.toString(userId)) + " "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by u.user_name asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("application")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("user_application_permissions", "obj")); temp.add(new CodaTableNameAlias("applications", "a")); temp.add(new CodaTableNameAlias("groups", "g")); temp.add(new CodaTableNameAlias("users", "u")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select u.user_name, g.group_name, a.application_name, obj.environment, obj.application_permission_name from user_application_permissions obj inner join users u on u.id = obj.user_id " + ( userId > 0 ? " and u.id = "+ serverConnection.formatStringForSQL("users", "id", Long.toString(userId)) : "") +" inner join applications a on a.id = obj.application_id and a.active_flag = 1 left outer join groups g on g.id = obj.group_id " + (groupId > 0 ? " and g.id = " + serverConnection.formatStringForSQL("groups", "id", Long.toString(groupId)) : ""); sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by u.user_name asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("sys")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("coda_system_information", "obj")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.* from coda_system_information obj "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " " : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("app")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("coda_system_information", "obj")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.* from coda_system_information obj "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? "" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("tables")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"tables", "obj")); temp.add(new CodaTableNameAlias(prefix +"tables", "p")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.table_name, obj.display_name, obj.group_flag, obj.soft_delete_flag, obj.ref_table_flag, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date, p.table_name as parent_table_name from "+prefix+"tables obj left outer join "+prefix+"tables p on p.id = obj.parent_table_id "; sql += " where obj.form_flag = 0 " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("forms")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"tables", "obj")); temp.add(new CodaTableNameAlias(prefix +"tables", "p")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.table_name as form_name, obj.display_name, obj.group_flag, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date, p.table_name as parent_form_name from "+prefix+"tables obj left outer join "+prefix+"tables p on p.id = obj.parent_table_id "; sql += " where obj.form_flag = 1 " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("procedures")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"procedures", "obj")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.procedure_name, obj.return_resultset_flag, obj.return_array_flag, obj.return_type_name, obj.procedure_body, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"procedures obj "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("triggers")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"triggers", "obj")); temp.add(new CodaTableNameAlias(prefix +"tables", "p")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } long tableId = this.getIdForObjectName(tableName, this.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2028); } boolean formFlag = this.isForm(connection, prefix, tableName); if (!formFlag) { sql = "select p.table_name, obj.operation_id, obj.before_flag, obj.procedure_body as trigger_body, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"triggers obj inner join "+prefix+"tables p on p.id = obj.table_id "; } else { sql = "select p.table_name as form_name, obj.operation_id, fs.verb_status_name, obj.before_flag, obj.procedure_body, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"tables obj inner join "+prefix+"tables p on p.id = obj.table_id left outer join "+prefix+"form_statuses fs on fs.id = obj.form_status_id "; } sql += " where obj.table_id = "+connection.formatStringForSQL(prefix+"triggers", "table_id", Long.toString(tableId))+" " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("indexes")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"indexes", "obj")); temp.add(new CodaTableNameAlias(prefix +"tables", "p")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.index_name, p.table_name, obj.index_type_id, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"indexes obj left outer join "+prefix+"tables p on p.id = obj.table_id "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("crons")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"crons", "obj")); temp.add(new CodaTableNameAlias(prefix +"procedures", "p")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.cron_name, obj.minute_part, obj.hour_part, obj.day_of_month_part, obj.month_part, obj.day_of_week_part, p.procedure_name, obj.executing_user_name, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"crons obj left outer join "+prefix+"procedures p on p.id = obj.procedure_id "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("roles")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"roles", "obj")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.role_name, obj.display_name, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"roles obj "; if (userId > 0) { sql += " inner join "+prefix+"user_roles r on obj.id = r.role_id and r.user_id = " + connection.formatStringForSQL(prefix+"user_roles", "user_id", Long.toString(userId)) + " " + (groupId > 0 ?"and r.group_id = " + connection.formatStringForSQL(prefix+"user_roles", "group_id", Long.toString(groupId)) + " " : ""); } sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("permissions")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"permissions", "obj")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } if (roleName != null) { roleId = this.getIdForObjectName(roleName, this.OBJECT_TYPE_ROLE, connection); } sql = "select obj.permission_name, obj.display_name, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"permissions obj "; if (userId > 0) { sql += " inner join "+prefix+"role_permissions p on obj.id = p.permission_id inner join "+prefix+"user_roles r on p.role_id = r.role_id and r.user_id = " + connection.formatStringForSQL(prefix+"user_roles", "user_id", Long.toString(userId)) + " " + (groupId > 0 ?"and r.group_id = " + connection.formatStringForSQL(prefix+"user_roles", "group_id", Long.toString(groupId)) + " " : ""); } else if (roleId > 0) { sql += " inner join "+prefix+"role_permissions r on obj.id = r.permission_id and r.role_id = " + connection.formatStringForSQL(prefix+"role_permissions", "role_id", Long.toString(roleId)) + " "; } sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("table")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (tableName != null && this.isForm(connection, prefix, tableName)) { return new CodaResponse(true, null, 2092); } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"role_tables", "obj")); temp.add(new CodaTableNameAlias(prefix +"roles", "r")); temp.add(new CodaTableNameAlias(prefix +"tables", "t")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } if (roleName != null) { roleId = this.getIdForObjectName(roleName, this.OBJECT_TYPE_ROLE, connection); if (roleId == -1) { return new CodaResponse(true, null, 2029); } } sql = "select r.role_name, t.table_name, obj.select_flag, obj.insert_flag, obj.update_flag, obj.delete_flag from "+prefix+"role_tables obj inner join "+prefix+"roles r on r.id = obj.role_id " + (roleId > 0 ? "and r.id = " + connection.formatStringForSQL(prefix + "roles", "id", Long.toString(roleId)) : "") + " inner join "+prefix+"tables t on t.id = obj.table_id and t.form_flag = 0 "; if (userId > 0) { sql += " inner join "+prefix+"user_roles u on r.id = u.role_id and u.user_id = " + connection.formatStringForSQL(prefix+"user_roles", "user_id", Long.toString(userId)) + " " + (groupId > 0 ?"and u.group_id = " + connection.formatStringForSQL(prefix+"user_roles", "group_id", Long.toString(groupId)) + " " : ""); } sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by r.role_name asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("form")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (tableName != null && !this.isForm(connection, prefix, tableName)) { return new CodaResponse(true, null, 2092); } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"role_form_statuses", "obj")); temp.add(new CodaTableNameAlias(prefix +"roles", "r")); temp.add(new CodaTableNameAlias(prefix +"tables", "f")); temp.add(new CodaTableNameAlias(prefix +"form_statuses", "s")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } if (roleName != null) { roleId = this.getIdForObjectName(roleName, this.OBJECT_TYPE_ROLE, connection); if (roleId == -1) { return new CodaResponse(true, null, 2029); } } sql = "select r.role_name, f.table_name as form_name, s.adj_status_name, s.verb_status_name, obj.view_flag, obj.call_flag, obj.update_flag from "+prefix+"role_form_statuses obj inner join "+prefix+"form_statuses s on s.id = obj.form_status_id inner join "+prefix+"roles r on r.id = obj.role_id " + (roleId > 0 ? "and r.id = " + connection.formatStringForSQL(prefix + "roles", "id", Long.toString(roleId)) : "") + " inner join "+prefix+"tables f on f.id = s.table_id and f.form_flag = 1 "; if (userId > 0) { sql += " inner join "+prefix+"user_roles u on r.id = u.role_id and u.user_id = " + connection.formatStringForSQL(prefix+"user_roles", "user_id", Long.toString(userId)) + " " + (groupId > 0 ?"and u.group_id = " + connection.formatStringForSQL(prefix+"user_roles", "group_id", Long.toString(groupId)) + " " : ""); } sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by r.role_name asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("procedure")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"role_procedures", "obj")); temp.add(new CodaTableNameAlias(prefix +"roles", "r")); temp.add(new CodaTableNameAlias(prefix +"procedures", "p")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } if (roleName != null) { roleId = this.getIdForObjectName(roleName, this.OBJECT_TYPE_ROLE, connection); if (roleId == -1) { return new CodaResponse(true, null, 2029); } } sql = "select r.role_name, p.procedure_name, obj.execute_flag from "+prefix+"role_procedures obj inner join "+prefix+"roles r on r.id = obj.role_id " + (roleId > 0 ? "and r.id = " + connection.formatStringForSQL(prefix + "roles", "id", Long.toString(roleId)) : "") + " inner join "+prefix+"procedures p on p.id = obj.procedure_id "; if (userId > 0) { sql += " inner join "+prefix+"user_roles u on r.id = u.role_id and u.user_id = " + connection.formatStringForSQL(prefix+"user_roles", "user_id", Long.toString(userId)) + " " + (groupId > 0 ?"and u.group_id = " + connection.formatStringForSQL(prefix+"user_roles", "group_id", Long.toString(groupId)) + " " : ""); } sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by r.role_name asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } return new CodaResponse(rs); } public CodaResponse describe (String sessionKey, String entityType, String entityName, String specifier, boolean beforeFlag, String operation) { CodaResultSet rs = null; String sql = ""; String applicationName = null; String environment = null; long groupId = -1; if (entityType.equalsIgnoreCase("user")) { CodaConnection connection = database.getConnection(); sql = "select obj.user_name, obj.first_name, obj.middle_name, obj.last_name, obj.organization, obj.address, obj.city, obj.state_prov, obj.postal_code, obj.country, obj.phone, obj.alt_phone, obj.email, obj.robot_flag, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name from users obj inner join users c on c.id = obj.create_user_id inner join users m on m.id = obj.mod_user_id "; if (!sessions.hasServerPermission(sessionKey, "MANAGE_USERS") && !sessions.hasServerPermission(sessionKey, "MANAGE_USER_DATA") && !sessions.hasServerPermission(sessionKey, "MANAGE_GROUPS") && !sessions.hasServerPermission(sessionKey, "MANAGE_APPLICATIONS")) { applicationName = sessions.getSessionApplication(sessionKey); groupId = sessions.getSessionGroupId(sessionKey); environment = sessions.getSessionEnvironment(sessionKey); if (environment == null) { return new CodaResponse(true, null, 1006); } } if (environment != null) { sql += " inner join user_application_permissions uap on uap.user_id = obj.id and uap.application_permission_name = 'CONNECT' and ( uap.environment = "+ connection.formatStringForSQL("user_application_permissions", "environment", Integer.toString(this.getIdForEnvironmentName(environment))) +" OR uap.environment IS NULL) "+(groupId > 0 ? " and aup.group_id = " + connection.formatStringForSQL("user_application_permissions", "group_id", Long.toString(groupId)) + " " : "")+" inner join applications a on uap.application_id = a.id and a.application_name = " + connection.formatStringForSQL("applications", "application_name", applicationName.toUpperCase()) + " "; } sql += " where obj.active_flag = 1 and obj.user_name = " + connection.formatStringForSQL("users", "user_name", entityName.toUpperCase()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("group")) { CodaConnection connection = database.getConnection(); sql = "select obj.group_name, obj.display_name, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name from groups obj inner join users c on c.id = obj.create_user_id inner join users m on m.id = obj.mod_user_id "; sql += " where obj.active_flag = 1 and obj.group_name = " + connection.formatStringForSQL("groups", "group_name", entityName.toUpperCase()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("type")) { CodaConnection connection = database.getConnection(); sql = "select obj.type_name, obj.built_in_flag, obj.validation_mask, obj.save_mask, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name from types obj inner join users c on c.id = obj.create_user_id inner join users m on m.id = obj.mod_user_id "; sql += " where obj.active_flag = 1 and obj.type_name = " + connection.formatStringForSQL("types", "type_name", entityName.toUpperCase()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("datasource")) { CodaConnection connection = database.getConnection(); sql = "select obj.datasource_name, obj.display_name, obj.driver_name, obj.host_name, obj.schema_name, obj.user_name, obj.pass_word, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name from datasources obj inner join users c on c.id = obj.create_user_id inner join users m on m.id = obj.mod_user_id "; sql += " where obj.datasource_name = " + connection.formatStringForSQL("datasources", "datasource_name", entityName.toUpperCase()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("application")) { CodaConnection connection = database.getConnection(); sql = "select obj.application_name, obj.display_name, obj.group_flag, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name, dev.datasource_name, test.datasource_name, prod.datasource_name from applications obj inner join users c on c.id = obj.create_user_id inner join users m on m.id = obj.mod_user_id left outer join datasources dev on dev.id = obj.dev_datasource_id left outer join datasources test on test.id = obj.test_datasource_id left outer join datasources prod on prod.id = obj.prod_datasource_id "; sql += " where obj.active_flag = 1 and obj.application_name = " + connection.formatStringForSQL("applications", "application_name", entityName.toUpperCase()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("table")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (this.isForm(connection, prefix, entityName)) { return new CodaResponse(true, null, 2039); } if (specifier != null && specifier.equalsIgnoreCase("columns")) { sql = "select obj.field_name as column_name, obj.display_name, obj.type_name, obj.array_flag, obj.nullable_flag, r.table_name as ref_table_name, obj.default_variable_id, obj.default_value, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"table_fields obj inner join "+prefix+"tables t on t.id = obj.table_id left outer join " +prefix +"tables r on obj.ref_table_id = r.id "; sql += " where t.table_name = " + connection.formatStringForSQL(prefix+"tables", "table_name", entityName.toUpperCase()); } else { sql = "select obj.table_name, obj.display_name, obj.group_flag, obj.soft_delete_flag, obj.ref_table_flag, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date, p.table_name as parent_table_name from "+prefix+"tables obj left outer join "+prefix+"tables p on p.id = obj.parent_table_id "; sql += " where obj.table_name = " + connection.formatStringForSQL(prefix+"tables", "table_name", entityName.toUpperCase()); } rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("form")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (!this.isForm(connection, prefix, entityName)) { return new CodaResponse(true, null, 2092); } if (specifier != null && specifier.equalsIgnoreCase("fields")) { sql = "select obj.field_name, obj.display_name, obj.type_name, obj.array_flag, r.table_name as ref_table_name, obj.default_variable_id, obj.default_value, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"table_fields obj inner join "+prefix+"tables t on t.id = obj.table_id left outer join " +prefix +"tables r on obj.ref_table_id = r.id "; sql += " where t.table_name = " + connection.formatStringForSQL(prefix+"tables", "table_name", entityName.toUpperCase()); } else if (specifier != null && specifier.equalsIgnoreCase("statuses")) { sql = "select obj.id, obj.adj_status_name, obj.adj_display_name, obj.verb_status_name, obj.verb_display_name, obj.initial_flag, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date, t.table_name as parent_table_name from "+prefix+"form_statuses obj inner join "+prefix+"tables t on t.id = obj.table_id "; sql += " where t.table_name = " + connection.formatStringForSQL(prefix+"tables", "table_name", entityName.toUpperCase()); } else if (specifier != null && specifier.equalsIgnoreCase("status")) { sql = "select orig.id as orig_id, orig.adj_status_name as orig_adj_status_name, orig.verb_status_name as orig_verb_status_name, next.id as next_id, next.adj_status_name as next_adj_status_name, next.verb_status_name as next_verb_status_name, obj.create_user_name, obj.create_date from "+prefix+"form_status_relationships obj inner join "+prefix+"form_statuses orig on orig.id = obj.form_status_id inner join "+prefix+"tables t on t.id = orig.table_id inner join " +prefix +"form_statuses next on obj.next_form_status_id = next.id "; sql += " where t.table_name = " + connection.formatStringForSQL(prefix+"tables", "table_name", entityName.toUpperCase()); } else { sql = "select obj.table_name as form_name, obj.display_name, obj.group_flag, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date, p.table_name as parent_form_name from "+prefix+"tables obj left outer join "+prefix+"tables p on p.id = obj.parent_table_id "; sql += " where obj.table_name = " + connection.formatStringForSQL(prefix+"tables", "table_name", entityName.toUpperCase()); } rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("procedure")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (specifier != null && specifier.equalsIgnoreCase("parameters")) { sql = "select obj.parameter_name, obj.type_name, obj.array_flag from " +prefix+"procedure_parameters obj inner join " +prefix + "procedures p on p.id = obj.procedure_id "; sql += " where p.procedure_name = " + connection.formatStringForSQL(prefix+"procedures", "procedure_name", entityName.toUpperCase()) + "order by obj.order_number asc"; } else { sql = "select obj.procedure_name, obj.return_resultset_flag, obj.return_array_flag, obj.return_type_name, obj.procedure_body, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"procedures obj "; sql += " where obj.procedure_name = " + connection.formatStringForSQL(prefix+"procedures", "procedure_name", entityName.toUpperCase()); } rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("trigger")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } long tableId = this.getIdForObjectName(entityName, this.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2028); } boolean formFlag = this.isForm(connection, prefix, entityName); long formStatusId = -1; if (specifier != null) { formStatusId = this.getIdForObjectName(Long.toString(tableId) + "." + specifier.toUpperCase(), CodaServer.OBJECT_TYPE_FORM_STATUS_VERB, connection); if (formStatusId < 0) { return new CodaResponse(true, null, 2093); } } if (!formFlag) { sql = "select p.table_name, obj.operation_id, obj.before_flag, obj.procedure_body as trigger_body, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"triggers obj inner join "+prefix+"tables p on p.id = obj.table_id "; } else { sql = "select p.table_name as form_name, obj.operation_id, fs.verb_status_name, obj.before_flag, obj.procedure_body, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"tables obj inner join "+prefix+"tables p on p.id = obj.table_id left outer join "+prefix+"form_statuses fs on fs.id = obj.form_status_id "; } sql += " where obj.table_id = "+connection.formatStringForSQL(prefix+"triggers", "table_id", Long.toString(tableId))+ " and obj.before_flag = " +connection.formatStringForSQL(prefix+"triggers", "before_flag", beforeFlag ? "1" : "0") + " and " + (!formFlag ? " obj.operation_id = " + connection.formatStringForSQL(prefix+"triggers", "operation_id", Integer.toString(getIdForDatabaseOperation(operation))) : (specifier.equalsIgnoreCase("update") ? " obj.operation_id = " + connection.formatStringForSQL(prefix+"triggers", "operation_id", Integer.toString(getIdForDatabaseOperation(operation))) : " obj.form_status_id = " + connection.formatStringForSQL(prefix+"triggers", "form_status_id", Long.toString(formStatusId)) )) ; rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("index")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (specifier != null && specifier.equalsIgnoreCase("columns")) { sql = "select f.field_name, f.display_name, f.type_name, f.array_flag from " +prefix+"index_fields obj inner join " +prefix + "indexes i on i.id = obj.index_id inner join "+ prefix + "table_fields f on f.id = obj.table_field_id "; sql += " where i.index_name = " + connection.formatStringForSQL(prefix+"indexes", "index_name", entityName.toUpperCase()); } else { sql = "select obj.index_name, t.table_name, obj.index_type_id, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"indexes obj left outer join "+prefix+"tables t on t.id = obj.table_id "; sql += " where obj.index_name = " + connection.formatStringForSQL(prefix+"indexes", "index_name", entityName.toUpperCase()); } rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("cron")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (specifier != null && specifier.equalsIgnoreCase("parameters")) { sql = "select p.parameter_name, p.type_name, p.array_flag, obj.parameter_value from " +prefix+"cron_parameters obj inner join " +prefix + "crons c on c.id = obj.cron_id inner join " +prefix+"procedure_parameters p on p.id = obj.procedure_parameter_id "; sql += " where c.cron_name = " + connection.formatStringForSQL(prefix+"crons", "cron_name", entityName.toUpperCase()) + "order by obj.id asc"; } else { sql = "select obj.cron_name, obj.minute_part, obj.hour_part, obj.day_of_month_part, obj.month_part, obj.day_of_week_part, p.procedure_name, obj.executing_user_name, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"crons obj left outer join "+prefix+"procedures p on p.id = obj.procedure_id "; sql += " where obj.cron_name = " + connection.formatStringForSQL(prefix+"crons", "cron_name", entityName.toUpperCase()); } rs = connection.runQuery(sql, null); } return new CodaResponse(rs); } }
true
true
public CodaResponse show (String sessionKey, String entityType, CodaSearchCondition whereClause, CodaOrderByClause orderByClause, String tableName, String userName, String groupName, String roleName, String applicationName, String environment) { CodaResultSet rs = null; String sql = ""; long groupId = -1, userId = -1, roleId = -1; CodaConnection serverConnection = database.getConnection(); if (groupName != null) { groupId = this.getIdForObjectName(serverConnection, groupName, this.OBJECT_TYPE_GROUP); if (groupId < 0) { return new CodaResponse(true, null, 2017); } } if (userName != null) { userId = this.getIdForObjectName(serverConnection, userName, this.OBJECT_TYPE_USER); if (userId < 0) { return new CodaResponse(true, null, 2015, "Username is invalid"); } } if (entityType.equalsIgnoreCase("users")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("users", "obj")); temp.add(new CodaTableNameAlias("users", "c")); temp.add(new CodaTableNameAlias("users", "m")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.user_name, obj.first_name, obj.middle_name, obj.last_name, obj.organization, obj.address, obj.city, obj.state_prov, obj.postal_code, obj.country, obj.phone, obj.alt_phone, obj.email, obj.robot_flag, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name from users obj inner join users c on c.id = obj.create_user_id inner join users m on m.id = obj.mod_user_id "; if (!sessions.hasServerPermission(sessionKey, "MANAGE_USERS") && !sessions.hasServerPermission(sessionKey, "MANAGE_USER_DATA") && !sessions.hasServerPermission(sessionKey, "MANAGE_GROUPS") && !sessions.hasServerPermission(sessionKey, "MANAGE_APPLICATIONS")) { applicationName = sessions.getSessionApplication(sessionKey); environment = sessions.getSessionEnvironment(sessionKey); if (environment == null) { return new CodaResponse(true, null, 9003); } } if (environment != null) { sql += " inner join user_application_permissions uap on uap.user_id = obj.id and uap.application_permission_name = 'CONNECT' and uap.environment = "+ serverConnection.formatStringForSQL("user_application_permissions", "environment", Integer.toString(this.getIdForEnvironmentName(environment))) +" "+(groupId > 0 ? " and aup.group_id = " + serverConnection.formatStringForSQL("user_application_permissions", "group_id", Long.toString(groupId)) + " " : "")+" inner join applications a on uap.application_id = a.id and a.application_name = " + serverConnection.formatStringForSQL("applications", "application_name", applicationName.toUpperCase()) + " "; } if (environment == null && groupId > 0) { sql += " inner join user_groups g on obj.id = g.user_id and g.group_id = " + serverConnection.formatStringForSQL("user_groups", "id", Long.toString(groupId)) + " "; } sql += " where obj.active_flag = 1 " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("groups")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("groups", "obj")); temp.add(new CodaTableNameAlias("users", "c")); temp.add(new CodaTableNameAlias("users", "m")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.group_name, obj.display_name, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name from groups obj inner join users c on c.id = obj.create_user_id inner join users m on m.id = obj.mod_user_id "; if (!sessions.hasServerPermission(sessionKey, "MANAGE_GROUPS")) { applicationName = sessions.getSessionApplication(sessionKey); environment = sessions.getSessionEnvironment(sessionKey); if (environment == null) { return new CodaResponse(true, null, 1006); } } if (environment != null) { sql += " inner join group_applications ga on ga.group_id = obj.id inner join applications a on a.id = ga.application_id and a.application_name = " + serverConnection.formatStringForSQL("applications", "application_name", applicationName)+" "; } if (userName != null) { sql += " inner join user_groups ug on ug.group_id = obj.id inner join users u on u.id = ug.user_id and u.user_name = " + serverConnection.formatStringForSQL("users", "user_name", userName)+" "; } sql += " where obj.active_flag = 1 " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("types")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("types", "obj")); temp.add(new CodaTableNameAlias("users", "c")); temp.add(new CodaTableNameAlias("users", "m")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.type_name, obj.built_in_flag, obj.validation_mask, obj.save_mask, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name from types obj left outer join users c on c.id = obj.create_user_id left outer join users m on m.id = obj.mod_user_id "; sql += " where obj.active_flag = 1 " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("datasources")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("datasources", "obj")); temp.add(new CodaTableNameAlias("users", "c")); temp.add(new CodaTableNameAlias("users", "m")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.datasource_name, obj.display_name, obj.driver_name, obj.host_name, obj.schema_name, obj.user_name, obj.pass_word, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name from datasources obj inner join users c on c.id = obj.create_user_id inner join users m on m.id = obj.mod_user_id "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("sessions")) { if (!sessions.hasServerPermission(sessionKey, "MANAGE_SESSIONS")) { return new CodaResponse(true, null, 9016); } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("sessions", "obj")); temp.add(new CodaTableNameAlias("users", "c")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.session_key, u.user_name, obj.application_name, obj.group_name, obj.environment, obj.session_timestamp from sessions obj inner join users u on u.id = obj.user_id "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.id asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("applications")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("applications", "obj")); temp.add(new CodaTableNameAlias("datasources", "dev")); temp.add(new CodaTableNameAlias("datasources", "test")); temp.add(new CodaTableNameAlias("datasources", "prod")); temp.add(new CodaTableNameAlias("users", "c")); temp.add(new CodaTableNameAlias("users", "m")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.application_name, obj.display_name, obj.group_flag, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name, dev.datasource_name, test.datasource_name, prod.datasource_name from applications obj inner join users c on c.id = obj.create_user_id inner join users m on m.id = obj.mod_user_id left outer join datasources dev on dev.id = obj.dev_datasource_id left outer join datasources test on test.id = obj.test_datasource_id left outer join datasources prod on prod.id = obj.prod_datasource_id "; if (groupId > 0) { sql += " inner join group_applications g on obj.id = g.application_id and g.group_id = " + serverConnection.formatStringForSQL("user_groups", "id", Long.toString(groupId)) + " "; } sql += " where obj.active_flag = 1 " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("server")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("user_system_permissions", "obj")); temp.add(new CodaTableNameAlias("users", "u")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select u.user_name, obj.server_permission_name from user_server_permissions obj inner join users u on u.id = obj.user_id and u.id = "+ serverConnection.formatStringForSQL("users", "id", Long.toString(userId)) + " "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by u.user_name asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("application")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("user_application_permissions", "obj")); temp.add(new CodaTableNameAlias("applications", "a")); temp.add(new CodaTableNameAlias("groups", "g")); temp.add(new CodaTableNameAlias("users", "u")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select u.user_name, g.group_name, a.application_name, obj.environment, obj.application_permission_name from user_application_permissions obj inner join users u on u.id = obj.user_id " + ( userId > 0 ? " and u.id = "+ serverConnection.formatStringForSQL("users", "id", Long.toString(userId)) : "") +" inner join applications a on a.id = obj.application_id and a.active_flag = 1 left outer join groups g on g.id = obj.group_id " + (groupId > 0 ? " and g.id = " + serverConnection.formatStringForSQL("groups", "id", Long.toString(groupId)) : ""); sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by u.user_name asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("sys")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("coda_system_information", "obj")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.* from coda_system_information obj "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " " : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("app")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("coda_system_information", "obj")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.* from coda_system_information obj "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? "" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("tables")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"tables", "obj")); temp.add(new CodaTableNameAlias(prefix +"tables", "p")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.table_name, obj.display_name, obj.group_flag, obj.soft_delete_flag, obj.ref_table_flag, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date, p.table_name as parent_table_name from "+prefix+"tables obj left outer join "+prefix+"tables p on p.id = obj.parent_table_id "; sql += " where obj.form_flag = 0 " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("forms")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"tables", "obj")); temp.add(new CodaTableNameAlias(prefix +"tables", "p")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.table_name as form_name, obj.display_name, obj.group_flag, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date, p.table_name as parent_form_name from "+prefix+"tables obj left outer join "+prefix+"tables p on p.id = obj.parent_table_id "; sql += " where obj.form_flag = 1 " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("procedures")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"procedures", "obj")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.procedure_name, obj.return_resultset_flag, obj.return_array_flag, obj.return_type_name, obj.procedure_body, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"procedures obj "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("triggers")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"triggers", "obj")); temp.add(new CodaTableNameAlias(prefix +"tables", "p")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } long tableId = this.getIdForObjectName(tableName, this.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2028); } boolean formFlag = this.isForm(connection, prefix, tableName); if (!formFlag) { sql = "select p.table_name, obj.operation_id, obj.before_flag, obj.procedure_body as trigger_body, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"triggers obj inner join "+prefix+"tables p on p.id = obj.table_id "; } else { sql = "select p.table_name as form_name, obj.operation_id, fs.verb_status_name, obj.before_flag, obj.procedure_body, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"tables obj inner join "+prefix+"tables p on p.id = obj.table_id left outer join "+prefix+"form_statuses fs on fs.id = obj.form_status_id "; } sql += " where obj.table_id = "+connection.formatStringForSQL(prefix+"triggers", "table_id", Long.toString(tableId))+" " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("indexes")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"indexes", "obj")); temp.add(new CodaTableNameAlias(prefix +"tables", "p")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.index_name, p.table_name, obj.index_type_id, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"indexes obj left outer join "+prefix+"tables p on p.id = obj.table_id "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("crons")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"crons", "obj")); temp.add(new CodaTableNameAlias(prefix +"procedures", "p")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.cron_name, obj.minute_part, obj.hour_part, obj.day_of_month_part, obj.month_part, obj.day_of_week_part, p.procedure_name, obj.executing_user_name, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"crons obj left outer join "+prefix+"procedures p on p.id = obj.procedure_id "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("roles")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"roles", "obj")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.role_name, obj.display_name, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"roles obj "; if (userId > 0) { sql += " inner join "+prefix+"user_roles r on obj.id = r.role_id and r.user_id = " + connection.formatStringForSQL(prefix+"user_roles", "user_id", Long.toString(userId)) + " " + (groupId > 0 ?"and r.group_id = " + connection.formatStringForSQL(prefix+"user_roles", "group_id", Long.toString(groupId)) + " " : ""); } sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("permissions")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"permissions", "obj")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } if (roleName != null) { roleId = this.getIdForObjectName(roleName, this.OBJECT_TYPE_ROLE, connection); } sql = "select obj.permission_name, obj.display_name, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"permissions obj "; if (userId > 0) { sql += " inner join "+prefix+"role_permissions p on obj.id = p.permission_id inner join "+prefix+"user_roles r on p.role_id = r.role_id and r.user_id = " + connection.formatStringForSQL(prefix+"user_roles", "user_id", Long.toString(userId)) + " " + (groupId > 0 ?"and r.group_id = " + connection.formatStringForSQL(prefix+"user_roles", "group_id", Long.toString(groupId)) + " " : ""); } else if (roleId > 0) { sql += " inner join "+prefix+"role_permissions r on obj.id = r.permission_id and r.role_id = " + connection.formatStringForSQL(prefix+"role_permissions", "role_id", Long.toString(roleId)) + " "; } sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("table")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (tableName != null && this.isForm(connection, prefix, tableName)) { return new CodaResponse(true, null, 2092); } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"role_tables", "obj")); temp.add(new CodaTableNameAlias(prefix +"roles", "r")); temp.add(new CodaTableNameAlias(prefix +"tables", "t")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } if (roleName != null) { roleId = this.getIdForObjectName(roleName, this.OBJECT_TYPE_ROLE, connection); if (roleId == -1) { return new CodaResponse(true, null, 2029); } } sql = "select r.role_name, t.table_name, obj.select_flag, obj.insert_flag, obj.update_flag, obj.delete_flag from "+prefix+"role_tables obj inner join "+prefix+"roles r on r.id = obj.role_id " + (roleId > 0 ? "and r.id = " + connection.formatStringForSQL(prefix + "roles", "id", Long.toString(roleId)) : "") + " inner join "+prefix+"tables t on t.id = obj.table_id and t.form_flag = 0 "; if (userId > 0) { sql += " inner join "+prefix+"user_roles u on r.id = u.role_id and u.user_id = " + connection.formatStringForSQL(prefix+"user_roles", "user_id", Long.toString(userId)) + " " + (groupId > 0 ?"and u.group_id = " + connection.formatStringForSQL(prefix+"user_roles", "group_id", Long.toString(groupId)) + " " : ""); } sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by r.role_name asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("form")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (tableName != null && !this.isForm(connection, prefix, tableName)) { return new CodaResponse(true, null, 2092); } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"role_form_statuses", "obj")); temp.add(new CodaTableNameAlias(prefix +"roles", "r")); temp.add(new CodaTableNameAlias(prefix +"tables", "f")); temp.add(new CodaTableNameAlias(prefix +"form_statuses", "s")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } if (roleName != null) { roleId = this.getIdForObjectName(roleName, this.OBJECT_TYPE_ROLE, connection); if (roleId == -1) { return new CodaResponse(true, null, 2029); } } sql = "select r.role_name, f.table_name as form_name, s.adj_status_name, s.verb_status_name, obj.view_flag, obj.call_flag, obj.update_flag from "+prefix+"role_form_statuses obj inner join "+prefix+"form_statuses s on s.id = obj.form_status_id inner join "+prefix+"roles r on r.id = obj.role_id " + (roleId > 0 ? "and r.id = " + connection.formatStringForSQL(prefix + "roles", "id", Long.toString(roleId)) : "") + " inner join "+prefix+"tables f on f.id = s.table_id and f.form_flag = 1 "; if (userId > 0) { sql += " inner join "+prefix+"user_roles u on r.id = u.role_id and u.user_id = " + connection.formatStringForSQL(prefix+"user_roles", "user_id", Long.toString(userId)) + " " + (groupId > 0 ?"and u.group_id = " + connection.formatStringForSQL(prefix+"user_roles", "group_id", Long.toString(groupId)) + " " : ""); } sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by r.role_name asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("procedure")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"role_procedures", "obj")); temp.add(new CodaTableNameAlias(prefix +"roles", "r")); temp.add(new CodaTableNameAlias(prefix +"procedures", "p")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } if (roleName != null) { roleId = this.getIdForObjectName(roleName, this.OBJECT_TYPE_ROLE, connection); if (roleId == -1) { return new CodaResponse(true, null, 2029); } } sql = "select r.role_name, p.procedure_name, obj.execute_flag from "+prefix+"role_procedures obj inner join "+prefix+"roles r on r.id = obj.role_id " + (roleId > 0 ? "and r.id = " + connection.formatStringForSQL(prefix + "roles", "id", Long.toString(roleId)) : "") + " inner join "+prefix+"procedures p on p.id = obj.procedure_id "; if (userId > 0) { sql += " inner join "+prefix+"user_roles u on r.id = u.role_id and u.user_id = " + connection.formatStringForSQL(prefix+"user_roles", "user_id", Long.toString(userId)) + " " + (groupId > 0 ?"and u.group_id = " + connection.formatStringForSQL(prefix+"user_roles", "group_id", Long.toString(groupId)) + " " : ""); } sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by r.role_name asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } return new CodaResponse(rs); }
public CodaResponse show (String sessionKey, String entityType, CodaSearchCondition whereClause, CodaOrderByClause orderByClause, String tableName, String userName, String groupName, String roleName, String applicationName, String environment) { CodaResultSet rs = null; String sql = ""; long groupId = -1, userId = -1, roleId = -1; CodaConnection serverConnection = database.getConnection(); if (groupName != null) { groupId = this.getIdForObjectName(serverConnection, groupName, this.OBJECT_TYPE_GROUP); if (groupId < 0) { return new CodaResponse(true, null, 2017); } } if (userName != null) { userId = this.getIdForObjectName(serverConnection, userName, this.OBJECT_TYPE_USER); if (userId < 0) { return new CodaResponse(true, null, 2015, "Username is invalid"); } } if (entityType.equalsIgnoreCase("users")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("users", "obj")); temp.add(new CodaTableNameAlias("users", "c")); temp.add(new CodaTableNameAlias("users", "m")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.user_name, obj.first_name, obj.middle_name, obj.last_name, obj.organization, obj.address, obj.city, obj.state_prov, obj.postal_code, obj.country, obj.phone, obj.alt_phone, obj.email, obj.robot_flag, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name from users obj inner join users c on c.id = obj.create_user_id inner join users m on m.id = obj.mod_user_id "; if (!sessions.hasServerPermission(sessionKey, "MANAGE_USERS") && !sessions.hasServerPermission(sessionKey, "MANAGE_USER_DATA") && !sessions.hasServerPermission(sessionKey, "MANAGE_GROUPS") && !sessions.hasServerPermission(sessionKey, "MANAGE_APPLICATIONS")) { applicationName = sessions.getSessionApplication(sessionKey); environment = sessions.getSessionEnvironment(sessionKey); if (environment == null) { return new CodaResponse(true, null, 9003); } } if (environment != null) { sql += " inner join user_application_permissions uap on uap.user_id = obj.id and uap.application_permission_name = 'CONNECT' and (uap.environment = "+ serverConnection.formatStringForSQL("user_application_permissions", "environment", Integer.toString(this.getIdForEnvironmentName(environment))) +" OR uap.environment IS NULL) "+(groupId > 0 ? " and aup.group_id = " + serverConnection.formatStringForSQL("user_application_permissions", "group_id", Long.toString(groupId)) + " " : "")+" inner join applications a on uap.application_id = a.id and a.application_name = " + serverConnection.formatStringForSQL("applications", "application_name", applicationName.toUpperCase()) + " "; } if (environment == null && groupId > 0) { sql += " inner join user_groups g on obj.id = g.user_id and g.group_id = " + serverConnection.formatStringForSQL("user_groups", "id", Long.toString(groupId)) + " "; } sql += " where obj.active_flag = 1 " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("groups")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("groups", "obj")); temp.add(new CodaTableNameAlias("users", "c")); temp.add(new CodaTableNameAlias("users", "m")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.group_name, obj.display_name, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name from groups obj inner join users c on c.id = obj.create_user_id inner join users m on m.id = obj.mod_user_id "; if (!sessions.hasServerPermission(sessionKey, "MANAGE_GROUPS")) { applicationName = sessions.getSessionApplication(sessionKey); environment = sessions.getSessionEnvironment(sessionKey); if (environment == null) { return new CodaResponse(true, null, 1006); } } if (environment != null) { sql += " inner join group_applications ga on ga.group_id = obj.id inner join applications a on a.id = ga.application_id and a.application_name = " + serverConnection.formatStringForSQL("applications", "application_name", applicationName)+" "; } if (userName != null) { sql += " inner join user_groups ug on ug.group_id = obj.id inner join users u on u.id = ug.user_id and u.user_name = " + serverConnection.formatStringForSQL("users", "user_name", userName)+" "; } sql += " where obj.active_flag = 1 " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("types")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("types", "obj")); temp.add(new CodaTableNameAlias("users", "c")); temp.add(new CodaTableNameAlias("users", "m")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.type_name, obj.built_in_flag, obj.validation_mask, obj.save_mask, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name from types obj left outer join users c on c.id = obj.create_user_id left outer join users m on m.id = obj.mod_user_id "; sql += " where obj.active_flag = 1 " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("datasources")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("datasources", "obj")); temp.add(new CodaTableNameAlias("users", "c")); temp.add(new CodaTableNameAlias("users", "m")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.datasource_name, obj.display_name, obj.driver_name, obj.host_name, obj.schema_name, obj.user_name, obj.pass_word, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name from datasources obj inner join users c on c.id = obj.create_user_id inner join users m on m.id = obj.mod_user_id "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("sessions")) { if (!sessions.hasServerPermission(sessionKey, "MANAGE_SESSIONS")) { return new CodaResponse(true, null, 9016); } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("sessions", "obj")); temp.add(new CodaTableNameAlias("users", "c")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.session_key, u.user_name, obj.application_name, obj.group_name, obj.environment, obj.session_timestamp from sessions obj inner join users u on u.id = obj.user_id "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.id asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("applications")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("applications", "obj")); temp.add(new CodaTableNameAlias("datasources", "dev")); temp.add(new CodaTableNameAlias("datasources", "test")); temp.add(new CodaTableNameAlias("datasources", "prod")); temp.add(new CodaTableNameAlias("users", "c")); temp.add(new CodaTableNameAlias("users", "m")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.application_name, obj.display_name, obj.group_flag, obj.create_date, obj.mod_date, c.user_name as create_user_name, m.user_name as mod_user_name, dev.datasource_name, test.datasource_name, prod.datasource_name from applications obj inner join users c on c.id = obj.create_user_id inner join users m on m.id = obj.mod_user_id left outer join datasources dev on dev.id = obj.dev_datasource_id left outer join datasources test on test.id = obj.test_datasource_id left outer join datasources prod on prod.id = obj.prod_datasource_id "; if (groupId > 0) { sql += " inner join group_applications g on obj.id = g.application_id and g.group_id = " + serverConnection.formatStringForSQL("user_groups", "id", Long.toString(groupId)) + " "; } sql += " where obj.active_flag = 1 " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("server")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("user_system_permissions", "obj")); temp.add(new CodaTableNameAlias("users", "u")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select u.user_name, obj.server_permission_name from user_server_permissions obj inner join users u on u.id = obj.user_id and u.id = "+ serverConnection.formatStringForSQL("users", "id", Long.toString(userId)) + " "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by u.user_name asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("application")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("user_application_permissions", "obj")); temp.add(new CodaTableNameAlias("applications", "a")); temp.add(new CodaTableNameAlias("groups", "g")); temp.add(new CodaTableNameAlias("users", "u")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select u.user_name, g.group_name, a.application_name, obj.environment, obj.application_permission_name from user_application_permissions obj inner join users u on u.id = obj.user_id " + ( userId > 0 ? " and u.id = "+ serverConnection.formatStringForSQL("users", "id", Long.toString(userId)) : "") +" inner join applications a on a.id = obj.application_id and a.active_flag = 1 left outer join groups g on g.id = obj.group_id " + (groupId > 0 ? " and g.id = " + serverConnection.formatStringForSQL("groups", "id", Long.toString(groupId)) : ""); sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by u.user_name asc" : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("sys")) { String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("coda_system_information", "obj")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.* from coda_system_information obj "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " " : orderByClause.toString()); rs = serverConnection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("app")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias("coda_system_information", "obj")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.* from coda_system_information obj "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? "" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("tables")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"tables", "obj")); temp.add(new CodaTableNameAlias(prefix +"tables", "p")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.table_name, obj.display_name, obj.group_flag, obj.soft_delete_flag, obj.ref_table_flag, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date, p.table_name as parent_table_name from "+prefix+"tables obj left outer join "+prefix+"tables p on p.id = obj.parent_table_id "; sql += " where obj.form_flag = 0 " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("forms")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"tables", "obj")); temp.add(new CodaTableNameAlias(prefix +"tables", "p")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.table_name as form_name, obj.display_name, obj.group_flag, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date, p.table_name as parent_form_name from "+prefix+"tables obj left outer join "+prefix+"tables p on p.id = obj.parent_table_id "; sql += " where obj.form_flag = 1 " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("procedures")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"procedures", "obj")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.procedure_name, obj.return_resultset_flag, obj.return_array_flag, obj.return_type_name, obj.procedure_body, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"procedures obj "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("triggers")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"triggers", "obj")); temp.add(new CodaTableNameAlias(prefix +"tables", "p")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } long tableId = this.getIdForObjectName(tableName, this.OBJECT_TYPE_TABLE, connection); if (tableId < 0) { return new CodaResponse(true, null, 2028); } boolean formFlag = this.isForm(connection, prefix, tableName); if (!formFlag) { sql = "select p.table_name, obj.operation_id, obj.before_flag, obj.procedure_body as trigger_body, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"triggers obj inner join "+prefix+"tables p on p.id = obj.table_id "; } else { sql = "select p.table_name as form_name, obj.operation_id, fs.verb_status_name, obj.before_flag, obj.procedure_body, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"tables obj inner join "+prefix+"tables p on p.id = obj.table_id left outer join "+prefix+"form_statuses fs on fs.id = obj.form_status_id "; } sql += " where obj.table_id = "+connection.formatStringForSQL(prefix+"triggers", "table_id", Long.toString(tableId))+" " + (whereClauseString != null ? " and " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("indexes")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"indexes", "obj")); temp.add(new CodaTableNameAlias(prefix +"tables", "p")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.index_name, p.table_name, obj.index_type_id, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"indexes obj left outer join "+prefix+"tables p on p.id = obj.table_id "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("crons")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"crons", "obj")); temp.add(new CodaTableNameAlias(prefix +"procedures", "p")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.cron_name, obj.minute_part, obj.hour_part, obj.day_of_month_part, obj.month_part, obj.day_of_week_part, p.procedure_name, obj.executing_user_name, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"crons obj left outer join "+prefix+"procedures p on p.id = obj.procedure_id "; sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("roles")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"roles", "obj")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } sql = "select obj.role_name, obj.display_name, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"roles obj "; if (userId > 0) { sql += " inner join "+prefix+"user_roles r on obj.id = r.role_id and r.user_id = " + connection.formatStringForSQL(prefix+"user_roles", "user_id", Long.toString(userId)) + " " + (groupId > 0 ?"and r.group_id = " + connection.formatStringForSQL(prefix+"user_roles", "group_id", Long.toString(groupId)) + " " : ""); } sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("permissions")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"permissions", "obj")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } if (roleName != null) { roleId = this.getIdForObjectName(roleName, this.OBJECT_TYPE_ROLE, connection); } sql = "select obj.permission_name, obj.display_name, obj.create_user_name, obj.create_date, obj.mod_user_name, obj.mod_date from "+prefix+"permissions obj "; if (userId > 0) { sql += " inner join "+prefix+"role_permissions p on obj.id = p.permission_id inner join "+prefix+"user_roles r on p.role_id = r.role_id and r.user_id = " + connection.formatStringForSQL(prefix+"user_roles", "user_id", Long.toString(userId)) + " " + (groupId > 0 ?"and r.group_id = " + connection.formatStringForSQL(prefix+"user_roles", "group_id", Long.toString(groupId)) + " " : ""); } else if (roleId > 0) { sql += " inner join "+prefix+"role_permissions r on obj.id = r.permission_id and r.role_id = " + connection.formatStringForSQL(prefix+"role_permissions", "role_id", Long.toString(roleId)) + " "; } sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by obj.create_date asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("table")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (tableName != null && this.isForm(connection, prefix, tableName)) { return new CodaResponse(true, null, 2092); } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"role_tables", "obj")); temp.add(new CodaTableNameAlias(prefix +"roles", "r")); temp.add(new CodaTableNameAlias(prefix +"tables", "t")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } if (roleName != null) { roleId = this.getIdForObjectName(roleName, this.OBJECT_TYPE_ROLE, connection); if (roleId == -1) { return new CodaResponse(true, null, 2029); } } sql = "select r.role_name, t.table_name, obj.select_flag, obj.insert_flag, obj.update_flag, obj.delete_flag from "+prefix+"role_tables obj inner join "+prefix+"roles r on r.id = obj.role_id " + (roleId > 0 ? "and r.id = " + connection.formatStringForSQL(prefix + "roles", "id", Long.toString(roleId)) : "") + " inner join "+prefix+"tables t on t.id = obj.table_id and t.form_flag = 0 "; if (userId > 0) { sql += " inner join "+prefix+"user_roles u on r.id = u.role_id and u.user_id = " + connection.formatStringForSQL(prefix+"user_roles", "user_id", Long.toString(userId)) + " " + (groupId > 0 ?"and u.group_id = " + connection.formatStringForSQL(prefix+"user_roles", "group_id", Long.toString(groupId)) + " " : ""); } sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by r.role_name asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("form")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } if (tableName != null && !this.isForm(connection, prefix, tableName)) { return new CodaResponse(true, null, 2092); } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"role_form_statuses", "obj")); temp.add(new CodaTableNameAlias(prefix +"roles", "r")); temp.add(new CodaTableNameAlias(prefix +"tables", "f")); temp.add(new CodaTableNameAlias(prefix +"form_statuses", "s")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } if (roleName != null) { roleId = this.getIdForObjectName(roleName, this.OBJECT_TYPE_ROLE, connection); if (roleId == -1) { return new CodaResponse(true, null, 2029); } } sql = "select r.role_name, f.table_name as form_name, s.adj_status_name, s.verb_status_name, obj.view_flag, obj.call_flag, obj.update_flag from "+prefix+"role_form_statuses obj inner join "+prefix+"form_statuses s on s.id = obj.form_status_id inner join "+prefix+"roles r on r.id = obj.role_id " + (roleId > 0 ? "and r.id = " + connection.formatStringForSQL(prefix + "roles", "id", Long.toString(roleId)) : "") + " inner join "+prefix+"tables f on f.id = s.table_id and f.form_flag = 1 "; if (userId > 0) { sql += " inner join "+prefix+"user_roles u on r.id = u.role_id and u.user_id = " + connection.formatStringForSQL(prefix+"user_roles", "user_id", Long.toString(userId)) + " " + (groupId > 0 ?"and u.group_id = " + connection.formatStringForSQL(prefix+"user_roles", "group_id", Long.toString(groupId)) + " " : ""); } sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by r.role_name asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } else if (entityType.equalsIgnoreCase("procedure")) { int environmentId = sessions.getSessionEnvironmentId(sessionKey); if (environmentId <= 0) { return new CodaResponse(true, null, 1006); } applicationName = sessions.getSessionApplication(sessionKey); CodaDatabase database = applicationName != null && deployedApplications.getDatasource(applicationName, environmentId) != null ? deployedApplications.getDatasource(applicationName, environmentId).getDatabase() : null; if (database == null) { return new CodaResponse(true, null, 8003); } CodaConnection connection = database.getConnection(); String prefix = connection.getMetadata().getSystemTable().getPrefixString(); if (prefix == null) { prefix = ""; } String whereClauseString = null; if (whereClause != null) { try { Vector<CodaTableNameAlias> temp = new Vector(); temp.add(new CodaTableNameAlias(prefix +"role_procedures", "obj")); temp.add(new CodaTableNameAlias(prefix +"roles", "r")); temp.add(new CodaTableNameAlias(prefix +"procedures", "p")); CodaFromClause fromClause = new CodaFromClause(temp, new Vector()); fromClause.setColumns(this, database); whereClauseString = whereClause.print(fromClause); } catch (CodaException e) { return new CodaResponse(true, null, 8004, e.getMessage()); } } if (roleName != null) { roleId = this.getIdForObjectName(roleName, this.OBJECT_TYPE_ROLE, connection); if (roleId == -1) { return new CodaResponse(true, null, 2029); } } sql = "select r.role_name, p.procedure_name, obj.execute_flag from "+prefix+"role_procedures obj inner join "+prefix+"roles r on r.id = obj.role_id " + (roleId > 0 ? "and r.id = " + connection.formatStringForSQL(prefix + "roles", "id", Long.toString(roleId)) : "") + " inner join "+prefix+"procedures p on p.id = obj.procedure_id "; if (userId > 0) { sql += " inner join "+prefix+"user_roles u on r.id = u.role_id and u.user_id = " + connection.formatStringForSQL(prefix+"user_roles", "user_id", Long.toString(userId)) + " " + (groupId > 0 ?"and u.group_id = " + connection.formatStringForSQL(prefix+"user_roles", "group_id", Long.toString(groupId)) + " " : ""); } sql += (whereClauseString != null ? " where " + whereClauseString : "") + (orderByClause == null ? " order by r.role_name asc" : orderByClause.toString()); rs = connection.runQuery(sql, null); } return new CodaResponse(rs); }
diff --git a/jkit/java/stages/TypeChecking.java b/jkit/java/stages/TypeChecking.java index 852f506..b9f329c 100644 --- a/jkit/java/stages/TypeChecking.java +++ b/jkit/java/stages/TypeChecking.java @@ -1,794 +1,797 @@ package jkit.java.stages; import java.util.*; import static jkit.compiler.SyntaxError.*; import static jkit.jil.util.Types.*; import jkit.compiler.ClassLoader; import jkit.compiler.Clazz; import jkit.java.io.JavaFile; import jkit.java.tree.Decl; import jkit.java.tree.Expr; import jkit.java.tree.Stmt; import jkit.java.tree.Value; import jkit.java.tree.Decl.*; import jkit.java.tree.Expr.*; import jkit.java.tree.Stmt.*; import jkit.jil.tree.SourceLocation; import jkit.jil.tree.Type; import jkit.jil.util.Types; import jkit.util.Triple; /** * The purpose of this class is to type check the statements and expressions * within a Java File. The process of propogating type information (i.e. the * Typing stage) is separated from the process of checking those types. This is * for two reasons: firstly, it divides the problem into two (simpler) * subproblems; secondly, it provides for different ways of propagating type * information (e.e.g type inference). * * @author djp * */ public class TypeChecking { private ClassLoader loader; private Stack<Decl> enclosingScopes = new Stack<Decl>(); private TypeSystem types; public TypeChecking(ClassLoader loader, TypeSystem types) { this.loader = loader; this.types = types; } public void apply(JavaFile file) { for(Decl d : file.declarations()) { checkDeclaration(d); } } protected void checkDeclaration(Decl d) { if(d instanceof JavaInterface) { checkInterface((JavaInterface)d); } else if(d instanceof JavaClass) { checkClass((JavaClass)d); } else if(d instanceof JavaMethod) { checkMethod((JavaMethod)d); } else if(d instanceof JavaField) { checkField((JavaField)d); } } protected void checkInterface(JavaInterface c) { enclosingScopes.push(c); for(Decl d : c.declarations()) { checkDeclaration(d); } enclosingScopes.pop(); } protected void checkClass(JavaClass c) { enclosingScopes.push(c); for(Decl d : c.declarations()) { checkDeclaration(d); } enclosingScopes.pop(); } protected void checkMethod(JavaMethod d) { enclosingScopes.push(d); checkStatement(d.body()); enclosingScopes.pop(); } protected void checkField(JavaField d) { checkExpression(d.initialiser()); Type lhs_t = (Type) d.type().attribute(Type.class); if(d.initialiser() != null) { Type rhs_t = (Type) d.initialiser().attribute(Type.class); try { if (!types.subtype(lhs_t, rhs_t, loader)) { syntax_error( "required type " + lhs_t + ", found type " + rhs_t, d); } } catch (ClassNotFoundException ex) { syntax_error(ex.getMessage(), d); } } } protected void checkStatement(Stmt e) { if(e instanceof Stmt.SynchronisedBlock) { checkSynchronisedBlock((Stmt.SynchronisedBlock)e); } else if(e instanceof Stmt.TryCatchBlock) { checkTryCatchBlock((Stmt.TryCatchBlock)e); } else if(e instanceof Stmt.Block) { checkBlock((Stmt.Block)e); } else if(e instanceof Stmt.VarDef) { checkVarDef((Stmt.VarDef) e); } else if(e instanceof Stmt.AssignmentOp) { checkAssignmentOp((Stmt.AssignmentOp) e); } else if(e instanceof Stmt.Assignment) { checkAssignment((Stmt.Assignment) e); } else if(e instanceof Stmt.Return) { checkReturn((Stmt.Return) e); } else if(e instanceof Stmt.Throw) { checkThrow((Stmt.Throw) e); } else if(e instanceof Stmt.Assert) { checkAssert((Stmt.Assert) e); } else if(e instanceof Stmt.Break) { checkBreak((Stmt.Break) e); } else if(e instanceof Stmt.Continue) { checkContinue((Stmt.Continue) e); } else if(e instanceof Stmt.Label) { checkLabel((Stmt.Label) e); } else if(e instanceof Stmt.If) { checkIf((Stmt.If) e); } else if(e instanceof Stmt.For) { checkFor((Stmt.For) e); } else if(e instanceof Stmt.ForEach) { checkForEach((Stmt.ForEach) e); } else if(e instanceof Stmt.While) { checkWhile((Stmt.While) e); } else if(e instanceof Stmt.DoWhile) { checkDoWhile((Stmt.DoWhile) e); } else if(e instanceof Stmt.Switch) { checkSwitch((Stmt.Switch) e); } else if(e instanceof Expr.Invoke) { checkInvoke((Expr.Invoke) e); } else if(e instanceof Expr.New) { checkNew((Expr.New) e); } else if(e instanceof Decl.JavaClass) { checkClass((Decl.JavaClass)e); } else if(e instanceof Stmt.PrePostIncDec) { checkExpression((Stmt.PrePostIncDec)e); } else if(e != null) { throw new RuntimeException("Invalid statement encountered: " + e.getClass()); } } protected void checkBlock(Stmt.Block block) { if(block != null) { for(Stmt s : block.statements()) { checkStatement(s); } } } protected void checkSynchronisedBlock(Stmt.SynchronisedBlock block) { checkExpression(block.expr()); checkBlock(block); Type e_t = (Type) block.expr().attribute(Type.class); if (!(e_t instanceof Type.Reference)) { syntax_error("required reference type, found type " + e_t, block); } } protected void checkTryCatchBlock(Stmt.TryCatchBlock block) { checkBlock(block); checkBlock(block.finaly()); for(Stmt.CatchBlock cb : block.handlers()) { checkBlock(cb); try { if (!types.subtype(Types.JAVA_LANG_THROWABLE, (Type.Clazz) cb.type().attribute(Type.class), loader)) { syntax_error( "required subtype of java.lang.Throwable, found type " + cb.type(), cb); } } catch (ClassNotFoundException ex) { syntax_error(ex.getMessage(), block); } } } protected void checkVarDef(Stmt.VarDef def) { // Observe that we cannot use the declared type here, rather we have to // use the resolved type! Type t = (Type) def.type().attribute(Type.class); for(Triple<String, Integer, Expr> d : def.definitions()) { if(d.third() != null) { checkExpression(d.third()); Type nt = t; for(int i=0;i!=d.second();++i) { nt = new Type.Array(nt); } Type i_t = (Type) d.third().attribute(Type.class); try { if (!types.subtype(nt, i_t, loader)) { syntax_error("required type " + nt + ", found type " + i_t, def); } } catch (ClassNotFoundException ex) { syntax_error(ex.getMessage(), def); } } } } protected void checkAssignment(Stmt.Assignment def) { checkExpression(def.lhs()); checkExpression(def.rhs()); Type lhs_t = (Type) def.lhs().attribute(Type.class); Type rhs_t = (Type) def.rhs().attribute(Type.class); try { if (!types.subtype(lhs_t, rhs_t, loader)) { syntax_error( "required type " + lhs_t + ", found type " + rhs_t, def); } } catch (ClassNotFoundException ex) { syntax_error(ex.getMessage(), def); } } protected void checkAssignmentOp(Stmt.AssignmentOp def) { checkExpression(def.lhs()); checkExpression(def.rhs()); Type lhs_t = (Type) def.lhs().attribute(Type.class); Type rhs_t = (Type) def.rhs().attribute(Type.class); try { if(def.op() == Expr.BinOp.CONCAT) { // special case. if (!types.subtype(Types.JAVA_LANG_STRING,lhs_t, loader)) { syntax_error( "required type string, found type " + lhs_t, def); } } else if (!types.subtype(lhs_t, rhs_t, loader)) { syntax_error( "required type " + lhs_t + ", found type " + rhs_t, def); } } catch (ClassNotFoundException ex) { syntax_error(ex.getMessage(), def); } } protected void checkReturn(Stmt.Return ret) { JavaMethod method = (JavaMethod) getEnclosingScope(JavaMethod.class); Type retType = (Type) method.returnType().attribute(Type.class); if(ret.expr() != null) { checkExpression(ret.expr()); Type ret_t = (Type) ret.expr().attribute(Type.class); try { if(ret_t.equals(new Type.Void())) { syntax_error( "cannot return a value from method whose result type is void", ret); } else if (!types.subtype(retType, ret_t, loader)) { syntax_error("required return type " + method.returnType() + ", found type " + ret_t, ret); } } catch (ClassNotFoundException ex) { syntax_error(ex.getMessage(), ret); } } else if(!(retType instanceof Type.Void)) { syntax_error("missing return value", ret); } } protected void checkThrow(Stmt.Throw ret) { checkExpression(ret.expr()); } protected void checkAssert(Stmt.Assert ret) { checkExpression(ret.expr()); } protected void checkBreak(Stmt.Break brk) { // could check break label exists (if there is one) } protected void checkContinue(Stmt.Continue brk) { // could check continue label exists (if there is one) } protected void checkLabel(Stmt.Label lab) { // do nothing } protected void checkIf(Stmt.If stmt) { checkExpression(stmt.condition()); checkStatement(stmt.trueStatement()); checkStatement(stmt.falseStatement()); if(stmt.condition() != null) { Type c_t = (Type) stmt.condition().attribute(Type.class); if(!(c_t instanceof Type.Bool)) { syntax_error("required type boolean, found " + c_t, stmt); } } } protected void checkWhile(Stmt.While stmt) { checkExpression(stmt.condition()); checkStatement(stmt.body()); if(stmt.condition() != null) { Type c_t = (Type) stmt.condition().attribute(Type.class); if (!(c_t instanceof Type.Bool)) { syntax_error("required type boolean, found " + c_t, stmt); } } } protected void checkDoWhile(Stmt.DoWhile stmt) { checkExpression(stmt.condition()); checkStatement(stmt.body()); if(stmt.condition() != null) { Type c_t = (Type) stmt.condition().attribute(Type.class); if (!(c_t instanceof Type.Bool)) { syntax_error("required type boolean, found " + c_t, stmt); } } } protected void checkFor(Stmt.For stmt) { checkStatement(stmt.initialiser()); checkExpression(stmt.condition()); checkStatement(stmt.increment()); checkStatement(stmt.body()); if(stmt.condition() != null) { Type c_t = (Type) stmt.condition().attribute(Type.class); if (!(c_t instanceof Type.Bool)) { syntax_error("required type boolean, found " + c_t, stmt); } } } protected void checkForEach(Stmt.ForEach stmt) { checkExpression(stmt.source()); checkStatement(stmt.body()); // need to check that the static type of the source expression // implements java.lang.iterable Type s_t = (Type) stmt.source().attribute(Type.class); try { if (!(s_t instanceof Type.Array) && !types.subtype(new Type.Clazz("java.lang", "Iterable"), s_t, loader)) { syntax_error("foreach not applicable to expression type", stmt); } } catch (ClassNotFoundException ex) { syntax_error(ex.getMessage(), stmt); } } protected void checkSwitch(Stmt.Switch sw) { checkExpression(sw.condition()); Type condT = (Type) sw.condition().attribute(Type.class); if(!(condT instanceof Type.Int)) { syntax_error("found type " + condT + ", required int",sw); } for(Case c : sw.cases()) { checkExpression(c.condition()); for(Stmt s : c.statements()) { checkStatement(s); } } } protected void checkExpression(Expr e) { if(e instanceof Value.Bool) { checkBoolVal((Value.Bool)e); } else if(e instanceof Value.Byte) { checkByteVal((Value.Byte)e); } else if(e instanceof Value.Char) { checkCharVal((Value.Char)e); } else if(e instanceof Value.Int) { checkIntVal((Value.Int)e); } else if(e instanceof Value.Short) { checkShortVal((Value.Short)e); } else if(e instanceof Value.Long) { checkLongVal((Value.Long)e); } else if(e instanceof Value.Float) { checkFloatVal((Value.Float)e); } else if(e instanceof Value.Double) { checkDoubleVal((Value.Double)e); } else if(e instanceof Value.String) { checkStringVal((Value.String)e); } else if(e instanceof Value.Null) { checkNullVal((Value.Null)e); } else if(e instanceof Value.TypedArray) { checkTypedArrayVal((Value.TypedArray)e); } else if(e instanceof Value.Array) { checkArrayVal((Value.Array)e); } else if(e instanceof Value.Class) { checkClassVal((Value.Class) e); } else if(e instanceof Expr.LocalVariable) { checkLocalVariable((Expr.LocalVariable)e); } else if(e instanceof Expr.NonLocalVariable) { checkNonLocalVariable((Expr.NonLocalVariable)e); } else if(e instanceof Expr.ClassVariable) { checkClassVariable((Expr.ClassVariable)e); } else if(e instanceof Expr.UnOp) { checkUnOp((Expr.UnOp)e); } else if(e instanceof Expr.BinOp) { checkBinOp((Expr.BinOp)e); } else if(e instanceof Expr.TernOp) { checkTernOp((Expr.TernOp)e); } else if(e instanceof Expr.Cast) { checkCast((Expr.Cast)e); } else if(e instanceof Expr.Convert) { checkConvert((Expr.Convert)e); } else if(e instanceof Expr.InstanceOf) { checkInstanceOf((Expr.InstanceOf)e); } else if(e instanceof Expr.Invoke) { checkInvoke((Expr.Invoke) e); } else if(e instanceof Expr.New) { checkNew((Expr.New) e); } else if(e instanceof Expr.ArrayIndex) { checkArrayIndex((Expr.ArrayIndex) e); } else if(e instanceof Expr.Deref) { checkDeref((Expr.Deref) e); } else if(e instanceof Stmt.Assignment) { checkAssignment((Stmt.Assignment) e); } else if(e != null) { throw new RuntimeException("Invalid expression encountered: " + e.getClass()); } } protected void checkDeref(Expr.Deref e) { checkExpression(e.target()); // here, we need to check that the field in question actually exists! } protected void checkArrayIndex(Expr.ArrayIndex e) { checkExpression(e.index()); checkExpression(e.target()); Type i_t = (Type) e.index().attribute(Type.class); if(!(i_t instanceof Type.Int)) { syntax_error("required type int, found type " + i_t, e); } Type t_t = (Type) e.target().attribute(Type.class); if(!(t_t instanceof Type.Array)) { syntax_error("array required, but " + t_t + " found", e); } } protected void checkNew(Expr.New e) { checkExpression(e.context()); for(Decl d : e.declarations()) { checkDeclaration(d); } } protected void checkInvoke(Expr.Invoke e) { for(Expr p : e.parameters()) { checkExpression(p); } } protected void checkInstanceOf(Expr.InstanceOf e) { checkExpression(e.lhs()); Type lhs_t = (Type) e.lhs().attribute(Type.class); Type rhs_t = (Type) e.rhs().attribute(Type.class); try { if(lhs_t instanceof Type.Primitive) { syntax_error("required reference type, found " + lhs_t , e); } else if(!(rhs_t instanceof Type.Reference)) { syntax_error("required class or array type, found " + rhs_t , e); } else if((lhs_t instanceof Type.Array || rhs_t instanceof Type.Array) && !(types.subtype(lhs_t,rhs_t,loader))) { syntax_error("inconvertible types: " + lhs_t + ", " + rhs_t, e); } } catch(ClassNotFoundException cne) { syntax_error("type error",e,cne); } } protected void checkCast(Expr.Cast e) { Type e_t = (Type) e.expr().attribute(Type.class); Type c_t = (Type) e.type().attribute(Type.class); try { if(e_t instanceof Type.Clazz && c_t instanceof Type.Clazz) { Clazz c_c = loader.loadClass((Type.Clazz) c_t); Clazz e_c = loader.loadClass((Type.Clazz) e_t); // the trick here, is that javac will never reject a cast // between an interface and a class or interface. However, if we // have a cast from one class to another class, then it will // reject this if neither is a subclass of the other. if(c_c.isInterface() || e_c.isInterface()) { // cast cannot fail here. return; } } if (types.boxSubtype(c_t, e_t, loader) || types.boxSubtype(e_t, c_t, loader)) { // this is OK return; } else if (c_t instanceof Type.Primitive && e_t instanceof Type.Primitive) { if (e_t instanceof Type.Char && (c_t instanceof Type.Byte || c_t instanceof Type.Short)) { return; } else if (c_t instanceof Type.Char && (e_t instanceof Type.Byte || e_t instanceof Type.Short)) { return; } } syntax_error("inconvertible types: " + e_t + ", " + c_t, e); } catch(ClassNotFoundException ex) { syntax_error (ex.getMessage(),e); } } protected void checkConvert(Expr.Convert e) { Type rhs_t = (Type) e.expr().attribute(Type.class); Type c_t = (Type) e.type().attribute(Type.class); SourceLocation loc = (SourceLocation) e.attribute(SourceLocation.class); try { if(!types.subtype(c_t,rhs_t, loader)) { if(rhs_t instanceof Type.Primitive) { syntax_error("possible loss of precision (" + rhs_t + "=>" + c_t+")",e); } else { syntax_error("incompatible types",e); } } } catch(ClassNotFoundException ex) { syntax_error (ex.getMessage(),e); } } protected void checkBoolVal(Value.Bool e) { // do nothing! } protected void checkByteVal(Value.Byte e) { // do nothing! } protected void checkCharVal(Value.Char e) { // do nothing! } protected void checkShortVal(Value.Short e) { // do nothing! } protected void checkIntVal(Value.Int e) { // do nothing! } protected void checkLongVal(Value.Long e) { // do nothing! } protected void checkFloatVal(Value.Float e) { // do nothing! } protected void checkDoubleVal(Value.Double e) { // do nothing! } protected void checkStringVal(Value.String e) { // do nothing! } protected void checkNullVal(Value.Null e) { // do nothing! } protected void checkTypedArrayVal(Value.TypedArray e) { for(Expr v : e.values()) { checkExpression(v); } } protected void checkArrayVal(Value.Array e) { for(Expr v : e.values()) { checkExpression(v); } } protected void checkClassVal(Value.Class e) { // do nothing! } protected void checkLocalVariable(Expr.LocalVariable e) { // do nothing! } protected void checkNonLocalVariable(Expr.NonLocalVariable e) { // do nothing! } protected void checkClassVariable(Expr.ClassVariable e) { // do nothing! } protected void checkUnOp(Expr.UnOp uop) { checkExpression(uop.expr()); Type e_t = (Type) uop.expr().attribute(Type.class); switch(uop.op()) { case UnOp.NEG: if (!(e_t instanceof Type.Byte || e_t instanceof Type.Char || e_t instanceof Type.Short || e_t instanceof Type.Int || e_t instanceof Type.Long || e_t instanceof Type.Float || e_t instanceof Type.Double)) { syntax_error("cannot negate type " + e_t, uop); } break; case UnOp.NOT: if (!(e_t instanceof Type.Bool)) { syntax_error("required type boolean, found " + e_t, uop); } break; case UnOp.INV: if (!(e_t instanceof Type.Byte || e_t instanceof Type.Char || e_t instanceof Type.Short || e_t instanceof Type.Int || e_t instanceof Type.Long)) { syntax_error("cannot invert type " + e_t, uop); } break; } } protected void checkBinOp(Expr.BinOp e) { checkExpression(e.lhs()); checkExpression(e.rhs()); Type lhs_t = (Type) e.lhs().attribute(Type.class); Type rhs_t = (Type) e.rhs().attribute(Type.class); Type e_t = (Type) e.attribute(Type.class); SourceLocation loc = (SourceLocation) e.attribute(SourceLocation.class); if ((lhs_t instanceof Type.Primitive || rhs_t instanceof Type.Primitive) && !lhs_t.equals(rhs_t)) { if ((lhs_t instanceof Type.Long || lhs_t instanceof Type.Int || lhs_t instanceof Type.Short || lhs_t instanceof Type.Char || lhs_t instanceof Type.Byte) && rhs_t instanceof Type.Int && (e.op() == BinOp.SHL || e.op() == BinOp.SHR || e.op() == BinOp.USHR)) { return; // Ok! } else if((isJavaLangString(lhs_t) || isJavaLangString(rhs_t)) && e.op() == BinOp.CONCAT) { return; // OK } } else if((lhs_t instanceof Type.Char || lhs_t instanceof Type.Byte || lhs_t instanceof Type.Int || lhs_t instanceof Type.Long || lhs_t instanceof Type.Short || lhs_t instanceof Type.Float || lhs_t instanceof Type.Double) && (rhs_t instanceof Type.Char || rhs_t instanceof Type.Byte || rhs_t instanceof Type.Int || rhs_t instanceof Type.Long || rhs_t instanceof Type.Short || rhs_t instanceof Type.Float || rhs_t instanceof Type.Double)) { switch(e.op()) { // easy cases first case BinOp.EQ: case BinOp.NEQ: case BinOp.LT: case BinOp.LTEQ: case BinOp.GT: case BinOp.GTEQ: // need more checks here if(!(e_t instanceof Type.Bool)) { syntax_error("required type boolean, found " + rhs_t,e); } return; case BinOp.ADD: case BinOp.SUB: case BinOp.MUL: case BinOp.DIV: case BinOp.MOD: { // hmmmm ? return; } case BinOp.SHL: case BinOp.SHR: case BinOp.USHR: { // bit-shift operations always take an int as their rhs, so // make sure we have an int type if (lhs_t instanceof Type.Float || lhs_t instanceof Type.Double) { syntax_error("Invalid operation on type " + lhs_t, e); } else if (!(rhs_t instanceof Type.Int)) { syntax_error("Invalid operation on type " + rhs_t, e); } return; } case BinOp.AND: case BinOp.OR: case BinOp.XOR: { if (rhs_t instanceof Type.Float || rhs_t instanceof Type.Double) { syntax_error("Invalid operation on type " + rhs_t, e); } return; } } } else if(lhs_t instanceof Type.Bool && rhs_t instanceof Type.Bool) { switch(e.op()) { case BinOp.LOR: - case BinOp.LAND: + case BinOp.LAND: + case BinOp.AND: + case BinOp.OR: + case BinOp.XOR: return; // OK } } else if((isJavaLangString(lhs_t) || isJavaLangString(rhs_t)) && e.op() == Expr.BinOp.CONCAT) { return; // OK } else if (lhs_t instanceof Type.Reference && rhs_t instanceof Type.Reference && (e.op() == Expr.BinOp.EQ || e.op() == Expr.BinOp.NEQ)) { return; } syntax_error("operand types do not go together: " + lhs_t + ", " + rhs_t,e); } protected void checkTernOp(Expr.TernOp e) { checkExpression(e.condition()); checkExpression(e.trueBranch()); checkExpression(e.falseBranch()); Type c_t = (Type) e.condition().attribute(Type.class); if (!(c_t instanceof Type.Bool)) { syntax_error("required type boolean, found " + c_t, e); } } protected Decl getEnclosingScope(Class c) { for(int i=enclosingScopes.size()-1;i>=0;--i) { Decl d = enclosingScopes.get(i); if(c.isInstance(d)) { return d; } } return null; } }
true
true
protected void checkBinOp(Expr.BinOp e) { checkExpression(e.lhs()); checkExpression(e.rhs()); Type lhs_t = (Type) e.lhs().attribute(Type.class); Type rhs_t = (Type) e.rhs().attribute(Type.class); Type e_t = (Type) e.attribute(Type.class); SourceLocation loc = (SourceLocation) e.attribute(SourceLocation.class); if ((lhs_t instanceof Type.Primitive || rhs_t instanceof Type.Primitive) && !lhs_t.equals(rhs_t)) { if ((lhs_t instanceof Type.Long || lhs_t instanceof Type.Int || lhs_t instanceof Type.Short || lhs_t instanceof Type.Char || lhs_t instanceof Type.Byte) && rhs_t instanceof Type.Int && (e.op() == BinOp.SHL || e.op() == BinOp.SHR || e.op() == BinOp.USHR)) { return; // Ok! } else if((isJavaLangString(lhs_t) || isJavaLangString(rhs_t)) && e.op() == BinOp.CONCAT) { return; // OK } } else if((lhs_t instanceof Type.Char || lhs_t instanceof Type.Byte || lhs_t instanceof Type.Int || lhs_t instanceof Type.Long || lhs_t instanceof Type.Short || lhs_t instanceof Type.Float || lhs_t instanceof Type.Double) && (rhs_t instanceof Type.Char || rhs_t instanceof Type.Byte || rhs_t instanceof Type.Int || rhs_t instanceof Type.Long || rhs_t instanceof Type.Short || rhs_t instanceof Type.Float || rhs_t instanceof Type.Double)) { switch(e.op()) { // easy cases first case BinOp.EQ: case BinOp.NEQ: case BinOp.LT: case BinOp.LTEQ: case BinOp.GT: case BinOp.GTEQ: // need more checks here if(!(e_t instanceof Type.Bool)) { syntax_error("required type boolean, found " + rhs_t,e); } return; case BinOp.ADD: case BinOp.SUB: case BinOp.MUL: case BinOp.DIV: case BinOp.MOD: { // hmmmm ? return; } case BinOp.SHL: case BinOp.SHR: case BinOp.USHR: { // bit-shift operations always take an int as their rhs, so // make sure we have an int type if (lhs_t instanceof Type.Float || lhs_t instanceof Type.Double) { syntax_error("Invalid operation on type " + lhs_t, e); } else if (!(rhs_t instanceof Type.Int)) { syntax_error("Invalid operation on type " + rhs_t, e); } return; } case BinOp.AND: case BinOp.OR: case BinOp.XOR: { if (rhs_t instanceof Type.Float || rhs_t instanceof Type.Double) { syntax_error("Invalid operation on type " + rhs_t, e); } return; } } } else if(lhs_t instanceof Type.Bool && rhs_t instanceof Type.Bool) { switch(e.op()) { case BinOp.LOR: case BinOp.LAND: return; // OK } } else if((isJavaLangString(lhs_t) || isJavaLangString(rhs_t)) && e.op() == Expr.BinOp.CONCAT) { return; // OK } else if (lhs_t instanceof Type.Reference && rhs_t instanceof Type.Reference && (e.op() == Expr.BinOp.EQ || e.op() == Expr.BinOp.NEQ)) { return; } syntax_error("operand types do not go together: " + lhs_t + ", " + rhs_t,e); }
protected void checkBinOp(Expr.BinOp e) { checkExpression(e.lhs()); checkExpression(e.rhs()); Type lhs_t = (Type) e.lhs().attribute(Type.class); Type rhs_t = (Type) e.rhs().attribute(Type.class); Type e_t = (Type) e.attribute(Type.class); SourceLocation loc = (SourceLocation) e.attribute(SourceLocation.class); if ((lhs_t instanceof Type.Primitive || rhs_t instanceof Type.Primitive) && !lhs_t.equals(rhs_t)) { if ((lhs_t instanceof Type.Long || lhs_t instanceof Type.Int || lhs_t instanceof Type.Short || lhs_t instanceof Type.Char || lhs_t instanceof Type.Byte) && rhs_t instanceof Type.Int && (e.op() == BinOp.SHL || e.op() == BinOp.SHR || e.op() == BinOp.USHR)) { return; // Ok! } else if((isJavaLangString(lhs_t) || isJavaLangString(rhs_t)) && e.op() == BinOp.CONCAT) { return; // OK } } else if((lhs_t instanceof Type.Char || lhs_t instanceof Type.Byte || lhs_t instanceof Type.Int || lhs_t instanceof Type.Long || lhs_t instanceof Type.Short || lhs_t instanceof Type.Float || lhs_t instanceof Type.Double) && (rhs_t instanceof Type.Char || rhs_t instanceof Type.Byte || rhs_t instanceof Type.Int || rhs_t instanceof Type.Long || rhs_t instanceof Type.Short || rhs_t instanceof Type.Float || rhs_t instanceof Type.Double)) { switch(e.op()) { // easy cases first case BinOp.EQ: case BinOp.NEQ: case BinOp.LT: case BinOp.LTEQ: case BinOp.GT: case BinOp.GTEQ: // need more checks here if(!(e_t instanceof Type.Bool)) { syntax_error("required type boolean, found " + rhs_t,e); } return; case BinOp.ADD: case BinOp.SUB: case BinOp.MUL: case BinOp.DIV: case BinOp.MOD: { // hmmmm ? return; } case BinOp.SHL: case BinOp.SHR: case BinOp.USHR: { // bit-shift operations always take an int as their rhs, so // make sure we have an int type if (lhs_t instanceof Type.Float || lhs_t instanceof Type.Double) { syntax_error("Invalid operation on type " + lhs_t, e); } else if (!(rhs_t instanceof Type.Int)) { syntax_error("Invalid operation on type " + rhs_t, e); } return; } case BinOp.AND: case BinOp.OR: case BinOp.XOR: { if (rhs_t instanceof Type.Float || rhs_t instanceof Type.Double) { syntax_error("Invalid operation on type " + rhs_t, e); } return; } } } else if(lhs_t instanceof Type.Bool && rhs_t instanceof Type.Bool) { switch(e.op()) { case BinOp.LOR: case BinOp.LAND: case BinOp.AND: case BinOp.OR: case BinOp.XOR: return; // OK } } else if((isJavaLangString(lhs_t) || isJavaLangString(rhs_t)) && e.op() == Expr.BinOp.CONCAT) { return; // OK } else if (lhs_t instanceof Type.Reference && rhs_t instanceof Type.Reference && (e.op() == Expr.BinOp.EQ || e.op() == Expr.BinOp.NEQ)) { return; } syntax_error("operand types do not go together: " + lhs_t + ", " + rhs_t,e); }
diff --git a/jsf/tests/org.jboss.tools.jsf.ui.test/src/org/jboss/tools/jsf/jsp/ca/test/CAForJSF2BeansInJavaTest.java b/jsf/tests/org.jboss.tools.jsf.ui.test/src/org/jboss/tools/jsf/jsp/ca/test/CAForJSF2BeansInJavaTest.java index 550b0f770..f9e10ee14 100644 --- a/jsf/tests/org.jboss.tools.jsf.ui.test/src/org/jboss/tools/jsf/jsp/ca/test/CAForJSF2BeansInJavaTest.java +++ b/jsf/tests/org.jboss.tools.jsf.ui.test/src/org/jboss/tools/jsf/jsp/ca/test/CAForJSF2BeansInJavaTest.java @@ -1,44 +1,44 @@ /******************************************************************************* * Copyright (c) 2011 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is 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 * * Contributor: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.jsf.jsp.ca.test; import org.jboss.tools.common.base.test.contentassist.JavaContentAssistantTestCase; import org.jboss.tools.test.util.TestProjectProvider; public class CAForJSF2BeansInJavaTest extends JavaContentAssistantTestCase{ TestProjectProvider provider = null; boolean makeCopy = true; private static final String PROJECT_NAME = "JSF2Beans"; private static final String PAGE_NAME = "/src/test/beans/Bean1.java"; public void setUp() throws Exception { provider = new TestProjectProvider("org.jboss.tools.jsf.test", null, PROJECT_NAME, makeCopy); project = provider.getProject(); } protected void tearDown() throws Exception { if(provider != null) { provider.dispose(); } } /** * JBIDE-9362 */ public void testCAForJSF2Beans(){ String[] proposals = { - "mybean1 : Bean1", "mybean2 : Bean2" + "mybean1 : Bean1", "mybean2 : Bean3" }; checkProposals(PAGE_NAME, "#{}", 2, proposals, false); } }
true
true
public void testCAForJSF2Beans(){ String[] proposals = { "mybean1 : Bean1", "mybean2 : Bean2" }; checkProposals(PAGE_NAME, "#{}", 2, proposals, false); }
public void testCAForJSF2Beans(){ String[] proposals = { "mybean1 : Bean1", "mybean2 : Bean3" }; checkProposals(PAGE_NAME, "#{}", 2, proposals, false); }
diff --git a/modules/org.restlet/src/org/restlet/engine/component/ComponentHelper.java b/modules/org.restlet/src/org/restlet/engine/component/ComponentHelper.java index c517f5de0..86889a061 100644 --- a/modules/org.restlet/src/org/restlet/engine/component/ComponentHelper.java +++ b/modules/org.restlet/src/org/restlet/engine/component/ComponentHelper.java @@ -1,275 +1,274 @@ /** * Copyright 2005-2009 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.component; import java.util.Iterator; import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.engine.ChainHelper; import org.restlet.routing.TemplateRoute; import org.restlet.routing.VirtualHost; /** * Component helper. * * @author Jerome Louvel */ public class ComponentHelper extends ChainHelper<Component> { /** The internal client router. */ private final ClientRouter clientRouter; /** The internal server router. */ private volatile ServerRouter serverRouter; /** * Constructor. * * @param component * The helper component. */ public ComponentHelper(Component component) { super(component); component.setContext(new ComponentContext(this)); this.clientRouter = new ClientRouter(getHelped()); this.serverRouter = new ServerRouter(getHelped()); } /** * Check the applications attached to a virtual host. * * @param host * The parent virtual host. * @return True if the check succeeded. * @throws Exception */ private boolean checkVirtualHost(VirtualHost host) throws Exception { boolean result = true; if (host != null) { for (TemplateRoute route : host.getRoutes()) { Restlet next = route.getNext(); if (next instanceof Application) { Application application = (Application) next; if (application.getConnectorService() != null) { if (application.getConnectorService() .getClientProtocols() != null) { for (Protocol clientProtocol : application .getConnectorService().getClientProtocols()) { boolean clientFound = false; // Try to find a client connector matching the - // client - // protocol + // client protocol Client client; for (Iterator<Client> iter = getHelped() .getClients().iterator(); !clientFound && iter.hasNext();) { client = iter.next(); clientFound = client.getProtocols() .contains(clientProtocol); } if (!clientFound) { getLogger() .severe( "Unable to start the application \"" + application .getName() + "\". Client connector for protocol " + clientProtocol .getName() + " is missing."); result = false; } } } if (application.getConnectorService() .getServerProtocols() != null) { for (Protocol serverProtocol : application .getConnectorService().getServerProtocols()) { boolean serverFound = false; // Try to find a server connector matching the // server // protocol Server server; for (Iterator<Server> iter = getHelped() .getServers().iterator(); !serverFound && iter.hasNext();) { server = iter.next(); serverFound = server.getProtocols() .contains(serverProtocol); } if (!serverFound) { getLogger() .severe( "Unable to start the application \"" + application .getName() + "\". Server connector for protocol " + serverProtocol .getName() + " is missing."); result = false; } } } } if (result && application.isStopped()) { application.start(); } } } } return result; } /** * Returns the internal client router. * * @return the internal client router. */ public ClientRouter getClientRouter() { return this.clientRouter; } /** * Returns the internal host router. * * @return the internal host router. */ public ServerRouter getServerRouter() { return this.serverRouter; } /** * Sets the internal server router. * * @param serverRouter * The internal host router. */ public void setServerRouter(ServerRouter serverRouter) { this.serverRouter = serverRouter; } @Override public synchronized void start() throws Exception { // Checking if all applications have proper connectors boolean success = checkVirtualHost(getHelped().getDefaultHost()); if (success) { for (VirtualHost host : getHelped().getHosts()) { success = success && checkVirtualHost(host); } } // Let's actually start the component if (!success) { getHelped().stop(); } else { // Logging of calls if (getHelped().getLogService().isEnabled()) { addFilter(getHelped().getLogService().createInboundFilter( getContext().createChildContext())); } // Addition of status pages if (getHelped().getStatusService().isEnabled()) { addFilter(getHelped().getStatusService().createInboundFilter( getContext().createChildContext())); } // Re-attach the original filter's attached Restlet setNext(getServerRouter()); } } @Override public synchronized void stop() throws Exception { // Stop the server's router getServerRouter().stop(); // Stop all applications stopVirtualHostApplications(getHelped().getDefaultHost()); for (VirtualHost host : getHelped().getHosts()) { stopVirtualHostApplications(host); } } /** * Stop all applications attached to a virtual host * * @param host * @throws Exception */ private void stopVirtualHostApplications(VirtualHost host) throws Exception { for (TemplateRoute route : host.getRoutes()) { if (route.getNext().isStarted()) { route.getNext().stop(); } } } /** * Set the new server router that will compute the new routes when the first * request will be received (automatic start). */ @Override public void update() throws Exception { // Note the old router to be able to stop it at the end ServerRouter oldRouter = getServerRouter(); // Set the new server router that will compute the new routes when the // first request will be received (automatic start). setServerRouter(new ServerRouter(getHelped())); // Replace the old server router setNext(getServerRouter()); // Stop the old server router if (oldRouter != null) { oldRouter.stop(); } } }
true
true
private boolean checkVirtualHost(VirtualHost host) throws Exception { boolean result = true; if (host != null) { for (TemplateRoute route : host.getRoutes()) { Restlet next = route.getNext(); if (next instanceof Application) { Application application = (Application) next; if (application.getConnectorService() != null) { if (application.getConnectorService() .getClientProtocols() != null) { for (Protocol clientProtocol : application .getConnectorService().getClientProtocols()) { boolean clientFound = false; // Try to find a client connector matching the // client // protocol Client client; for (Iterator<Client> iter = getHelped() .getClients().iterator(); !clientFound && iter.hasNext();) { client = iter.next(); clientFound = client.getProtocols() .contains(clientProtocol); } if (!clientFound) { getLogger() .severe( "Unable to start the application \"" + application .getName() + "\". Client connector for protocol " + clientProtocol .getName() + " is missing."); result = false; } } } if (application.getConnectorService() .getServerProtocols() != null) { for (Protocol serverProtocol : application .getConnectorService().getServerProtocols()) { boolean serverFound = false; // Try to find a server connector matching the // server // protocol Server server; for (Iterator<Server> iter = getHelped() .getServers().iterator(); !serverFound && iter.hasNext();) { server = iter.next(); serverFound = server.getProtocols() .contains(serverProtocol); } if (!serverFound) { getLogger() .severe( "Unable to start the application \"" + application .getName() + "\". Server connector for protocol " + serverProtocol .getName() + " is missing."); result = false; } } } } if (result && application.isStopped()) { application.start(); } } } } return result; }
private boolean checkVirtualHost(VirtualHost host) throws Exception { boolean result = true; if (host != null) { for (TemplateRoute route : host.getRoutes()) { Restlet next = route.getNext(); if (next instanceof Application) { Application application = (Application) next; if (application.getConnectorService() != null) { if (application.getConnectorService() .getClientProtocols() != null) { for (Protocol clientProtocol : application .getConnectorService().getClientProtocols()) { boolean clientFound = false; // Try to find a client connector matching the // client protocol Client client; for (Iterator<Client> iter = getHelped() .getClients().iterator(); !clientFound && iter.hasNext();) { client = iter.next(); clientFound = client.getProtocols() .contains(clientProtocol); } if (!clientFound) { getLogger() .severe( "Unable to start the application \"" + application .getName() + "\". Client connector for protocol " + clientProtocol .getName() + " is missing."); result = false; } } } if (application.getConnectorService() .getServerProtocols() != null) { for (Protocol serverProtocol : application .getConnectorService().getServerProtocols()) { boolean serverFound = false; // Try to find a server connector matching the // server // protocol Server server; for (Iterator<Server> iter = getHelped() .getServers().iterator(); !serverFound && iter.hasNext();) { server = iter.next(); serverFound = server.getProtocols() .contains(serverProtocol); } if (!serverFound) { getLogger() .severe( "Unable to start the application \"" + application .getName() + "\". Server connector for protocol " + serverProtocol .getName() + " is missing."); result = false; } } } } if (result && application.isStopped()) { application.start(); } } } } return result; }
diff --git a/android/src/org/coolreader/crengine/CRRootView.java b/android/src/org/coolreader/crengine/CRRootView.java index 4e09d6a9..a1813cb9 100644 --- a/android/src/org/coolreader/crengine/CRRootView.java +++ b/android/src/org/coolreader/crengine/CRRootView.java @@ -1,498 +1,501 @@ package org.coolreader.crengine; import java.io.File; import java.util.ArrayList; import org.coolreader.CoolReader; import org.coolreader.R; import org.coolreader.crengine.CoverpageManager.CoverpageReadyListener; import org.coolreader.db.CRDBService; import org.coolreader.db.CRDBService.OPDSCatalogsLoadingCallback; import org.coolreader.plugins.OnlineStorePluginManager; import org.coolreader.plugins.OnlineStoreWrapper; import org.coolreader.plugins.litres.LitresPlugin; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; public class CRRootView extends ViewGroup implements CoverpageReadyListener { public static final Logger log = L.create("cr"); private final CoolReader mActivity; private ViewGroup mView; private LinearLayout mRecentBooksScroll; private LinearLayout mFilesystemScroll; private LinearLayout mLibraryScroll; private LinearLayout mOnlineCatalogsScroll; private CoverpageManager mCoverpageManager; private int coverWidth; private int coverHeight; private BookInfo currentBook; private CoverpageReadyListener coverpageListener; public CRRootView(CoolReader activity) { super(activity); this.mActivity = activity; this.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); this.mCoverpageManager = Services.getCoverpageManager(); int screenHeight = mActivity.getWindowManager().getDefaultDisplay().getHeight(); int screenWidth = mActivity.getWindowManager().getDefaultDisplay().getWidth(); int h = screenHeight / 4; int w = screenWidth / 4; if (h > w) h = w; w = h * 3 / 4; coverWidth = w; coverHeight = h; createViews(); } private InterfaceTheme lastTheme; public void onThemeChange(InterfaceTheme theme) { if (lastTheme != theme) { lastTheme = theme; createViews(); } } public void onClose() { this.mCoverpageManager.removeCoverpageReadyListener(coverpageListener); coverpageListener = null; super.onDetachedFromWindow(); } private void setBookInfoItem(ViewGroup baseView, int viewId, String value) { TextView view = (TextView)baseView.findViewById(viewId); if (view != null) { if (value != null && value.length() > 0) { view.setText(value); } else { view.setText(""); } } } private void updateCurrentBook(BookInfo book) { currentBook = book; // set current book cover page ImageView cover = (ImageView)mView.findViewById(R.id.book_cover); if (currentBook != null) { FileInfo item = currentBook.getFileInfo(); cover.setImageDrawable(mCoverpageManager.getCoverpageDrawableFor(mActivity.getDB(), item, coverWidth, coverHeight)); cover.setMinimumHeight(coverHeight); cover.setMinimumWidth(coverWidth); cover.setMaxHeight(coverHeight); cover.setMaxWidth(coverWidth); cover.setTag(new CoverpageManager.ImageItem(item, coverWidth, coverHeight)); setBookInfoItem(mView, R.id.lbl_book_author, Utils.formatAuthors(item.authors)); setBookInfoItem(mView, R.id.lbl_book_title, currentBook.getFileInfo().title); setBookInfoItem(mView, R.id.lbl_book_series, Utils.formatSeries(item.series, item.seriesNumber)); String state = Utils.formatReadingState(mActivity, item); state = state + " " + Utils.formatFileInfo(item) + " "; state = state + " " + Utils.formatLastPosition(Services.getHistory().getLastPos(item)); setBookInfoItem(mView, R.id.lbl_book_info, state); } else { log.w("No current book in history"); cover.setImageDrawable(null); cover.setMinimumHeight(0); cover.setMinimumWidth(0); cover.setMaxHeight(0); cover.setMaxWidth(0); setBookInfoItem(mView, R.id.lbl_book_author, ""); setBookInfoItem(mView, R.id.lbl_book_title, "No last book"); // TODO: i18n setBookInfoItem(mView, R.id.lbl_book_series, ""); } } private final static int MAX_RECENT_BOOKS = 12; private void updateRecentBooks(ArrayList<BookInfo> books) { ArrayList<FileInfo> files = new ArrayList<FileInfo>(); for (int i = 1; i <= MAX_RECENT_BOOKS && i < books.size(); i++) files.add(books.get(i).getFileInfo()); files.add(Services.getScanner().createRecentRoot()); LayoutInflater inflater = LayoutInflater.from(mActivity); mRecentBooksScroll.removeAllViews(); for (final FileInfo item : files) { final View view = inflater.inflate(R.layout.root_item_recent_book, null); ImageView cover = (ImageView)view.findViewById(R.id.book_cover); TextView label = (TextView)view.findViewById(R.id.book_name); cover.setMinimumHeight(coverHeight); cover.setMaxHeight(coverHeight); cover.setMaxWidth(coverWidth); if (item.isRecentDir()) { cover.setImageResource(R.drawable.cr3_button_next); if (label != null) { label.setText("More..."); } view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Activities.showRecentBooks(); } }); } else { cover.setMinimumWidth(coverWidth); cover.setTag(new CoverpageManager.ImageItem(item, coverWidth, coverHeight)); cover.setImageDrawable(mCoverpageManager.getCoverpageDrawableFor(mActivity.getDB(), item, coverWidth, coverHeight)); if (label != null) { String title = item.title; String authors = Utils.formatAuthors(item.authors); String s = item.getFileNameToDisplay(); if (!Utils.empty(title) && !Utils.empty(authors)) s = title + " - " + authors; else if (!Utils.empty(title)) s = title; else if (!Utils.empty(authors)) s = authors; label.setText(s != null ? s : ""); label.setMaxWidth(coverWidth); } view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Activities.loadDocument(item); } }); view.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { Activities.editBookInfo(mActivity, Services.getScanner().createRecentRoot(), item); return true; } }); } mRecentBooksScroll.addView(view); } mRecentBooksScroll.invalidate(); } public void refreshRecentBooks() { BackgroundThread.instance().postGUI(new Runnable() { @Override public void run() { if (Services.getHistory() != null && mActivity.getDB() != null) Services.getHistory().getOrLoadRecentBooks(mActivity.getDB(), new CRDBService.RecentBooksLoadingCallback() { @Override public void onRecentBooksListLoaded(ArrayList<BookInfo> bookList) { updateCurrentBook(bookList != null && bookList.size() > 0 ? bookList.get(0) : null); updateRecentBooks(bookList); } }); } }); } public void refreshOnlineCatalogs() { if (mActivity.getDB() != null) mActivity.getDB().loadOPDSCatalogs(new OPDSCatalogsLoadingCallback() { @Override public void onOPDSCatalogsLoaded(ArrayList<FileInfo> catalogs) { updateOnlineCatalogs(catalogs); } }); } private void updateOnlineCatalogs(ArrayList<FileInfo> catalogs) { catalogs.add(0, Services.getScanner().createOnlineLibraryPluginItem("org.coolreader.plugins.litres", "LitRes")); - catalogs.add(Services.getScanner().createOPDSRoot()); + FileInfo opdsRoot = Services.getScanner().getOPDSRoot(); + if (opdsRoot.dirCount() == 0) + opdsRoot.addItems(catalogs); + catalogs.add(opdsRoot); LayoutInflater inflater = LayoutInflater.from(mActivity); mOnlineCatalogsScroll.removeAllViews(); for (final FileInfo item : catalogs) { final View view = inflater.inflate(R.layout.root_item_online_catalog, null); ImageView icon = (ImageView)view.findViewById(R.id.item_icon); TextView label = (TextView)view.findViewById(R.id.item_name); if (item.isOPDSRoot()) { icon.setImageResource(R.drawable.cr3_browser_folder_opds_add); label.setText("Add"); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Activities.editOPDSCatalog(null); } }); } else if (item.isOnlineCatalogPluginDir()) { icon.setImageResource(R.drawable.plugins_logo_litres); label.setText(item.filename); view.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { OnlineStoreWrapper plugin = OnlineStorePluginManager.getPlugin(FileInfo.ONLINE_CATALOG_PLUGIN_PREFIX + LitresPlugin.PACKAGE_NAME); if (plugin != null) { OnlineStoreLoginDialog dlg = new OnlineStoreLoginDialog(mActivity, plugin, new Runnable() { @Override public void run() { Activities.showBrowser(FileInfo.ONLINE_CATALOG_PLUGIN_PREFIX + LitresPlugin.PACKAGE_NAME); } }); dlg.show(); } return true; } }); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Activities.showBrowser(FileInfo.ONLINE_CATALOG_PLUGIN_PREFIX + LitresPlugin.PACKAGE_NAME); // LitresConnection.instance().loadGenres(new ResultHandler() { // @Override // public void onResponse(LitresResponse response) { // if (response instanceof LitresConnection.LitresGenre) { // LitresConnection.LitresGenre result = (LitresConnection.LitresGenre)response; // log.d("genres found: " + result.getChildCount() + " on top level"); // } // } // }); // LitresConnection.instance().authorize("login", "password", new ResultHandler() { // @Override // public void onResponse(LitresResponse response) { // if (response instanceof LitresConnection.LitresAuthInfo) { // LitresConnection.LitresAuthInfo result = (LitresConnection.LitresAuthInfo)response; // log.d("authorization successful: " + result); // } else { // log.d("authorization failed"); // } // } // }); // LitresConnection.instance().loadAuthorsByLastName("л", new ResultHandler() { // @Override // public void onResponse(LitresResponse response) { // if (response instanceof LitresConnection.LitresAuthors) { // LitresConnection.LitresAuthors result = (LitresConnection.LitresAuthors)response; // log.d("authors found: " + result.size()); // for (int i=0; i<result.size() && i<10; i++) { // log.d(result.get(i).toString()); // } // } // } // }); // mActivity.showToast("TODO"); } }); } else { if (label != null) { label.setText(item.getFileNameToDisplay()); label.setMaxWidth(coverWidth * 3 / 2); } view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Activities.showCatalog(item); } }); view.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { Activities.editOPDSCatalog(item); return true; } }); } mOnlineCatalogsScroll.addView(view); } mOnlineCatalogsScroll.invalidate(); } private void updateFilesystems(ArrayList<FileInfo> dirs) { LayoutInflater inflater = LayoutInflater.from(mActivity); mFilesystemScroll.removeAllViews(); for (int i = 0; i < dirs.size(); i++) { final FileInfo item = dirs.get(i); final View view = inflater.inflate(R.layout.root_item_dir, null); ImageView icon = (ImageView)view.findViewById(R.id.item_icon); TextView label = (TextView)view.findViewById(R.id.item_name); if (i == dirs.size() - 1) icon.setImageResource(R.drawable.cr3_browser_folder_user); else icon.setImageResource(R.drawable.cr3_browser_folder_database); label.setText(item.pathname); label.setMaxWidth(coverWidth * 25 / 10); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Activities.showDirectory(item); } }); mFilesystemScroll.addView(view); } mFilesystemScroll.invalidate(); } private void updateLibraryItems(ArrayList<FileInfo> dirs) { LayoutInflater inflater = LayoutInflater.from(mActivity); mLibraryScroll.removeAllViews(); for (final FileInfo item : dirs) { final View view = inflater.inflate(R.layout.root_item_library, null); ImageView image = (ImageView)view.findViewById(R.id.item_icon); TextView label = (TextView)view.findViewById(R.id.item_name); if (item.isSearchShortcut()) image.setImageResource(R.drawable.cr3_browser_find); else if (item.isBooksByAuthorRoot() || item.isBooksByTitleRoot() || item.isBooksBySeriesRoot()) image.setImageResource(R.drawable.cr3_browser_folder_authors); if (label != null) { label.setText(item.filename); label.setMinWidth(coverWidth); label.setMaxWidth(coverWidth * 2); } view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Activities.showDirectory(item); } }); mLibraryScroll.addView(view); } mLibraryScroll.invalidate(); } // private HorizontalListView createHScroll(int layoutId, OnLongClickListener longClickListener) { // LinearLayout layout = (LinearLayout)mView.findViewById(layoutId); // layout.removeAllViews(); // HorizontalListView view = new HorizontalListView(mActivity, null); // view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); //// view.setFadingEdgeLength(10); //// view.setHorizontalFadingEdgeEnabled(true); // layout.addView(view); // if (longClickListener != null) // layout.setOnLongClickListener(longClickListener); // return view; // } private void updateDelimiterTheme(int viewId) { View view = mView.findViewById(viewId); InterfaceTheme theme = mActivity.getCurrentTheme(); view.setBackgroundResource(theme.getRootDelimiterResourceId()); view.setMinimumHeight(theme.getRootDelimiterHeight()); view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, theme.getRootDelimiterHeight())); } private void createViews() { LayoutInflater inflater = LayoutInflater.from(mActivity); View view = inflater.inflate(R.layout.root_window, null); mView = (ViewGroup)view; updateDelimiterTheme(R.id.delimiter1); updateDelimiterTheme(R.id.delimiter2); updateDelimiterTheme(R.id.delimiter3); updateDelimiterTheme(R.id.delimiter4); updateDelimiterTheme(R.id.delimiter5); mRecentBooksScroll = (LinearLayout)mView.findViewById(R.id.scroll_recent_books); mFilesystemScroll = (LinearLayout)mView.findViewById(R.id.scroll_filesystem); mLibraryScroll = (LinearLayout)mView.findViewById(R.id.scroll_library); mOnlineCatalogsScroll = (LinearLayout)mView.findViewById(R.id.scroll_online_catalogs); updateCurrentBook(Services.getHistory().getLastBook()); // ((ImageButton)mView.findViewById(R.id.btn_recent_books)).setOnClickListener(new OnClickListener() { // @Override // public void onClick(View v) { // Activities.showRecentBooks(); // } // }); // // ((ImageButton)mView.findViewById(R.id.btn_online_catalogs)).setOnClickListener(new OnClickListener() { // @Override // public void onClick(View v) { // Activities.showOnlineCatalogs(); // } // }); mView.findViewById(R.id.current_book).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (currentBook != null) { Activities.loadDocument(currentBook.getFileInfo()); } } }); mView.findViewById(R.id.current_book).setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { if (currentBook != null) Activities.editBookInfo(mActivity, Services.getScanner().createRecentRoot(), currentBook.getFileInfo()); return true; } }); refreshRecentBooks(); BackgroundThread.instance().postGUI(new Runnable() { @Override public void run() { refreshOnlineCatalogs(); } }); BackgroundThread.instance().postGUI(new Runnable() { @Override public void run() { ArrayList<FileInfo> dirs = new ArrayList<FileInfo>(); File[] roots = Engine.getStorageDirectories(false); for (File f : roots) { FileInfo dir = new FileInfo(f); dirs.add(dir); } dirs.add(Services.getScanner().getDownloadDirectory()); updateFilesystems(dirs); updateLibraryItems(Services.getScanner().getLibraryItems()); } }); removeAllViews(); addView(mView); setFocusable(true); setFocusableInTouchMode(true); requestFocus(); } public void onCoverpagesReady(ArrayList<CoverpageManager.ImageItem> files) { //invalidate(); log.d("CRRootView.onCoverpagesReady(" + files + ")"); CoverpageManager.invalidateChildImages(mView, files); // for (int i=0; i<mRecentBooksScroll.getChildCount(); i++) { // mRecentBooksScroll.getChildAt(i).invalidate(); // } // //mRecentBooksScroll.invalidate(); //ImageView cover = (ImageView)mView.findViewById(R.id.book_cover); //cover.invalidate(); // //mView.invalidate(); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { r -= l; b -= t; t = 0; l = 0; mView.layout(l, t, r, b); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { mView.measure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(mView.getMeasuredWidth(), mView.getMeasuredHeight()); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); } }
true
true
private void updateOnlineCatalogs(ArrayList<FileInfo> catalogs) { catalogs.add(0, Services.getScanner().createOnlineLibraryPluginItem("org.coolreader.plugins.litres", "LitRes")); catalogs.add(Services.getScanner().createOPDSRoot()); LayoutInflater inflater = LayoutInflater.from(mActivity); mOnlineCatalogsScroll.removeAllViews(); for (final FileInfo item : catalogs) { final View view = inflater.inflate(R.layout.root_item_online_catalog, null); ImageView icon = (ImageView)view.findViewById(R.id.item_icon); TextView label = (TextView)view.findViewById(R.id.item_name); if (item.isOPDSRoot()) { icon.setImageResource(R.drawable.cr3_browser_folder_opds_add); label.setText("Add"); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Activities.editOPDSCatalog(null); } }); } else if (item.isOnlineCatalogPluginDir()) { icon.setImageResource(R.drawable.plugins_logo_litres); label.setText(item.filename); view.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { OnlineStoreWrapper plugin = OnlineStorePluginManager.getPlugin(FileInfo.ONLINE_CATALOG_PLUGIN_PREFIX + LitresPlugin.PACKAGE_NAME); if (plugin != null) { OnlineStoreLoginDialog dlg = new OnlineStoreLoginDialog(mActivity, plugin, new Runnable() { @Override public void run() { Activities.showBrowser(FileInfo.ONLINE_CATALOG_PLUGIN_PREFIX + LitresPlugin.PACKAGE_NAME); } }); dlg.show(); } return true; } }); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Activities.showBrowser(FileInfo.ONLINE_CATALOG_PLUGIN_PREFIX + LitresPlugin.PACKAGE_NAME); // LitresConnection.instance().loadGenres(new ResultHandler() { // @Override // public void onResponse(LitresResponse response) { // if (response instanceof LitresConnection.LitresGenre) { // LitresConnection.LitresGenre result = (LitresConnection.LitresGenre)response; // log.d("genres found: " + result.getChildCount() + " on top level"); // } // } // }); // LitresConnection.instance().authorize("login", "password", new ResultHandler() { // @Override // public void onResponse(LitresResponse response) { // if (response instanceof LitresConnection.LitresAuthInfo) { // LitresConnection.LitresAuthInfo result = (LitresConnection.LitresAuthInfo)response; // log.d("authorization successful: " + result); // } else { // log.d("authorization failed"); // } // } // }); // LitresConnection.instance().loadAuthorsByLastName("л", new ResultHandler() { // @Override // public void onResponse(LitresResponse response) { // if (response instanceof LitresConnection.LitresAuthors) { // LitresConnection.LitresAuthors result = (LitresConnection.LitresAuthors)response; // log.d("authors found: " + result.size()); // for (int i=0; i<result.size() && i<10; i++) { // log.d(result.get(i).toString()); // } // } // } // }); // mActivity.showToast("TODO"); } }); } else { if (label != null) { label.setText(item.getFileNameToDisplay()); label.setMaxWidth(coverWidth * 3 / 2); } view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Activities.showCatalog(item); } }); view.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { Activities.editOPDSCatalog(item); return true; } }); } mOnlineCatalogsScroll.addView(view); } mOnlineCatalogsScroll.invalidate(); }
private void updateOnlineCatalogs(ArrayList<FileInfo> catalogs) { catalogs.add(0, Services.getScanner().createOnlineLibraryPluginItem("org.coolreader.plugins.litres", "LitRes")); FileInfo opdsRoot = Services.getScanner().getOPDSRoot(); if (opdsRoot.dirCount() == 0) opdsRoot.addItems(catalogs); catalogs.add(opdsRoot); LayoutInflater inflater = LayoutInflater.from(mActivity); mOnlineCatalogsScroll.removeAllViews(); for (final FileInfo item : catalogs) { final View view = inflater.inflate(R.layout.root_item_online_catalog, null); ImageView icon = (ImageView)view.findViewById(R.id.item_icon); TextView label = (TextView)view.findViewById(R.id.item_name); if (item.isOPDSRoot()) { icon.setImageResource(R.drawable.cr3_browser_folder_opds_add); label.setText("Add"); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Activities.editOPDSCatalog(null); } }); } else if (item.isOnlineCatalogPluginDir()) { icon.setImageResource(R.drawable.plugins_logo_litres); label.setText(item.filename); view.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { OnlineStoreWrapper plugin = OnlineStorePluginManager.getPlugin(FileInfo.ONLINE_CATALOG_PLUGIN_PREFIX + LitresPlugin.PACKAGE_NAME); if (plugin != null) { OnlineStoreLoginDialog dlg = new OnlineStoreLoginDialog(mActivity, plugin, new Runnable() { @Override public void run() { Activities.showBrowser(FileInfo.ONLINE_CATALOG_PLUGIN_PREFIX + LitresPlugin.PACKAGE_NAME); } }); dlg.show(); } return true; } }); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Activities.showBrowser(FileInfo.ONLINE_CATALOG_PLUGIN_PREFIX + LitresPlugin.PACKAGE_NAME); // LitresConnection.instance().loadGenres(new ResultHandler() { // @Override // public void onResponse(LitresResponse response) { // if (response instanceof LitresConnection.LitresGenre) { // LitresConnection.LitresGenre result = (LitresConnection.LitresGenre)response; // log.d("genres found: " + result.getChildCount() + " on top level"); // } // } // }); // LitresConnection.instance().authorize("login", "password", new ResultHandler() { // @Override // public void onResponse(LitresResponse response) { // if (response instanceof LitresConnection.LitresAuthInfo) { // LitresConnection.LitresAuthInfo result = (LitresConnection.LitresAuthInfo)response; // log.d("authorization successful: " + result); // } else { // log.d("authorization failed"); // } // } // }); // LitresConnection.instance().loadAuthorsByLastName("л", new ResultHandler() { // @Override // public void onResponse(LitresResponse response) { // if (response instanceof LitresConnection.LitresAuthors) { // LitresConnection.LitresAuthors result = (LitresConnection.LitresAuthors)response; // log.d("authors found: " + result.size()); // for (int i=0; i<result.size() && i<10; i++) { // log.d(result.get(i).toString()); // } // } // } // }); // mActivity.showToast("TODO"); } }); } else { if (label != null) { label.setText(item.getFileNameToDisplay()); label.setMaxWidth(coverWidth * 3 / 2); } view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Activities.showCatalog(item); } }); view.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { Activities.editOPDSCatalog(item); return true; } }); } mOnlineCatalogsScroll.addView(view); } mOnlineCatalogsScroll.invalidate(); }
diff --git a/app/pdf/PdfGenerator.java b/app/pdf/PdfGenerator.java index e841fa5..cc72f04 100644 --- a/app/pdf/PdfGenerator.java +++ b/app/pdf/PdfGenerator.java @@ -1,58 +1,60 @@ package pdf; import com.itextpdf.text.Font; import com.itextpdf.text.FontFactory; import play.Play; import java.io.File; import java.io.FileNotFoundException; import java.util.Date; /** * @author Lukasz Piliszczuk <lukasz.piliszczuk AT zenika.com> */ public abstract class PdfGenerator { private static final String GENERATED_PATH = "/generated/"; private static final String GENERATED_EXTENSION = ".pdf"; protected Font textBoldFont; protected Font textFont; protected Font titleFont; protected String rootPath; public PdfGenerator() { rootPath = Play.configuration.getProperty("my.pdf.resources.path"); String mode = Play.configuration.getProperty("application.mode"); if (mode.equals("dev")) { rootPath = Play.applicationPath.getPath() + rootPath; + } else { + rootPath = "/app/" + rootPath; } FontFactory.register(new File(rootPath + "/ARIALN.ttf").getPath(), "arialnarrow_normal"); FontFactory.register(new File(rootPath + "/ARIALNB.ttf").getPath(), "arialnarrow_bold"); textBoldFont = FontFactory.getFont("arialnarrow_bold", 8); textFont = FontFactory.getFont("arialnarrow_normal", 8); titleFont = FontFactory.getFont("arialnarrow_bold", 14); } protected File getFileForGeneration(String folder, String name) { File folderFile = new File(GENERATED_PATH + folder); if (!folderFile.exists()) { folderFile.mkdirs(); } return new File(folderFile, name + GENERATED_EXTENSION); } protected File getSupinfoLogo() { return new File(rootPath + "/supinfo_logo.png"); } }
true
true
public PdfGenerator() { rootPath = Play.configuration.getProperty("my.pdf.resources.path"); String mode = Play.configuration.getProperty("application.mode"); if (mode.equals("dev")) { rootPath = Play.applicationPath.getPath() + rootPath; } FontFactory.register(new File(rootPath + "/ARIALN.ttf").getPath(), "arialnarrow_normal"); FontFactory.register(new File(rootPath + "/ARIALNB.ttf").getPath(), "arialnarrow_bold"); textBoldFont = FontFactory.getFont("arialnarrow_bold", 8); textFont = FontFactory.getFont("arialnarrow_normal", 8); titleFont = FontFactory.getFont("arialnarrow_bold", 14); }
public PdfGenerator() { rootPath = Play.configuration.getProperty("my.pdf.resources.path"); String mode = Play.configuration.getProperty("application.mode"); if (mode.equals("dev")) { rootPath = Play.applicationPath.getPath() + rootPath; } else { rootPath = "/app/" + rootPath; } FontFactory.register(new File(rootPath + "/ARIALN.ttf").getPath(), "arialnarrow_normal"); FontFactory.register(new File(rootPath + "/ARIALNB.ttf").getPath(), "arialnarrow_bold"); textBoldFont = FontFactory.getFont("arialnarrow_bold", 8); textFont = FontFactory.getFont("arialnarrow_normal", 8); titleFont = FontFactory.getFont("arialnarrow_bold", 14); }
diff --git a/app/controllers/Photos.java b/app/controllers/Photos.java index f673bc0..4e5a152 100644 --- a/app/controllers/Photos.java +++ b/app/controllers/Photos.java @@ -1,246 +1,246 @@ package controllers; import java.awt.image.BufferedImage; import java.util.*; import javax.imageio.ImageIO; import java.io.*; import play.*; import play.data.validation.Error; import play.libs.*; import play.mvc.*; import play.db.jpa.*; import models.*; import java.security.*; import java.net.*; import java.awt.image.*; public class Photos extends OBController { /* All possible image mime types in a single regex. */ public static final String IMAGE_TYPE = "^image/(gif|jpeg|pjpeg|png)$"; public static final int MAX_FILE_SIZE = 2 * 1024 * 1024; /* Size in bytes. */ public static void photos(Long ownerId) { List<Photo> photos; if (ownerId == null) { photos = Photo.find("byOwner", user()).fetch(); } else { User user = User.findById(ownerId); photos = Photo.find("byOwner", user).fetch(); } render(photos); } public static void getPhoto(Long photoId) { Photo photo = Photo.findById(photoId); if (photo == null) { notFound("That photo does not exist."); } else { response.setContentTypeIfNotSet(photo.image.type()); renderBinary(photo.image.get()); } } /** * Convert a given File to a Photo model.Used in Bootstrap.java * * @param image the file to convert. * @return the newly created Photo model. * @throws FileNotFoundException */ public static Photo initFileToPhoto(String path, String caption) throws IOException, FileNotFoundException { File image = new File(path); User user = User.find("username = ?", "default").first();//set owner as default owner Photo photo = new Photo(user, image, caption); photo.save(); return photo; } public static void addPhoto(File image) throws FileNotFoundException, IOException { validation.keep(); /* Remember any errors after redirect. */ if (image == null || !MimeTypes.getContentType(image.getName()).matches(IMAGE_TYPE)) { validation.addError("image", "validation.image.type"); redirect("/users/" + user().id + "/photos"); } Photo photo = new Photo(user(), image); validation.max(photo.image.length(), MAX_FILE_SIZE); if (!validation.hasErrors()) { photo.save(); } redirect("/users/" + photo.owner.id + "/photos"); } public static void removePhoto(Long photoId) { Photo photo = Photo.findById(photoId); if (photo == null) notFound("That photo does not exist."); if (!photo.owner.equals(user())) forbidden(); photo.delete(); redirect("/users/" + photo.owner.id + "/photos"); } public static void setProfilePhotoPage() { User user = user(); List<Photo> photos = Photo.find("byOwner", user).fetch(); render(user,photos); } public static void changeBGImage() { User user = user(); photos(user.id); } public static void setProfilePhoto(Long photoId) { User user = user(); Photo photo = Photo.findById(photoId); if (photo == null) notFound("That photo does not exist."); if (!photo.owner.equals(user())) forbidden(); user.profile.profilePhoto = photo; user.profile.save(); setProfilePhotoPage();//render page } /** * addProfilePhoto * * just does the adding of the photo and then uses setProfilePhoto to set the profilePhoto * @param image * @throws FileNotFoundException * @throws IOException */ public static void addProfilePhoto(File image) throws FileNotFoundException, IOException { if(image != null) { try { Photo photo = new Photo(user(), image); validation.match(photo.image.type(), IMAGE_TYPE); validation.max(photo.image.length(), MAX_FILE_SIZE); if (validation.hasErrors()) { validation.keep(); /* Remember errors after redirect. */} else { photo.save(); User user = user(); user.profile.profilePhoto = photo; user.profile.save(); } } catch(FileNotFoundException f) { setProfilePhotoPage();//for if try to put in null file } } setProfilePhotoPage();//for if try to put in null file } /** * set gravatar to the profile photo */ public static void setGravatar(String gravatarEmail) throws FileNotFoundException, IOException { //first takes the user's email and makes it into the correct hex string User u = user(); String hash = md5Hex((gravatarEmail.trim()).toLowerCase()); String urlPath = "http://www.gravatar.com/avatar/"+hash+".jpg"+ "?" +//parameters - "size=100&d=mm"; + "size=120&d=mm"; URL url = new URL(urlPath); BufferedImage image = ImageIO.read(url); if(u.profile.gravatarPhoto == null) { // don't yet have a gravatarPhoto try { File gravatar = new File(hash+".jpg"); ImageIO.write(image, "jpg",gravatar); if(gravatar != null) { Photo photo = new Photo(user(), gravatar); validation.match(photo.image.type(), IMAGE_TYPE); validation.max(photo.image.length(), MAX_FILE_SIZE); if (validation.hasErrors()) { validation.keep(); /* Remember errors after redirect. */} else { photo.save(); User user = user(); user.profile.profilePhoto = photo; //set gravatarPhoto id u.profile.gravatarPhoto = photo; user.profile.save(); } gravatar.delete(); } } catch(Exception f) { redirect("https://en.gravatar.com/site/signup/"); } } else { // have already added the gravatar picture, so we need to displace pic. Photo oldPhoto = Photo.findById(u.profile.gravatarPhoto.id); try{ File gravatar = new File(hash+".jpg"); ImageIO.write(image, "jpg",gravatar); if(gravatar != null){ oldPhoto.updateImage(gravatar); validation.match(oldPhoto.image.type(), IMAGE_TYPE); validation.max(oldPhoto.image.length(), MAX_FILE_SIZE); if (validation.hasErrors()) { validation.keep(); /* Remember errors after redirect. */} else { oldPhoto.save(); User user = user(); user.profile.profilePhoto = oldPhoto; //set gravatarPhoto id u.profile.gravatarPhoto = oldPhoto; user.profile.save(); } } gravatar.delete();//delete file. We don't need it } catch(Exception f) { redirect("https://en.gravatar.com/site/signup/"); } } //if reach here have successfully changed the gravatar so we reset the email u.profile.gravatarEmail = gravatarEmail; u.profile.save(); setProfilePhotoPage();//render page } /** * helper method for gravatar * makes String into md5hex * @param message * @return */ private static String md5Hex (String message) { try { MessageDigest md = MessageDigest.getInstance("MD5"); return Codec.byteToHexString(md.digest(message.getBytes("CP1252"))); } catch (NoSuchAlgorithmException e) { } catch (UnsupportedEncodingException e) { } return null; } }
true
true
public static void setGravatar(String gravatarEmail) throws FileNotFoundException, IOException { //first takes the user's email and makes it into the correct hex string User u = user(); String hash = md5Hex((gravatarEmail.trim()).toLowerCase()); String urlPath = "http://www.gravatar.com/avatar/"+hash+".jpg"+ "?" +//parameters "size=100&d=mm"; URL url = new URL(urlPath); BufferedImage image = ImageIO.read(url); if(u.profile.gravatarPhoto == null) { // don't yet have a gravatarPhoto try { File gravatar = new File(hash+".jpg"); ImageIO.write(image, "jpg",gravatar); if(gravatar != null) { Photo photo = new Photo(user(), gravatar); validation.match(photo.image.type(), IMAGE_TYPE); validation.max(photo.image.length(), MAX_FILE_SIZE); if (validation.hasErrors()) { validation.keep(); /* Remember errors after redirect. */} else { photo.save(); User user = user(); user.profile.profilePhoto = photo; //set gravatarPhoto id u.profile.gravatarPhoto = photo; user.profile.save(); } gravatar.delete(); } } catch(Exception f) { redirect("https://en.gravatar.com/site/signup/"); } } else { // have already added the gravatar picture, so we need to displace pic. Photo oldPhoto = Photo.findById(u.profile.gravatarPhoto.id); try{ File gravatar = new File(hash+".jpg"); ImageIO.write(image, "jpg",gravatar); if(gravatar != null){ oldPhoto.updateImage(gravatar); validation.match(oldPhoto.image.type(), IMAGE_TYPE); validation.max(oldPhoto.image.length(), MAX_FILE_SIZE); if (validation.hasErrors()) { validation.keep(); /* Remember errors after redirect. */} else { oldPhoto.save(); User user = user(); user.profile.profilePhoto = oldPhoto; //set gravatarPhoto id u.profile.gravatarPhoto = oldPhoto; user.profile.save(); } } gravatar.delete();//delete file. We don't need it } catch(Exception f) { redirect("https://en.gravatar.com/site/signup/"); } } //if reach here have successfully changed the gravatar so we reset the email u.profile.gravatarEmail = gravatarEmail; u.profile.save(); setProfilePhotoPage();//render page }
public static void setGravatar(String gravatarEmail) throws FileNotFoundException, IOException { //first takes the user's email and makes it into the correct hex string User u = user(); String hash = md5Hex((gravatarEmail.trim()).toLowerCase()); String urlPath = "http://www.gravatar.com/avatar/"+hash+".jpg"+ "?" +//parameters "size=120&d=mm"; URL url = new URL(urlPath); BufferedImage image = ImageIO.read(url); if(u.profile.gravatarPhoto == null) { // don't yet have a gravatarPhoto try { File gravatar = new File(hash+".jpg"); ImageIO.write(image, "jpg",gravatar); if(gravatar != null) { Photo photo = new Photo(user(), gravatar); validation.match(photo.image.type(), IMAGE_TYPE); validation.max(photo.image.length(), MAX_FILE_SIZE); if (validation.hasErrors()) { validation.keep(); /* Remember errors after redirect. */} else { photo.save(); User user = user(); user.profile.profilePhoto = photo; //set gravatarPhoto id u.profile.gravatarPhoto = photo; user.profile.save(); } gravatar.delete(); } } catch(Exception f) { redirect("https://en.gravatar.com/site/signup/"); } } else { // have already added the gravatar picture, so we need to displace pic. Photo oldPhoto = Photo.findById(u.profile.gravatarPhoto.id); try{ File gravatar = new File(hash+".jpg"); ImageIO.write(image, "jpg",gravatar); if(gravatar != null){ oldPhoto.updateImage(gravatar); validation.match(oldPhoto.image.type(), IMAGE_TYPE); validation.max(oldPhoto.image.length(), MAX_FILE_SIZE); if (validation.hasErrors()) { validation.keep(); /* Remember errors after redirect. */} else { oldPhoto.save(); User user = user(); user.profile.profilePhoto = oldPhoto; //set gravatarPhoto id u.profile.gravatarPhoto = oldPhoto; user.profile.save(); } } gravatar.delete();//delete file. We don't need it } catch(Exception f) { redirect("https://en.gravatar.com/site/signup/"); } } //if reach here have successfully changed the gravatar so we reset the email u.profile.gravatarEmail = gravatarEmail; u.profile.save(); setProfilePhotoPage();//render page }
diff --git a/src/cytoscape/actions/LoadBioDataServerAction.java b/src/cytoscape/actions/LoadBioDataServerAction.java index 10c63d0f2..2c15b1dad 100755 --- a/src/cytoscape/actions/LoadBioDataServerAction.java +++ b/src/cytoscape/actions/LoadBioDataServerAction.java @@ -1,61 +1,61 @@ //------------------------------------------------------------------------- // $Revision$ // $Date$ // $Author$ //------------------------------------------------------------------------- package cytoscape.actions; //------------------------------------------------------------------------- import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JFileChooser; import java.io.File; import cytoscape.view.NetworkView; import cytoscape.data.servers.BioDataServer; import cytoscape.data.Semantics; //------------------------------------------------------------------------- /** * Action allows the loading of a BioDataServer from the gui. * * added by dramage 2002-08-20 */ public class LoadBioDataServerAction extends AbstractAction { NetworkView networkView; public LoadBioDataServerAction(NetworkView networkView) { super("Bio Data Server..."); this.networkView = networkView; } public void actionPerformed(ActionEvent e) { File currentDirectory = networkView.getCytoscapeObj().getCurrentDirectory(); JFileChooser chooser = new JFileChooser(currentDirectory); - chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + //chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (chooser.showOpenDialog (networkView.getMainFrame()) == chooser.APPROVE_OPTION) { currentDirectory = chooser.getCurrentDirectory(); networkView.getCytoscapeObj().setCurrentDirectory(currentDirectory); String bioDataDirectory = chooser.getSelectedFile().toString(); BioDataServer bioDataServer = null; //bioDataServer = BioDataServerFactory.create (bioDataDirectory); try { bioDataServer = new BioDataServer (bioDataDirectory); networkView.getCytoscapeObj().setBioDataServer(bioDataServer); } catch (Exception e0) { String es = "cannot create new biodata server at " + bioDataDirectory; networkView.getCytoscapeObj().getLogger().warning(es); return; } //now that we have a bioDataServer, we probably want to use it to //provide naming services for the objects in the network. We delegate //to a static method that can handle this Semantics.applyNamingServices(networkView.getNetwork(), networkView.getCytoscapeObj()); //recalculating the appearances may be necessary if the above method //assigned new attributes networkView.redrawGraph(false, true); } } }
true
true
public void actionPerformed(ActionEvent e) { File currentDirectory = networkView.getCytoscapeObj().getCurrentDirectory(); JFileChooser chooser = new JFileChooser(currentDirectory); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (chooser.showOpenDialog (networkView.getMainFrame()) == chooser.APPROVE_OPTION) { currentDirectory = chooser.getCurrentDirectory(); networkView.getCytoscapeObj().setCurrentDirectory(currentDirectory); String bioDataDirectory = chooser.getSelectedFile().toString(); BioDataServer bioDataServer = null; //bioDataServer = BioDataServerFactory.create (bioDataDirectory); try { bioDataServer = new BioDataServer (bioDataDirectory); networkView.getCytoscapeObj().setBioDataServer(bioDataServer); } catch (Exception e0) { String es = "cannot create new biodata server at " + bioDataDirectory; networkView.getCytoscapeObj().getLogger().warning(es); return; } //now that we have a bioDataServer, we probably want to use it to //provide naming services for the objects in the network. We delegate //to a static method that can handle this Semantics.applyNamingServices(networkView.getNetwork(), networkView.getCytoscapeObj()); //recalculating the appearances may be necessary if the above method //assigned new attributes networkView.redrawGraph(false, true); } }
public void actionPerformed(ActionEvent e) { File currentDirectory = networkView.getCytoscapeObj().getCurrentDirectory(); JFileChooser chooser = new JFileChooser(currentDirectory); //chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (chooser.showOpenDialog (networkView.getMainFrame()) == chooser.APPROVE_OPTION) { currentDirectory = chooser.getCurrentDirectory(); networkView.getCytoscapeObj().setCurrentDirectory(currentDirectory); String bioDataDirectory = chooser.getSelectedFile().toString(); BioDataServer bioDataServer = null; //bioDataServer = BioDataServerFactory.create (bioDataDirectory); try { bioDataServer = new BioDataServer (bioDataDirectory); networkView.getCytoscapeObj().setBioDataServer(bioDataServer); } catch (Exception e0) { String es = "cannot create new biodata server at " + bioDataDirectory; networkView.getCytoscapeObj().getLogger().warning(es); return; } //now that we have a bioDataServer, we probably want to use it to //provide naming services for the objects in the network. We delegate //to a static method that can handle this Semantics.applyNamingServices(networkView.getNetwork(), networkView.getCytoscapeObj()); //recalculating the appearances may be necessary if the above method //assigned new attributes networkView.redrawGraph(false, true); } }
diff --git a/src/main/java/com/redhat/rcm/version/Cli.java b/src/main/java/com/redhat/rcm/version/Cli.java index 9eeb007..e1bd972 100644 --- a/src/main/java/com/redhat/rcm/version/Cli.java +++ b/src/main/java/com/redhat/rcm/version/Cli.java @@ -1,1169 +1,1169 @@ /* * Copyright (c) 2012 Red Hat, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see * <http://www.gnu.org/licenses>. */ package com.redhat.rcm.version; import static com.redhat.rcm.version.stats.VersionInfo.APP_BUILDER; import static com.redhat.rcm.version.stats.VersionInfo.APP_COMMIT_ID; import static com.redhat.rcm.version.stats.VersionInfo.APP_DESCRIPTION; import static com.redhat.rcm.version.stats.VersionInfo.APP_NAME; import static com.redhat.rcm.version.stats.VersionInfo.APP_TIMESTAMP; import static com.redhat.rcm.version.stats.VersionInfo.APP_VERSION; import static com.redhat.rcm.version.util.InputUtils.getClasspathResource; import static com.redhat.rcm.version.util.InputUtils.getFile; import static com.redhat.rcm.version.util.InputUtils.readClasspathProperties; import static com.redhat.rcm.version.util.InputUtils.readListProperty; import static com.redhat.rcm.version.util.InputUtils.readProperties; import static com.redhat.rcm.version.util.InputUtils.readPropertiesList; import static org.apache.commons.io.IOUtils.closeQuietly; import static org.apache.commons.lang.StringUtils.join; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.text.BreakIterator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.log4j.Appender; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.FileAppender; import org.apache.log4j.Layout; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.PatternLayout; import org.apache.log4j.spi.Configurator; import org.apache.log4j.spi.LoggerRepository; import org.apache.maven.mae.MAEException; import org.apache.maven.mae.project.key.FullProjectKey; import org.codehaus.plexus.util.StringUtils; import org.commonjava.util.logging.Logger; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import com.redhat.rcm.version.mgr.VersionManager; import com.redhat.rcm.version.mgr.mod.ProjectModder; import com.redhat.rcm.version.mgr.session.SessionBuilder; import com.redhat.rcm.version.mgr.session.VersionManagerSession; import com.redhat.rcm.version.util.InputUtils; import com.redhat.rcm.version.util.http.SSLUtils; public class Cli { @Argument( index = 0, metaVar = "target", usage = "POM file (or directory containing POM files) to modify." ) private File target = new File( System.getProperty( "user.dir" ), "pom.xml" ); @Option( name = "-b", aliases = "--boms", usage = "File containing a list of BOM URLs to use for standardizing dependencies.\nProperty file equivalent: boms" ) private File bomList; @Option( name = "-B", aliases = { "--bootstrap" }, usage = "Bootstrap properties to read for location of VMan configuration." ) private File bootstrapConfig; @Option( name = "-C", aliases = "--config", usage = "Load default configuration for BOMs, toolchain, removedPluginsList, etc. from this file/url." ) private String configuration; @Option( name = "-e", usage = "POM exclude path pattern (glob)" ) private String pomExcludePattern; @Option( name = "-E", usage = "POM exclude module list (groupId:artifactId,groupId:artifactId...)\nProperty file equivalent: pom-module-excludes" ) private String pomExcludeModules; @Option( name = "-h", aliases = { "--help" }, usage = "Print this message and quit" ) private boolean help; @Option( name = "-H", aliases = { "--help-modifications" }, usage = "Print the list of available modifications and quit" ) private boolean helpModders; @Option( name = "--console", usage = "Log information to console IN ADDITION TO <workspace>/vman.log.\n" ) private boolean console; @Option( name = "--no-console", usage = "DON'T log information to console in addition to <workspace>/vman.log.\n" ) private boolean noConsole; @Option( name = "--no-log-file", usage = "DON'T log information to <workspace>/vman.log.\n" ) private boolean noLogFile; @Option( name = "-L", aliases = { "--local-repo", "--local-repository" }, usage = "Local repository directory.\nDefault: <workspace>/local-repository\nProperty file equivalent: local-repository" ) private File localRepository; @Option( name = "-m", aliases = "--remote-repositories", usage = "Maven remote repositories from which load missing parent POMs.\nProperty file equivalent: remote-repositories." ) private String remoteRepositories; @Option( name = "-M", aliases = { "--enable-modifications" }, usage = "List of modifications to enable for this execution (see --help-modifications for more information)." ) private String modifications; @Option( name = "-O", aliases = { "--capture-output", "--capture-pom" }, usage = "Write captured (missing) definitions to this POM location.\nProperty file equivalent: capture-pom" ) private File capturePom; @Option( name = "-p", usage = "POM path pattern (glob).\nDefault: **/*.pom,**/pom.xml" ) private final String pomPattern = "**/*.pom,**/pom.xml"; @Option( name = "-P", aliases = { "--preserve" }, usage = "Write changed POMs back to original input files.\nDefault: false" ) private final boolean preserveFiles = false; @Option( name = "-r", aliases = { "--rm-plugins", "--removed-plugins" }, usage = "List of plugins (format: <groupId:artifactId>[,<groupId:artifactId>]) to REMOVE if found.\nProperty file equivalent: removed-plugins" ) private String removedPluginsList; @Option( name = "--removed-tests", usage = "List of test modules (format: <groupId:artifactId>[,<groupId:artifactId>]) to remove (via maven.test.skip) if found.\nProperty file equivalent: removed-tests" ) private String removedTestsList; @Option( name = "--extensions-whitelist", usage = "List of extensions (format: <groupId:artifactId>[,<groupId:artifactId>]) to preserve.\nProperty file equivalent: extensions-whitelist" ) private String extensionsWhitelistList; @Option( name = "-R", aliases = { "--report-dir" }, usage = "Write reports here.\nDefault: <workspace>/reports" ) private final File reports = new File( "vman-workspace/reports" ); @Option( name = "-s", aliases = "--version-suffix", usage = "A suffix to append to each POM's version.\nProperty file equivalent: version-suffix" ) private String versionSuffix; @Option( name = "--version-modifier", usage = "Change each POM's version using pattern:replacement format.\nProperty file equivalent: version-modifier" ) private String versionModifier; @Option( name = "--strict", usage = "Change ONLY the dependencies, plugins, and parents that are listed in BOMs and toolchain POM\nDefault: false\nProperty file equivalent: strict" ) private boolean strict = false; @Option( name = "-S", aliases = { "--settings" }, usage = "Maven settings.xml file/URL.\nProperty file equivalent: settings" ) private String settings; @Option( name = "-t", aliases = "--toolchain", usage = "Toolchain POM URL, containing standard plugin versions in the build/pluginManagement section, and plugin injections in the regular build/plugins section.\nProperty file equivalent: toolchain" ) private String toolchain; @Option( name = "-T", aliases = "--test-config", usage = "Test-load the configuration given, and print diagnostic information" ) private boolean testConfig; @Option( name = "-v", aliases = "--version", usage = "Show version information and quit." ) private boolean showVersion; @Option( name = "-W", aliases = { "--workspace" }, usage = "Backup original files here up before modifying.\nDefault: vman-workspace" ) private final File workspace = new File( "vman-workspace" ); @Option( name = "-Z", aliases = { "--no-system-exit" }, usage = "Don't call System.exit(..) with the return value (for embedding/testing)." ) private boolean noSystemExit; @Option( name = "--trustpath", usage = "Directory containing .pem files with certificates of servers to trust. (Use 'classpath:' prefix for a directory embedded in the jar.)" ) private String truststorePath = DEFAULT_TRUSTSTORE_PATH; @Option( name = "--use-effective-poms", usage = "Disable resolution of effective POMs for projects being modified (May be useful if parent POMs aren't resolvable)." ) private boolean useEffectivePoms = false; private static final String DEFAULT_TRUSTSTORE_PATH = "classpath:ssl/trust"; private static final File DEFAULT_CONFIG_FILE = new File( System.getProperty( "user.home" ), ".vman.properties" ); static final String BOOTSTRAP_PROPERTIES = "vman.boot.properties"; public static final String REMOTE_REPOSITORIES_PROPERTY = "remote-repositories"; @Deprecated public static final String REMOTE_REPOSITORY_PROPERTY = "remote-repository"; public static final String VERSION_SUFFIX_PROPERTY = "version-suffix"; public static final String VERSION_MODIFIER_PROPERTY = "version-modifier"; public static final String TOOLCHAIN_PROPERTY = "toolchain"; public static final String BOMS_LIST_PROPERTY = "boms"; public static final String REMOVED_PLUGINS_PROPERTY = "removed-plugins"; public static final String EXTENSIONS_WHITELIST_PROPERTY = "extensions-whitelist"; public static final String POM_EXCLUDE_MODULE_PROPERTY = "pom-module-excludes"; public static final String REMOVED_TESTS_PROPERTY = "removed-tests"; public static final String LOCAL_REPOSITORY_PROPERTY = "local-repository"; public static final String SETTINGS_PROPERTY = "settings"; public static final String CAPTURE_POM_PROPERTY = "capture-pom"; public static final String STRICT_MODE_PROPERTY = "strict"; public static final String MODIFICATIONS = "modifications"; public static final String RELOCATIONS_PROPERTY = "relocated-coordinates"; public static final String PROPERTY_MAPPINGS_PROPERTY = "property-mappings"; public static final String BOOT_CONFIG_PROPERTY = "configuration"; public static final String TRUSTSTORE_PATH_PROPERTY = "truststore-path"; public static final String USE_EFFECTIVE_POMS_PROPERTY = "use-effective-poms"; private static final File DEFAULT_BOOTSTRAP_CONFIG = new File( System.getProperty( "user.home" ), ".vman.boot.properties" ); private static VersionManager vman; private List<String> boms; private List<String> removedPlugins; private List<String> extensionsWhitelist; private List<String> removedTests; private List<String> modders; private Map<String, String> relocatedCoords; private Map<String, String> propertyMappings; private String bootstrapLocation; private String configLocation; private boolean bootstrapRead; private final File logFile = new File( workspace, "vman.log" ); private static int exitValue = Integer.MIN_VALUE; public static void main( final String[] args ) { final Cli cli = new Cli(); final CmdLineParser parser = new CmdLineParser( cli ); try { parser.parseArgument( args ); final boolean useLog = !( cli.noLogFile || cli.testConfig || /*cli.help ||*/cli.helpModders || cli.showVersion ); // System.out.printf( "--no-console: %s \n\n--no-log-file: %s \n--test-config: %s\n--help: %s\n--help-modifications: %s\n--version: %s\nlogfile: %s\n\nUse logfile? %s\n\n", // cli.noConsole, cli.noLogFile, cli.testConfig, cli.help, cli.helpModders, // cli.showVersion, cli.logFile, useLog ); configureLogging( !cli.noConsole, useLog, cli.logFile ); new Logger( Cli.class ).info( "Testing log appenders..." ); vman = VersionManager.getInstance(); exitValue = 0; if ( cli.help ) { printUsage( parser, null ); } else if ( cli.helpModders ) { printModders(); } else if ( cli.showVersion ) { printVersionInfo(); } else if ( cli.testConfig ) { cli.testConfigAndPrintDiags(); } else { exitValue = cli.run(); } if ( !cli.noSystemExit ) { System.exit( exitValue ); } } catch ( final CmdLineException error ) { printUsage( parser, error ); } catch ( final MAEException e ) { printUsage( parser, e ); } catch ( final MalformedURLException e ) { printUsage( parser, e ); } } public Cli( final File target, final File bomList ) { this.target = target; this.bomList = bomList; } public Cli() { } private void testConfigAndPrintDiags() { VersionManagerSession session = null; final List<VManException> errors = new ArrayList<VManException>(); try { session = initSession(); } catch ( final VManException e ) { errors.add( e ); } if ( session != null ) { try { vman.configureSession( boms, toolchain, session ); } catch ( final VManException e ) { errors.add( e ); } } final FullProjectKey toolchainKey = session == null ? null : session.getToolchainKey(); final List<FullProjectKey> bomCoords = session == null ? null : session.getBomCoords(); final LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>(); map.put( "Bootstrap location:", bootstrapLocation ); map.put( "Bootstrap read?", bootstrapRead ); map.put( "Config location:", configLocation ); map.put( "", "" ); map.put( " ", "" ); map.put( "Toolchain location:", toolchain ); map.put( "Toolchain:", toolchainKey ); map.put( " ", "" ); map.put( "BOM locations:", boms ); map.put( "BOMs:", bomCoords ); map.put( " ", "" ); map.put( " ", "" ); map.put( "Settings.xml:", settings ); map.put( "Remote repo:", remoteRepositories ); System.out.println( "Version information:\n-------------------------------------------------\n\n" ); printVersionInfo(); System.out.printf( "Diagnostics:\n-------------------------------------------------\n\n" ); int max = 0; for ( final String key : map.keySet() ) { max = Math.max( max, key.length() ); } final StringBuilder indent = new StringBuilder(); for ( int i = 0; i < max + 4; i++ ) { indent.append( ' ' ); } final int descMax = 75 - max; final String fmt = "%-" + max + "s %-" + descMax + "s\n"; for ( final Map.Entry<String, Object> entry : map.entrySet() ) { final Object value = entry.getValue(); String val = value == null ? "-NONE-" : String.valueOf( value ); if ( value instanceof Collection<?> ) { final Collection<?> coll = ( (Collection<?>) value ); if ( coll.isEmpty() ) { val = "-NONE-"; } else { val = join( coll, "\n" + indent ) + "\n"; } } System.out.printf( fmt, entry.getKey(), val ); } System.out.println(); System.out.printf( "Errors:\n-------------------------------------------------\n%s\n\n", errors.isEmpty() ? "-NONE" : join( errors, "\n\n" ) ); System.out.println(); } private static void configureLogging( boolean useConsole, final boolean useLogFile, final File logFile ) { System.out.println( "Log file is: " + logFile.getAbsolutePath() ); final Layout layout = new PatternLayout( "%5p [%t] - %m%n" ); final List<AppenderSkeleton> appenders = new ArrayList<AppenderSkeleton>(); if ( !useConsole && !useLogFile ) { if ( !useLogFile ) { System.out.println( "\n\nNOTE: --no-console option has been OVERRIDDEN since --no-log-file option was also provided.\nOutputting to console ONLY.\n" ); useConsole = true; } } if ( useConsole ) { final ConsoleAppender console = new ConsoleAppender( layout ); console.setName( "console" ); console.setThreshold( Level.ALL ); appenders.add( console ); } if ( useLogFile ) { System.out.println( "\n\nNOTE: See " + logFile + " for a COPY of console output.\n" ); try { final File dir = logFile.getParentFile(); if ( dir != null && !dir.isDirectory() && !dir.mkdirs() ) { throw new RuntimeException( "Failed to create parent directory for logfile: " + dir.getAbsolutePath() ); } final FileAppender file = new FileAppender( layout, logFile.getPath() ); file.setName( "logfile" ); file.setThreshold( Level.ALL ); appenders.add( file ); } catch ( final IOException e ) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter( sw ); e.printStackTrace( pw ); System.out.printf( "ERROR: Failed to initialize log file: %s. Reason: %s\n\n%s\n\n", logFile, e.getMessage(), sw.toString() ); throw new RuntimeException( "Failed to initialize logfile." ); } } // Clear the logfile for the next run. if ( logFile != null ) { logFile.delete(); } final Configurator log4jConfigurator = new Configurator() { @Override public void doConfigure( final URL notUsed, final LoggerRepository repo ) { final Level level = Level.INFO; repo.setThreshold( level ); final org.apache.log4j.Logger root = repo.getRootLogger(); root.removeAllAppenders(); root.setLevel( level ); for ( final AppenderSkeleton appender : appenders ) { appender.setThreshold( Level.ALL ); root.addAppender( appender ); } @SuppressWarnings( "unchecked" ) final ArrayList<Appender> allRoot = Collections.list( root.getAllAppenders() ); for ( final Appender appender : allRoot ) { System.out.println( "ROOT has appender: " + appender.getName() ); } } }; log4jConfigurator.doConfigure( null, LogManager.getLoggerRepository() ); } public int run() throws MAEException, VManException, MalformedURLException { final Logger logger = new Logger( getClass() ); final VersionManagerSession session = initSession(); if ( boms == null || boms.isEmpty() ) { logger.error( "You must specify at least one BOM." ); return -2; } if ( session.getErrors() .isEmpty() ) { logger.info( "Modifying POM(s).\n\nTarget:\n\t" + target + "\n\nBOMs:\n\t" + StringUtils.join( boms.iterator(), "\n\t" ) + "\n\nWorkspace:\n\t" + workspace + "\n\nReports:\n\t" + reports ); if ( target.isDirectory() ) { vman.modifyVersions( target, pomPattern, pomExcludePattern, boms, toolchain, session ); } else { vman.modifyVersions( target, boms, toolchain, session ); } } reports.mkdirs(); vman.generateReports( reports, session ); if ( capturePom != null && capturePom.exists() ) { logger.warn( "\n\n\n\n\nMissing dependency/plugin information has been captured in:\n\n\t" + capturePom.getAbsolutePath() + "\n\n\n\n" ); return -1; } else { final List<Throwable> errors = session.getErrors(); if ( errors != null && !errors.isEmpty() ) { logger.error( errors.size() + " errors detected!\n\n" ); int i = 1; for ( final Throwable error : errors ) { logger.error( "\n\n" + i, error ); i++; } return -1; } } return 0; } private VersionManagerSession initSession() throws VManException { SSLUtils.initSSLContext( truststorePath ); loadConfiguration(); loadBomList(); loadPlugins(); loadAndNormalizeModifications(); final Logger logger = new Logger( getClass() ); logger.info( "modifications = " + join( modders, " " ) ); final SessionBuilder builder = new SessionBuilder( workspace, reports ).withVersionSuffix( versionSuffix ) .withVersionModifier( versionModifier ) .withRemovedPlugins( removedPlugins ) .withRemovedTests( removedTests ) .withExtensionsWhitelist( extensionsWhitelist ) .withModders( modders ) .withPreserveFiles( preserveFiles ) .withStrict( strict ) .withCoordinateRelocations( relocatedCoords ) .withPropertyMappings( propertyMappings ) .withExcludedModulePoms( pomExcludeModules ) .withUseEffectivePoms( useEffectivePoms ); final VersionManagerSession session = builder.build(); if ( remoteRepositories != null ) { try { session.setRemoteRepositories( remoteRepositories ); } catch ( final MalformedURLException e ) { throw new VManException( "Cannot initialize remote repositories: %s. Error: %s", e, remoteRepositories, e.getMessage() ); } } if ( settings != null ) { session.setSettingsXml( settings ); } if ( localRepository == null ) { localRepository = new File( workspace, "local-repository" ); } session.setLocalRepositoryDirectory( localRepository ); if ( capturePom != null ) { session.setCapturePom( capturePom ); } return session; } private static void printVersionInfo() { final StringBuilder sb = new StringBuilder(); sb.append( APP_NAME ) .append( "\n\n" ) .append( APP_DESCRIPTION ) .append( "\n\n" ); final LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>(); map.put( "Built By:", APP_BUILDER ); map.put( "Commit ID:", APP_COMMIT_ID ); map.put( "Built On:", APP_TIMESTAMP ); map.put( "Version:", APP_VERSION ); sb.append( formatHelpMap( map, "\n" ) ); sb.append( "\n\n" ); System.out.println( sb.toString() ); } private static void printModders() { final Map<String, ProjectModder> modders = vman.getModders(); final List<String> keys = new ArrayList<String>( modders.keySet() ); Collections.sort( keys ); final LinkedHashMap<String, Object> props = new LinkedHashMap<String, Object>(); for ( final String key : keys ) { props.put( key, modders.get( key ) .getDescription() ); } final StringBuilder sb = new StringBuilder(); sb.append( "The following project modifications are available: " ); sb.append( formatHelpMap( props, "\n\n" ) ); sb.append( "\n\nNOTE: To ADD any of these modifiers to the standard list, use the notation '--modifications=+<modifier-id>' (prefixed with '+') or for the properties file use 'modifications=+...'.\n\nThe standard modifiers are: " ); for ( final String key : ProjectModder.STANDARD_MODIFICATIONS ) { sb.append( String.format( "\n - %s", key ) ); } sb.append( "\n\n" ); System.out.println( sb ); } private static String formatHelpMap( final LinkedHashMap<String, Object> map, final String itemSeparator ) { int max = 0; for ( final String key : map.keySet() ) { max = Math.max( max, key.length() ); } final int descMax = 75 - max; final String fmt = "%-" + max + "s %-" + descMax + "s" + itemSeparator; final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter( sw ); final List<String> lines = new ArrayList<String>(); for ( final Map.Entry<String, Object> entry : map.entrySet() ) { final String key = entry.getKey(); final String description = entry.getValue() == null ? "-NONE-" : String.valueOf( entry.getValue() ); lines.clear(); final BreakIterator iter = BreakIterator.getLineInstance(); iter.setText( description ); int start = iter.first(); int end = BreakIterator.DONE; final StringBuilder currentLine = new StringBuilder(); String seg; while ( start != BreakIterator.DONE && ( end = iter.next() ) != BreakIterator.DONE ) { seg = description.substring( start, end ); if ( currentLine.length() + seg.length() > descMax ) { lines.add( currentLine.toString() ); currentLine.setLength( 0 ); } currentLine.append( seg ); start = end; } if ( currentLine.length() > 0 ) { lines.add( currentLine.toString() ); } pw.printf( fmt, key, lines.isEmpty() ? "" : lines.get( 0 ) ); if ( lines.size() > 1 ) { for ( int i = 1; i < lines.size(); i++ ) { pw.printf( fmt, "", lines.get( i ) ); } } } return sw.toString(); } private void loadPlugins() { if ( extensionsWhitelistList == null && extensionsWhitelistList != null ) { final String[] ls = extensionsWhitelistList.split( "\\s*,\\s*" ); extensionsWhitelist = Arrays.asList( ls ); } if ( removedPlugins == null && removedPluginsList != null ) { final String[] ls = removedPluginsList.split( "\\s*,\\s*" ); removedPlugins = Arrays.asList( ls ); } if ( removedTests == null && removedTestsList != null ) { final String[] ls = removedTestsList.split( "\\s*,\\s*" ); removedTests = Arrays.asList( ls ); } } private void loadAndNormalizeModifications() { if ( modifications != null ) { final String[] ls = modifications.split( "\\s*,\\s*" ); modders = new ArrayList<String>(); for ( final String modder : ls ) { if ( !modders.contains( modder ) ) { modders.add( modder ); } } } final List<String> mods = new ArrayList<String>(); boolean loadStandards = modders == null; if ( modders != null ) { if ( !modders.isEmpty() && modders.iterator() .next() .startsWith( "+" ) ) { loadStandards = true; } for ( final String key : modders ) { if ( ProjectModder.STANDARD_MODS_ALIAS.equals( key ) ) { loadStandards = true; } else if ( key.startsWith( "+" ) ) { if ( key.length() > 1 ) { mods.add( key.substring( 1 ) .trim() ); } } else { mods.add( key ); } } } if ( loadStandards ) { mods.addAll( Arrays.asList( ProjectModder.STANDARD_MODIFICATIONS ) ); } modders = mods; } private void loadConfiguration() throws VManException { final Logger logger = new Logger( getClass() ); File config = null; if ( configuration != null ) { config = InputUtils.getFile( configuration, workspace ); } if ( config == null ) { config = loadBootstrapConfig(); } if ( config == null ) { configLocation = DEFAULT_CONFIG_FILE.getAbsolutePath(); config = DEFAULT_CONFIG_FILE; } if ( config != null && config.canRead() ) { InputStream is = null; try { is = new FileInputStream( config ); final Properties props = new Properties(); props.load( is ); final StringWriter sWriter = new StringWriter(); for ( final Enumeration<?> e = props.propertyNames(); e.hasMoreElements(); ) { final String key = (String) e.nextElement(); sWriter.write( " " ); sWriter.write( key ); sWriter.write( " = " ); sWriter.write( props.getProperty( key ) ); sWriter.write( "\n" ); } props.list( new PrintWriter( sWriter ) ); logger.info( "Loading configuration from: " + config + ":\n\n" + sWriter ); final File downloadsDir = VersionManagerSession.getDownloadsDir( workspace ); final List<String> relocations = readListProperty( props, RELOCATIONS_PROPERTY ); if ( relocations != null ) { relocatedCoords = readPropertiesList( relocations, downloadsDir, true ); } else { relocatedCoords = new HashMap<String, String>(); } final List<String> mappingsLocations = readListProperty( props, PROPERTY_MAPPINGS_PROPERTY ); if ( propertyMappings != null ) { this.propertyMappings = readPropertiesList( mappingsLocations, downloadsDir, true ); } else { this.propertyMappings = new HashMap<String, String>(); } if ( removedPluginsList == null ) { removedPlugins = readListProperty( props, REMOVED_PLUGINS_PROPERTY ); } if ( removedTestsList == null ) { removedTests = readListProperty( props, REMOVED_TESTS_PROPERTY ); } if ( extensionsWhitelistList == null ) { extensionsWhitelist = readListProperty( props, EXTENSIONS_WHITELIST_PROPERTY ); } if ( pomExcludeModules == null ) { pomExcludeModules = props.getProperty( POM_EXCLUDE_MODULE_PROPERTY ); } if ( modifications == null ) { final List<String> lst = readListProperty( props, MODIFICATIONS ); logger.info( "modifications from properties: '" + join( lst, " " ) + "'" ); if ( lst != null ) { modders = modders == null ? new ArrayList<String>() : new ArrayList<String>( modders ); modders.addAll( lst ); } } if ( bomList == null ) { if ( boms == null ) { boms = new ArrayList<String>(); } final List<String> pBoms = readListProperty( props, BOMS_LIST_PROPERTY ); if ( pBoms != null ) { boms.addAll( pBoms ); } } if ( toolchain == null ) { toolchain = props.getProperty( TOOLCHAIN_PROPERTY ); if ( toolchain != null ) { toolchain = toolchain.trim(); } } if ( versionSuffix == null ) { versionSuffix = props.getProperty( VERSION_SUFFIX_PROPERTY ); if ( versionSuffix != null ) { versionSuffix = versionSuffix.trim(); } } if ( versionModifier == null ) { versionModifier = props.getProperty( VERSION_MODIFIER_PROPERTY ); if ( versionModifier != null ) { versionModifier = versionModifier.trim(); } } if ( remoteRepositories == null ) { remoteRepositories = props.getProperty( REMOTE_REPOSITORIES_PROPERTY ); if ( remoteRepositories != null ) { remoteRepositories = remoteRepositories.trim(); } else { remoteRepositories = props.getProperty( REMOTE_REPOSITORY_PROPERTY ); if ( remoteRepositories != null ) { logger.warn( "Using deprecated " + REMOTE_REPOSITORY_PROPERTY ); remoteRepositories = remoteRepositories.trim(); } } } if ( settings == null ) { final String s = props.getProperty( SETTINGS_PROPERTY ); if ( s != null ) { settings = s; } } if ( localRepository == null ) { final String l = props.getProperty( LOCAL_REPOSITORY_PROPERTY ); if ( l != null ) { localRepository = new File( l ); } } if ( capturePom == null ) { final String p = props.getProperty( CAPTURE_POM_PROPERTY ); if ( p != null ) { capturePom = new File( p ); } } if ( !strict ) { strict = Boolean.valueOf( props.getProperty( STRICT_MODE_PROPERTY, Boolean.toString( Boolean.FALSE ) ) ); } if ( !useEffectivePoms ) { useEffectivePoms = - !Boolean.valueOf( props.getProperty( USE_EFFECTIVE_POMS_PROPERTY, - Boolean.toString( Boolean.FALSE ) ) ); + Boolean.valueOf( props.getProperty( USE_EFFECTIVE_POMS_PROPERTY, + Boolean.toString( Boolean.FALSE ) ) ); } if ( truststorePath == null ) { truststorePath = props.getProperty( TRUSTSTORE_PATH_PROPERTY ); } } catch ( final IOException e ) { throw new VManException( "Failed to load configuration from: " + config, e ); } finally { closeQuietly( is ); } } else { configLocation = "command-line"; } } /** * Try to load bootstrap configuration using the following order or preference: * 1. configured file (using -B option) * 2. default file ($HOME/.vman.boot.properties) * 3. embedded resource (classpath:bootstrap.properties) * * @return The configuration file referenced by the bootstrap properties, or null if no bootstrap properties is * found. * * @throws VManException In cases where the specified bootstrap properties file is unreadable. */ private File loadBootstrapConfig() throws VManException { final Logger logger = new Logger( getClass() ); Map<String, String> bootProps = null; if ( bootstrapConfig == null ) { if ( DEFAULT_BOOTSTRAP_CONFIG.exists() && DEFAULT_BOOTSTRAP_CONFIG.canRead() ) { logger.info( "Reading bootstrap info from: " + DEFAULT_BOOTSTRAP_CONFIG ); bootstrapLocation = "file:" + DEFAULT_BOOTSTRAP_CONFIG.getAbsolutePath(); bootProps = readProperties( DEFAULT_BOOTSTRAP_CONFIG ); } else { logger.info( "Reading bootstrap info from classpath resource: " + BOOTSTRAP_PROPERTIES ); final URL resource = getClasspathResource( BOOTSTRAP_PROPERTIES ); if ( resource != null ) { bootstrapLocation = "classpath:" + resource; bootProps = readClasspathProperties( BOOTSTRAP_PROPERTIES ); } } } else { if ( !bootstrapConfig.exists() || !bootstrapConfig.canRead() ) { throw new VManException( "Cannot read bootstrap from: " + bootstrapConfig ); } else { logger.info( "Reading bootstrap info from: " + bootstrapConfig ); bootstrapLocation = "file:" + bootstrapConfig.getAbsolutePath(); bootProps = readProperties( bootstrapConfig ); } } bootstrapRead = bootProps != null; if ( bootProps != null ) { configLocation = bootProps.get( BOOT_CONFIG_PROPERTY ); if ( configLocation != null ) { logger.info( "Reading configuration from: " + configLocation ); try { final File file = getFile( configLocation, new File( System.getProperty( "java.io.tmpdir" ) ), true ); logger.info( "...downloaded to file: " + file ); return file; } catch ( final VManException e ) { logger.error( "Failed to download configuration from: " + configLocation + ". Reason: " + e.getMessage(), e ); throw e; } } } return null; } private void loadBomList() throws VManException { if ( boms == null ) { boms = new ArrayList<String>(); } if ( bomList != null && bomList.canRead() ) { BufferedReader reader = null; try { reader = new BufferedReader( new FileReader( bomList ) ); String line = null; while ( ( line = reader.readLine() ) != null ) { boms.add( line.trim() ); } } catch ( final IOException e ) { throw new VManException( "Failed to read bom list from: " + bomList, e ); } finally { closeQuietly( reader ); } } } private static void printUsage( final CmdLineParser parser, final Exception error ) { if ( error != null ) { System.err.println( "Invalid option(s): " + error.getMessage() ); System.err.println(); } System.err.println( "Usage: $0 [OPTIONS] [<target-path>]" ); System.err.println(); System.err.println(); // If we are running under a Linux shell COLUMNS might be available for the width // of the terminal. parser.setUsageWidth( ( System.getenv( "COLUMNS" ) == null ? 100 : Integer.valueOf( System.getenv( "COLUMNS" ) ) ) ); parser.printUsage( System.err ); System.err.println(); } }
true
true
private void loadConfiguration() throws VManException { final Logger logger = new Logger( getClass() ); File config = null; if ( configuration != null ) { config = InputUtils.getFile( configuration, workspace ); } if ( config == null ) { config = loadBootstrapConfig(); } if ( config == null ) { configLocation = DEFAULT_CONFIG_FILE.getAbsolutePath(); config = DEFAULT_CONFIG_FILE; } if ( config != null && config.canRead() ) { InputStream is = null; try { is = new FileInputStream( config ); final Properties props = new Properties(); props.load( is ); final StringWriter sWriter = new StringWriter(); for ( final Enumeration<?> e = props.propertyNames(); e.hasMoreElements(); ) { final String key = (String) e.nextElement(); sWriter.write( " " ); sWriter.write( key ); sWriter.write( " = " ); sWriter.write( props.getProperty( key ) ); sWriter.write( "\n" ); } props.list( new PrintWriter( sWriter ) ); logger.info( "Loading configuration from: " + config + ":\n\n" + sWriter ); final File downloadsDir = VersionManagerSession.getDownloadsDir( workspace ); final List<String> relocations = readListProperty( props, RELOCATIONS_PROPERTY ); if ( relocations != null ) { relocatedCoords = readPropertiesList( relocations, downloadsDir, true ); } else { relocatedCoords = new HashMap<String, String>(); } final List<String> mappingsLocations = readListProperty( props, PROPERTY_MAPPINGS_PROPERTY ); if ( propertyMappings != null ) { this.propertyMappings = readPropertiesList( mappingsLocations, downloadsDir, true ); } else { this.propertyMappings = new HashMap<String, String>(); } if ( removedPluginsList == null ) { removedPlugins = readListProperty( props, REMOVED_PLUGINS_PROPERTY ); } if ( removedTestsList == null ) { removedTests = readListProperty( props, REMOVED_TESTS_PROPERTY ); } if ( extensionsWhitelistList == null ) { extensionsWhitelist = readListProperty( props, EXTENSIONS_WHITELIST_PROPERTY ); } if ( pomExcludeModules == null ) { pomExcludeModules = props.getProperty( POM_EXCLUDE_MODULE_PROPERTY ); } if ( modifications == null ) { final List<String> lst = readListProperty( props, MODIFICATIONS ); logger.info( "modifications from properties: '" + join( lst, " " ) + "'" ); if ( lst != null ) { modders = modders == null ? new ArrayList<String>() : new ArrayList<String>( modders ); modders.addAll( lst ); } } if ( bomList == null ) { if ( boms == null ) { boms = new ArrayList<String>(); } final List<String> pBoms = readListProperty( props, BOMS_LIST_PROPERTY ); if ( pBoms != null ) { boms.addAll( pBoms ); } } if ( toolchain == null ) { toolchain = props.getProperty( TOOLCHAIN_PROPERTY ); if ( toolchain != null ) { toolchain = toolchain.trim(); } } if ( versionSuffix == null ) { versionSuffix = props.getProperty( VERSION_SUFFIX_PROPERTY ); if ( versionSuffix != null ) { versionSuffix = versionSuffix.trim(); } } if ( versionModifier == null ) { versionModifier = props.getProperty( VERSION_MODIFIER_PROPERTY ); if ( versionModifier != null ) { versionModifier = versionModifier.trim(); } } if ( remoteRepositories == null ) { remoteRepositories = props.getProperty( REMOTE_REPOSITORIES_PROPERTY ); if ( remoteRepositories != null ) { remoteRepositories = remoteRepositories.trim(); } else { remoteRepositories = props.getProperty( REMOTE_REPOSITORY_PROPERTY ); if ( remoteRepositories != null ) { logger.warn( "Using deprecated " + REMOTE_REPOSITORY_PROPERTY ); remoteRepositories = remoteRepositories.trim(); } } } if ( settings == null ) { final String s = props.getProperty( SETTINGS_PROPERTY ); if ( s != null ) { settings = s; } } if ( localRepository == null ) { final String l = props.getProperty( LOCAL_REPOSITORY_PROPERTY ); if ( l != null ) { localRepository = new File( l ); } } if ( capturePom == null ) { final String p = props.getProperty( CAPTURE_POM_PROPERTY ); if ( p != null ) { capturePom = new File( p ); } } if ( !strict ) { strict = Boolean.valueOf( props.getProperty( STRICT_MODE_PROPERTY, Boolean.toString( Boolean.FALSE ) ) ); } if ( !useEffectivePoms ) { useEffectivePoms = !Boolean.valueOf( props.getProperty( USE_EFFECTIVE_POMS_PROPERTY, Boolean.toString( Boolean.FALSE ) ) ); } if ( truststorePath == null ) { truststorePath = props.getProperty( TRUSTSTORE_PATH_PROPERTY ); } } catch ( final IOException e ) { throw new VManException( "Failed to load configuration from: " + config, e ); } finally { closeQuietly( is ); } } else { configLocation = "command-line"; } }
private void loadConfiguration() throws VManException { final Logger logger = new Logger( getClass() ); File config = null; if ( configuration != null ) { config = InputUtils.getFile( configuration, workspace ); } if ( config == null ) { config = loadBootstrapConfig(); } if ( config == null ) { configLocation = DEFAULT_CONFIG_FILE.getAbsolutePath(); config = DEFAULT_CONFIG_FILE; } if ( config != null && config.canRead() ) { InputStream is = null; try { is = new FileInputStream( config ); final Properties props = new Properties(); props.load( is ); final StringWriter sWriter = new StringWriter(); for ( final Enumeration<?> e = props.propertyNames(); e.hasMoreElements(); ) { final String key = (String) e.nextElement(); sWriter.write( " " ); sWriter.write( key ); sWriter.write( " = " ); sWriter.write( props.getProperty( key ) ); sWriter.write( "\n" ); } props.list( new PrintWriter( sWriter ) ); logger.info( "Loading configuration from: " + config + ":\n\n" + sWriter ); final File downloadsDir = VersionManagerSession.getDownloadsDir( workspace ); final List<String> relocations = readListProperty( props, RELOCATIONS_PROPERTY ); if ( relocations != null ) { relocatedCoords = readPropertiesList( relocations, downloadsDir, true ); } else { relocatedCoords = new HashMap<String, String>(); } final List<String> mappingsLocations = readListProperty( props, PROPERTY_MAPPINGS_PROPERTY ); if ( propertyMappings != null ) { this.propertyMappings = readPropertiesList( mappingsLocations, downloadsDir, true ); } else { this.propertyMappings = new HashMap<String, String>(); } if ( removedPluginsList == null ) { removedPlugins = readListProperty( props, REMOVED_PLUGINS_PROPERTY ); } if ( removedTestsList == null ) { removedTests = readListProperty( props, REMOVED_TESTS_PROPERTY ); } if ( extensionsWhitelistList == null ) { extensionsWhitelist = readListProperty( props, EXTENSIONS_WHITELIST_PROPERTY ); } if ( pomExcludeModules == null ) { pomExcludeModules = props.getProperty( POM_EXCLUDE_MODULE_PROPERTY ); } if ( modifications == null ) { final List<String> lst = readListProperty( props, MODIFICATIONS ); logger.info( "modifications from properties: '" + join( lst, " " ) + "'" ); if ( lst != null ) { modders = modders == null ? new ArrayList<String>() : new ArrayList<String>( modders ); modders.addAll( lst ); } } if ( bomList == null ) { if ( boms == null ) { boms = new ArrayList<String>(); } final List<String> pBoms = readListProperty( props, BOMS_LIST_PROPERTY ); if ( pBoms != null ) { boms.addAll( pBoms ); } } if ( toolchain == null ) { toolchain = props.getProperty( TOOLCHAIN_PROPERTY ); if ( toolchain != null ) { toolchain = toolchain.trim(); } } if ( versionSuffix == null ) { versionSuffix = props.getProperty( VERSION_SUFFIX_PROPERTY ); if ( versionSuffix != null ) { versionSuffix = versionSuffix.trim(); } } if ( versionModifier == null ) { versionModifier = props.getProperty( VERSION_MODIFIER_PROPERTY ); if ( versionModifier != null ) { versionModifier = versionModifier.trim(); } } if ( remoteRepositories == null ) { remoteRepositories = props.getProperty( REMOTE_REPOSITORIES_PROPERTY ); if ( remoteRepositories != null ) { remoteRepositories = remoteRepositories.trim(); } else { remoteRepositories = props.getProperty( REMOTE_REPOSITORY_PROPERTY ); if ( remoteRepositories != null ) { logger.warn( "Using deprecated " + REMOTE_REPOSITORY_PROPERTY ); remoteRepositories = remoteRepositories.trim(); } } } if ( settings == null ) { final String s = props.getProperty( SETTINGS_PROPERTY ); if ( s != null ) { settings = s; } } if ( localRepository == null ) { final String l = props.getProperty( LOCAL_REPOSITORY_PROPERTY ); if ( l != null ) { localRepository = new File( l ); } } if ( capturePom == null ) { final String p = props.getProperty( CAPTURE_POM_PROPERTY ); if ( p != null ) { capturePom = new File( p ); } } if ( !strict ) { strict = Boolean.valueOf( props.getProperty( STRICT_MODE_PROPERTY, Boolean.toString( Boolean.FALSE ) ) ); } if ( !useEffectivePoms ) { useEffectivePoms = Boolean.valueOf( props.getProperty( USE_EFFECTIVE_POMS_PROPERTY, Boolean.toString( Boolean.FALSE ) ) ); } if ( truststorePath == null ) { truststorePath = props.getProperty( TRUSTSTORE_PATH_PROPERTY ); } } catch ( final IOException e ) { throw new VManException( "Failed to load configuration from: " + config, e ); } finally { closeQuietly( is ); } } else { configLocation = "command-line"; } }
diff --git a/src/main/java/zhenghui/jvm/Main.java b/src/main/java/zhenghui/jvm/Main.java index 8bf0deb..8d76826 100644 --- a/src/main/java/zhenghui/jvm/Main.java +++ b/src/main/java/zhenghui/jvm/Main.java @@ -1,33 +1,36 @@ package zhenghui.jvm; import zhenghui.jvm.parse.BaseInfoParse; import zhenghui.jvm.parse.ConstantPoolParse; import zhenghui.jvm.parse.ParseResult; /** * * User: zhenghui * Date: 13-1-10 * Time: ����2:19 * */ public class Main { public static void main(String[] args) throws Exception { ClassLoader cl = new ClassLoader(); String code = cl.loadClass("d:\\Test.class"); + //������Ϣ BaseInfoParse baseInfoParse = new BaseInfoParse(code); for(String str : baseInfoParse.parseBaseInfo()){ System.out.println(str); } + //������ ConstantPoolParse constantPoolParse = new ConstantPoolParse(code); ParseResult result = constantPoolParse.pareContantPool(); for(String str : result.getStrs()){ System.out.println(str); } + //���ʱ�� result = baseInfoParse.parseAccessFlags(result.getHandle()); for(String str : result.getStrs()){ System.out.println(str); } } }
false
true
public static void main(String[] args) throws Exception { ClassLoader cl = new ClassLoader(); String code = cl.loadClass("d:\\Test.class"); BaseInfoParse baseInfoParse = new BaseInfoParse(code); for(String str : baseInfoParse.parseBaseInfo()){ System.out.println(str); } ConstantPoolParse constantPoolParse = new ConstantPoolParse(code); ParseResult result = constantPoolParse.pareContantPool(); for(String str : result.getStrs()){ System.out.println(str); } result = baseInfoParse.parseAccessFlags(result.getHandle()); for(String str : result.getStrs()){ System.out.println(str); } }
public static void main(String[] args) throws Exception { ClassLoader cl = new ClassLoader(); String code = cl.loadClass("d:\\Test.class"); //������Ϣ BaseInfoParse baseInfoParse = new BaseInfoParse(code); for(String str : baseInfoParse.parseBaseInfo()){ System.out.println(str); } //������ ConstantPoolParse constantPoolParse = new ConstantPoolParse(code); ParseResult result = constantPoolParse.pareContantPool(); for(String str : result.getStrs()){ System.out.println(str); } //���ʱ�� result = baseInfoParse.parseAccessFlags(result.getHandle()); for(String str : result.getStrs()){ System.out.println(str); } }
diff --git a/src/graphics/Sprite.java b/src/graphics/Sprite.java index a9b712a..4dadfef 100644 --- a/src/graphics/Sprite.java +++ b/src/graphics/Sprite.java @@ -1,31 +1,30 @@ package graphics; import game.Debug; import game.Main; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; public class Sprite { public static Image[][] load(String filename, int w, int h) { try { - BufferedImage image = ImageIO.read(Main.class - .getResource("/ressources/" + filename)); + BufferedImage image = ImageIO.read(Main.class.getResource("/ressources/" + filename)); int partsX = image.getWidth() / w; int partsY = image.getHeight() / h; Image[][] parts = new Image[partsX][partsY]; for (int x = 0; x < partsX; x++) { for (int y = 0; y < partsY; y++) { parts[x][y] = new Image(w, h); image.getRGB(x * w, y * h, w, h, parts[x][y].pixels, 0, w); } } return parts; } catch (Exception e) { Debug.log(Debug.ERROR, "[Sprite]-Error: Can't load " + filename); return null; } } }
true
true
public static Image[][] load(String filename, int w, int h) { try { BufferedImage image = ImageIO.read(Main.class .getResource("/ressources/" + filename)); int partsX = image.getWidth() / w; int partsY = image.getHeight() / h; Image[][] parts = new Image[partsX][partsY]; for (int x = 0; x < partsX; x++) { for (int y = 0; y < partsY; y++) { parts[x][y] = new Image(w, h); image.getRGB(x * w, y * h, w, h, parts[x][y].pixels, 0, w); } } return parts; } catch (Exception e) { Debug.log(Debug.ERROR, "[Sprite]-Error: Can't load " + filename); return null; } }
public static Image[][] load(String filename, int w, int h) { try { BufferedImage image = ImageIO.read(Main.class.getResource("/ressources/" + filename)); int partsX = image.getWidth() / w; int partsY = image.getHeight() / h; Image[][] parts = new Image[partsX][partsY]; for (int x = 0; x < partsX; x++) { for (int y = 0; y < partsY; y++) { parts[x][y] = new Image(w, h); image.getRGB(x * w, y * h, w, h, parts[x][y].pixels, 0, w); } } return parts; } catch (Exception e) { Debug.log(Debug.ERROR, "[Sprite]-Error: Can't load " + filename); return null; } }
diff --git a/src/eu/alefzero/owncloud/syncadapter/FileSyncAdapter.java b/src/eu/alefzero/owncloud/syncadapter/FileSyncAdapter.java index d14151a..3397836 100644 --- a/src/eu/alefzero/owncloud/syncadapter/FileSyncAdapter.java +++ b/src/eu/alefzero/owncloud/syncadapter/FileSyncAdapter.java @@ -1,292 +1,292 @@ /* ownCloud Android client application * Copyright (C) 2011 Bartek Przybylski * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package eu.alefzero.owncloud.syncadapter; import java.io.IOException; import java.util.List; import java.util.Vector; import org.apache.jackrabbit.webdav.DavException; import org.apache.jackrabbit.webdav.MultiStatus; import org.apache.jackrabbit.webdav.client.methods.PropFindMethod; import android.accounts.Account; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.content.ContentProviderClient; import android.content.Context; import android.content.Intent; import android.content.SyncResult; import android.os.Bundle; import android.util.Log; import eu.alefzero.owncloud.datamodel.FileDataStorageManager; import eu.alefzero.owncloud.datamodel.OCFile; import eu.alefzero.owncloud.files.services.FileDownloader; import eu.alefzero.webdav.WebdavEntry; import eu.alefzero.webdav.WebdavUtils; /** * SyncAdapter implementation for syncing sample SyncAdapter contacts to the * platform ContactOperations provider. * * @author Bartek Przybylski */ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { private final static String TAG = "FileSyncAdapter"; /* Commented code for ugly performance tests private final static int MAX_DELAYS = 100; private static long[] mResponseDelays = new long[MAX_DELAYS]; private static long[] mSaveDelays = new long[MAX_DELAYS]; private int mDelaysIndex = 0; private int mDelaysCount = 0; */ private long mCurrentSyncTime; private boolean mCancellation; private Account mAccount; public FileSyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); } @Override public synchronized void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { mCancellation = false; mAccount = account; this.setAccount(mAccount); this.setContentProvider(provider); this.setStorageManager(new FileDataStorageManager(mAccount, getContentProvider())); /* Commented code for ugly performance tests mDelaysIndex = 0; mDelaysCount = 0; */ Log.d(TAG, "syncing owncloud account " + mAccount.name); sendStickyBroadcast(true, null); // message to signal the start to the UI PropFindMethod query; try { mCurrentSyncTime = System.currentTimeMillis(); query = new PropFindMethod(getUri().toString() + "/"); getClient().executeMethod(query); MultiStatus resp = null; resp = query.getResponseBodyAsMultiStatus(); if (resp.getResponses().length > 0) { WebdavEntry we = new WebdavEntry(resp.getResponses()[0], getUri().getPath()); OCFile file = fillOCFile(we); file.setParentId(0); getStorageManager().saveFile(file); if (!mCancellation) { fetchData(getUri().toString(), syncResult, file.getFileId()); } } } catch (OperationCanceledException e) { e.printStackTrace(); } catch (AuthenticatorException e) { syncResult.stats.numAuthExceptions++; e.printStackTrace(); } catch (IOException e) { syncResult.stats.numIoExceptions++; e.printStackTrace(); } catch (DavException e) { syncResult.stats.numIoExceptions++; e.printStackTrace(); } catch (Throwable t) { // TODO update syncResult Log.e(TAG, "problem while synchronizing owncloud account " + account.name, t); t.printStackTrace(); } /* Commented code for ugly performance tests long sum = 0, mean = 0, max = 0, min = Long.MAX_VALUE; for (int i=0; i<MAX_DELAYS && i<mDelaysCount; i++) { sum += mResponseDelays[i]; max = Math.max(max, mResponseDelays[i]); min = Math.min(min, mResponseDelays[i]); } mean = sum / mDelaysCount; Log.e(TAG, "SYNC STATS - response: mean time = " + mean + " ; max time = " + max + " ; min time = " + min); sum = 0; max = 0; min = Long.MAX_VALUE; for (int i=0; i<MAX_DELAYS && i<mDelaysCount; i++) { sum += mSaveDelays[i]; max = Math.max(max, mSaveDelays[i]); min = Math.min(min, mSaveDelays[i]); } mean = sum / mDelaysCount; Log.e(TAG, "SYNC STATS - save: mean time = " + mean + " ; max time = " + max + " ; min time = " + min); Log.e(TAG, "SYNC STATS - folders measured: " + mDelaysCount); */ sendStickyBroadcast(false, null); } private void fetchData(String uri, SyncResult syncResult, long parentId) { try { //Log.v(TAG, "syncing: fetching " + uri); // remote request PropFindMethod query = new PropFindMethod(uri); /* Commented code for ugly performance tests long responseDelay = System.currentTimeMillis(); */ getClient().executeMethod(query); /* Commented code for ugly performance tests responseDelay = System.currentTimeMillis() - responseDelay; Log.e(TAG, "syncing: RESPONSE TIME for " + uri + " contents, " + responseDelay + "ms"); */ MultiStatus resp = null; resp = query.getResponseBodyAsMultiStatus(); // insertion or update of files List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1); for (int i = 1; i < resp.getResponses().length; ++i) { WebdavEntry we = new WebdavEntry(resp.getResponses()[i], getUri().getPath()); OCFile file = fillOCFile(we); file.setParentId(parentId); if (getStorageManager().getFileByPath(file.getRemotePath()) != null && getStorageManager().getFileByPath(file.getRemotePath()).keepInSync() && file.getModificationTimestamp() > getStorageManager().getFileByPath(file.getRemotePath()) .getModificationTimestamp()) { Intent intent = new Intent(this.getContext(), FileDownloader.class); intent.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount()); intent.putExtra(FileDownloader.EXTRA_FILE_PATH, file.getRemotePath()); intent.putExtra(FileDownloader.EXTRA_REMOTE_PATH, file.getRemotePath()); intent.putExtra(FileDownloader.EXTRA_FILE_SIZE, file.getFileLength()); file.setKeepInSync(true); getContext().startService(intent); } if (getStorageManager().getFileByPath(file.getRemotePath()) != null) file.setKeepInSync(getStorageManager().getFileByPath(file.getRemotePath()).keepInSync()); //getStorageManager().saveFile(file); updatedFiles.add(file); if (parentId == 0) parentId = file.getFileId(); } /* Commented code for ugly performance tests long saveDelay = System.currentTimeMillis(); */ getStorageManager().saveFiles(updatedFiles); // all "at once" ; trying to get a best performance in database update /* Commented code for ugly performance tests saveDelay = System.currentTimeMillis() - saveDelay; Log.e(TAG, "syncing: SAVE TIME for " + uri + " contents, " + mSaveDelays[mDelaysIndex] + "ms"); */ // removal of obsolete files Vector<OCFile> files = getStorageManager().getDirectoryContent( getStorageManager().getFileById(parentId)); OCFile file; for (int i=0; i < files.size(); ) { file = files.get(i); - if (file.getLastSyncDate() != mCurrentSyncTime && file.getLastSyncDate() != 0) { + if (file.getLastSyncDate() != mCurrentSyncTime) { getStorageManager().removeFile(file); files.remove(i); } else { i++; } } // synchronized folder -> notice to UI sendStickyBroadcast(true, getStorageManager().getFileById(parentId).getRemotePath()); // recursive fetch for (int i=0; i < files.size() && !mCancellation; i++) { OCFile newFile = files.get(i); if (newFile.getMimetype().equals("DIR")) { fetchData(getUri().toString() + WebdavUtils.encodePath(newFile.getRemotePath()), syncResult, newFile.getFileId()); } } if (mCancellation) Log.d(TAG, "Leaving " + uri + " because cancellation request"); /* Commented code for ugly performance tests mResponseDelays[mDelaysIndex] = responseDelay; mSaveDelays[mDelaysIndex] = saveDelay; mDelaysCount++; mDelaysIndex++; if (mDelaysIndex >= MAX_DELAYS) mDelaysIndex = 0; */ } catch (OperationCanceledException e) { e.printStackTrace(); } catch (AuthenticatorException e) { syncResult.stats.numAuthExceptions++; e.printStackTrace(); } catch (IOException e) { syncResult.stats.numIoExceptions++; e.printStackTrace(); } catch (DavException e) { syncResult.stats.numIoExceptions++; e.printStackTrace(); } catch (Throwable t) { // TODO update syncResult Log.e(TAG, "problem while synchronizing owncloud account " + mAccount.name, t); t.printStackTrace(); } } private OCFile fillOCFile(WebdavEntry we) { OCFile file = new OCFile(we.decodedPath()); file.setCreationTimestamp(we.createTimestamp()); file.setFileLength(we.contentLength()); file.setMimetype(we.contentType()); file.setModificationTimestamp(we.modifiedTimesamp()); file.setLastSyncDate(mCurrentSyncTime); return file; } private void sendStickyBroadcast(boolean inProgress, String dirRemotePath) { Intent i = new Intent(FileSyncService.SYNC_MESSAGE); i.putExtra(FileSyncService.IN_PROGRESS, inProgress); i.putExtra(FileSyncService.ACCOUNT_NAME, getAccount().name); if (dirRemotePath != null) { i.putExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH, dirRemotePath); } getContext().sendStickyBroadcast(i); } /** * Called by system SyncManager when a synchronization is required to be cancelled. * * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder * fetched will be still saved in the database. See onPerformSync implementation. */ @Override public void onSyncCanceled() { Log.d(TAG, "Synchronization of " + mAccount.name + " has been requested to cancell"); mCancellation = true; super.onSyncCanceled(); } }
true
true
private void fetchData(String uri, SyncResult syncResult, long parentId) { try { //Log.v(TAG, "syncing: fetching " + uri); // remote request PropFindMethod query = new PropFindMethod(uri); /* Commented code for ugly performance tests long responseDelay = System.currentTimeMillis(); */ getClient().executeMethod(query); /* Commented code for ugly performance tests responseDelay = System.currentTimeMillis() - responseDelay; Log.e(TAG, "syncing: RESPONSE TIME for " + uri + " contents, " + responseDelay + "ms"); */ MultiStatus resp = null; resp = query.getResponseBodyAsMultiStatus(); // insertion or update of files List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1); for (int i = 1; i < resp.getResponses().length; ++i) { WebdavEntry we = new WebdavEntry(resp.getResponses()[i], getUri().getPath()); OCFile file = fillOCFile(we); file.setParentId(parentId); if (getStorageManager().getFileByPath(file.getRemotePath()) != null && getStorageManager().getFileByPath(file.getRemotePath()).keepInSync() && file.getModificationTimestamp() > getStorageManager().getFileByPath(file.getRemotePath()) .getModificationTimestamp()) { Intent intent = new Intent(this.getContext(), FileDownloader.class); intent.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount()); intent.putExtra(FileDownloader.EXTRA_FILE_PATH, file.getRemotePath()); intent.putExtra(FileDownloader.EXTRA_REMOTE_PATH, file.getRemotePath()); intent.putExtra(FileDownloader.EXTRA_FILE_SIZE, file.getFileLength()); file.setKeepInSync(true); getContext().startService(intent); } if (getStorageManager().getFileByPath(file.getRemotePath()) != null) file.setKeepInSync(getStorageManager().getFileByPath(file.getRemotePath()).keepInSync()); //getStorageManager().saveFile(file); updatedFiles.add(file); if (parentId == 0) parentId = file.getFileId(); } /* Commented code for ugly performance tests long saveDelay = System.currentTimeMillis(); */ getStorageManager().saveFiles(updatedFiles); // all "at once" ; trying to get a best performance in database update /* Commented code for ugly performance tests saveDelay = System.currentTimeMillis() - saveDelay; Log.e(TAG, "syncing: SAVE TIME for " + uri + " contents, " + mSaveDelays[mDelaysIndex] + "ms"); */ // removal of obsolete files Vector<OCFile> files = getStorageManager().getDirectoryContent( getStorageManager().getFileById(parentId)); OCFile file; for (int i=0; i < files.size(); ) { file = files.get(i); if (file.getLastSyncDate() != mCurrentSyncTime && file.getLastSyncDate() != 0) { getStorageManager().removeFile(file); files.remove(i); } else { i++; } } // synchronized folder -> notice to UI sendStickyBroadcast(true, getStorageManager().getFileById(parentId).getRemotePath()); // recursive fetch for (int i=0; i < files.size() && !mCancellation; i++) { OCFile newFile = files.get(i); if (newFile.getMimetype().equals("DIR")) { fetchData(getUri().toString() + WebdavUtils.encodePath(newFile.getRemotePath()), syncResult, newFile.getFileId()); } } if (mCancellation) Log.d(TAG, "Leaving " + uri + " because cancellation request"); /* Commented code for ugly performance tests mResponseDelays[mDelaysIndex] = responseDelay; mSaveDelays[mDelaysIndex] = saveDelay; mDelaysCount++; mDelaysIndex++; if (mDelaysIndex >= MAX_DELAYS) mDelaysIndex = 0; */ } catch (OperationCanceledException e) { e.printStackTrace(); } catch (AuthenticatorException e) { syncResult.stats.numAuthExceptions++; e.printStackTrace(); } catch (IOException e) { syncResult.stats.numIoExceptions++; e.printStackTrace(); } catch (DavException e) { syncResult.stats.numIoExceptions++; e.printStackTrace(); } catch (Throwable t) { // TODO update syncResult Log.e(TAG, "problem while synchronizing owncloud account " + mAccount.name, t); t.printStackTrace(); } }
private void fetchData(String uri, SyncResult syncResult, long parentId) { try { //Log.v(TAG, "syncing: fetching " + uri); // remote request PropFindMethod query = new PropFindMethod(uri); /* Commented code for ugly performance tests long responseDelay = System.currentTimeMillis(); */ getClient().executeMethod(query); /* Commented code for ugly performance tests responseDelay = System.currentTimeMillis() - responseDelay; Log.e(TAG, "syncing: RESPONSE TIME for " + uri + " contents, " + responseDelay + "ms"); */ MultiStatus resp = null; resp = query.getResponseBodyAsMultiStatus(); // insertion or update of files List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1); for (int i = 1; i < resp.getResponses().length; ++i) { WebdavEntry we = new WebdavEntry(resp.getResponses()[i], getUri().getPath()); OCFile file = fillOCFile(we); file.setParentId(parentId); if (getStorageManager().getFileByPath(file.getRemotePath()) != null && getStorageManager().getFileByPath(file.getRemotePath()).keepInSync() && file.getModificationTimestamp() > getStorageManager().getFileByPath(file.getRemotePath()) .getModificationTimestamp()) { Intent intent = new Intent(this.getContext(), FileDownloader.class); intent.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount()); intent.putExtra(FileDownloader.EXTRA_FILE_PATH, file.getRemotePath()); intent.putExtra(FileDownloader.EXTRA_REMOTE_PATH, file.getRemotePath()); intent.putExtra(FileDownloader.EXTRA_FILE_SIZE, file.getFileLength()); file.setKeepInSync(true); getContext().startService(intent); } if (getStorageManager().getFileByPath(file.getRemotePath()) != null) file.setKeepInSync(getStorageManager().getFileByPath(file.getRemotePath()).keepInSync()); //getStorageManager().saveFile(file); updatedFiles.add(file); if (parentId == 0) parentId = file.getFileId(); } /* Commented code for ugly performance tests long saveDelay = System.currentTimeMillis(); */ getStorageManager().saveFiles(updatedFiles); // all "at once" ; trying to get a best performance in database update /* Commented code for ugly performance tests saveDelay = System.currentTimeMillis() - saveDelay; Log.e(TAG, "syncing: SAVE TIME for " + uri + " contents, " + mSaveDelays[mDelaysIndex] + "ms"); */ // removal of obsolete files Vector<OCFile> files = getStorageManager().getDirectoryContent( getStorageManager().getFileById(parentId)); OCFile file; for (int i=0; i < files.size(); ) { file = files.get(i); if (file.getLastSyncDate() != mCurrentSyncTime) { getStorageManager().removeFile(file); files.remove(i); } else { i++; } } // synchronized folder -> notice to UI sendStickyBroadcast(true, getStorageManager().getFileById(parentId).getRemotePath()); // recursive fetch for (int i=0; i < files.size() && !mCancellation; i++) { OCFile newFile = files.get(i); if (newFile.getMimetype().equals("DIR")) { fetchData(getUri().toString() + WebdavUtils.encodePath(newFile.getRemotePath()), syncResult, newFile.getFileId()); } } if (mCancellation) Log.d(TAG, "Leaving " + uri + " because cancellation request"); /* Commented code for ugly performance tests mResponseDelays[mDelaysIndex] = responseDelay; mSaveDelays[mDelaysIndex] = saveDelay; mDelaysCount++; mDelaysIndex++; if (mDelaysIndex >= MAX_DELAYS) mDelaysIndex = 0; */ } catch (OperationCanceledException e) { e.printStackTrace(); } catch (AuthenticatorException e) { syncResult.stats.numAuthExceptions++; e.printStackTrace(); } catch (IOException e) { syncResult.stats.numIoExceptions++; e.printStackTrace(); } catch (DavException e) { syncResult.stats.numIoExceptions++; e.printStackTrace(); } catch (Throwable t) { // TODO update syncResult Log.e(TAG, "problem while synchronizing owncloud account " + mAccount.name, t); t.printStackTrace(); } }
diff --git a/core/src/test/net/sf/clirr/core/internal/checks/MethodSetCheckTest.java b/core/src/test/net/sf/clirr/core/internal/checks/MethodSetCheckTest.java index ca0ba75..5ed7283 100644 --- a/core/src/test/net/sf/clirr/core/internal/checks/MethodSetCheckTest.java +++ b/core/src/test/net/sf/clirr/core/internal/checks/MethodSetCheckTest.java @@ -1,78 +1,78 @@ package net.sf.clirr.core.internal.checks; import net.sf.clirr.core.internal.ClassChangeCheck; import net.sf.clirr.core.Severity; import net.sf.clirr.core.ScopeSelector; import net.sf.clirr.core.internal.checks.MethodSetCheck; import net.sf.clirr.core.internal.checks.AbstractCheckTestCase; import net.sf.clirr.core.internal.checks.ExpectedDiff; /** * TODO: Docs. * * @author lkuehne */ public class MethodSetCheckTest extends AbstractCheckTestCase { public void testMethodCheck() throws Exception { ExpectedDiff[] expected = new ExpectedDiff[] { // method addition and removal new ExpectedDiff("Method 'public void removedMethod(java.lang.String)' has been removed", Severity.ERROR, "testlib.MethodsChange", "public void removedMethod(java.lang.String)", null), - new ExpectedDiff("Accessability of method 'public int getPriv2()' has been decreased from public to private", + new ExpectedDiff("Accessibility of method 'public int getPriv2()' has been decreased from public to private", Severity.ERROR, "testlib.MethodsChange", "public int getPriv2()", null), new ExpectedDiff("Method 'protected MethodsChange(int, boolean)' has been added", Severity.INFO, "testlib.MethodsChange", "protected MethodsChange(int, boolean)", null), new ExpectedDiff("Method 'public java.lang.Long getPrivSquare()' has been added", Severity.INFO, "testlib.MethodsChange", "public java.lang.Long getPrivSquare()", null), new ExpectedDiff("Method 'public void moveToSuper()' has been added", Severity.INFO, "testlib.ComplexMethodMoveBase", "public void moveToSuper()", null), new ExpectedDiff("Method 'public void moveToSuper()' is now implemented in superclass testlib.ComplexMethodMoveBase", Severity.INFO, "testlib.ComplexMethodMoveSub", "public void moveToSuper()", null), new ExpectedDiff("Abstract method 'public void method()' is now specified by implemented interface testlib.BaseInterface", Severity.INFO, "testlib.AbstractImpl", "public void method()", null), // Constructor changes new ExpectedDiff("Parameter 1 of 'protected MethodsChange(int)' has changed its type to java.lang.Integer", Severity.ERROR, "testlib.MethodsChange", "protected MethodsChange(int)", null), // return type changes new ExpectedDiff("Return type of method 'public java.lang.Number getPrivAsNumber()' has been changed to java.lang.Integer", Severity.ERROR, "testlib.MethodsChange", "public java.lang.Number getPrivAsNumber()", null), // TODO: INFO if method is final new ExpectedDiff("Return type of method 'public java.lang.Integer getPrivAsInteger()' has been changed to java.lang.Number", Severity.ERROR, "testlib.MethodsChange", "public java.lang.Integer getPrivAsInteger()", null), // parameter list changes // Note: This is the current behaviour, not necessarily the spec of the desired behaviour // TODO: need to check assignability of types (and check if method or class is final?) new ExpectedDiff("In method 'public void printPriv()' the number of arguments has changed", Severity.ERROR, "testlib.MethodsChange", "public void printPriv()", null), new ExpectedDiff("Parameter 1 of 'public void strengthenParamType(java.lang.Object)' has changed its type to java.lang.String", Severity.ERROR, "testlib.MethodsChange", "public void strengthenParamType(java.lang.Object)", null), new ExpectedDiff("Parameter 1 of 'public void weakenParamType(java.lang.String)' has changed its type to java.lang.Object", Severity.ERROR, "testlib.MethodsChange", "public void weakenParamType(java.lang.String)", null), new ExpectedDiff("Parameter 1 of 'public void changeParamType(java.lang.String)' has changed its type to java.lang.Integer", Severity.ERROR, "testlib.MethodsChange", "public void changeParamType(java.lang.String)", null), // deprecation changes new ExpectedDiff("Method 'public void becomesDeprecated()' has been deprecated", Severity.INFO, "testlib.MethodsChange", "public void becomesDeprecated()", null), new ExpectedDiff("Method 'public void becomesUndeprecated()' is no longer deprecated", Severity.INFO, "testlib.MethodsChange", "public void becomesUndeprecated()", null), // declared exceptions // TODO }; verify(expected); } protected final ClassChangeCheck createCheck(TestDiffListener tdl) { return new MethodSetCheck(tdl, new ScopeSelector()); } }
true
true
public void testMethodCheck() throws Exception { ExpectedDiff[] expected = new ExpectedDiff[] { // method addition and removal new ExpectedDiff("Method 'public void removedMethod(java.lang.String)' has been removed", Severity.ERROR, "testlib.MethodsChange", "public void removedMethod(java.lang.String)", null), new ExpectedDiff("Accessability of method 'public int getPriv2()' has been decreased from public to private", Severity.ERROR, "testlib.MethodsChange", "public int getPriv2()", null), new ExpectedDiff("Method 'protected MethodsChange(int, boolean)' has been added", Severity.INFO, "testlib.MethodsChange", "protected MethodsChange(int, boolean)", null), new ExpectedDiff("Method 'public java.lang.Long getPrivSquare()' has been added", Severity.INFO, "testlib.MethodsChange", "public java.lang.Long getPrivSquare()", null), new ExpectedDiff("Method 'public void moveToSuper()' has been added", Severity.INFO, "testlib.ComplexMethodMoveBase", "public void moveToSuper()", null), new ExpectedDiff("Method 'public void moveToSuper()' is now implemented in superclass testlib.ComplexMethodMoveBase", Severity.INFO, "testlib.ComplexMethodMoveSub", "public void moveToSuper()", null), new ExpectedDiff("Abstract method 'public void method()' is now specified by implemented interface testlib.BaseInterface", Severity.INFO, "testlib.AbstractImpl", "public void method()", null), // Constructor changes new ExpectedDiff("Parameter 1 of 'protected MethodsChange(int)' has changed its type to java.lang.Integer", Severity.ERROR, "testlib.MethodsChange", "protected MethodsChange(int)", null), // return type changes new ExpectedDiff("Return type of method 'public java.lang.Number getPrivAsNumber()' has been changed to java.lang.Integer", Severity.ERROR, "testlib.MethodsChange", "public java.lang.Number getPrivAsNumber()", null), // TODO: INFO if method is final new ExpectedDiff("Return type of method 'public java.lang.Integer getPrivAsInteger()' has been changed to java.lang.Number", Severity.ERROR, "testlib.MethodsChange", "public java.lang.Integer getPrivAsInteger()", null), // parameter list changes // Note: This is the current behaviour, not necessarily the spec of the desired behaviour // TODO: need to check assignability of types (and check if method or class is final?) new ExpectedDiff("In method 'public void printPriv()' the number of arguments has changed", Severity.ERROR, "testlib.MethodsChange", "public void printPriv()", null), new ExpectedDiff("Parameter 1 of 'public void strengthenParamType(java.lang.Object)' has changed its type to java.lang.String", Severity.ERROR, "testlib.MethodsChange", "public void strengthenParamType(java.lang.Object)", null), new ExpectedDiff("Parameter 1 of 'public void weakenParamType(java.lang.String)' has changed its type to java.lang.Object", Severity.ERROR, "testlib.MethodsChange", "public void weakenParamType(java.lang.String)", null), new ExpectedDiff("Parameter 1 of 'public void changeParamType(java.lang.String)' has changed its type to java.lang.Integer", Severity.ERROR, "testlib.MethodsChange", "public void changeParamType(java.lang.String)", null), // deprecation changes new ExpectedDiff("Method 'public void becomesDeprecated()' has been deprecated", Severity.INFO, "testlib.MethodsChange", "public void becomesDeprecated()", null), new ExpectedDiff("Method 'public void becomesUndeprecated()' is no longer deprecated", Severity.INFO, "testlib.MethodsChange", "public void becomesUndeprecated()", null), // declared exceptions // TODO }; verify(expected); }
public void testMethodCheck() throws Exception { ExpectedDiff[] expected = new ExpectedDiff[] { // method addition and removal new ExpectedDiff("Method 'public void removedMethod(java.lang.String)' has been removed", Severity.ERROR, "testlib.MethodsChange", "public void removedMethod(java.lang.String)", null), new ExpectedDiff("Accessibility of method 'public int getPriv2()' has been decreased from public to private", Severity.ERROR, "testlib.MethodsChange", "public int getPriv2()", null), new ExpectedDiff("Method 'protected MethodsChange(int, boolean)' has been added", Severity.INFO, "testlib.MethodsChange", "protected MethodsChange(int, boolean)", null), new ExpectedDiff("Method 'public java.lang.Long getPrivSquare()' has been added", Severity.INFO, "testlib.MethodsChange", "public java.lang.Long getPrivSquare()", null), new ExpectedDiff("Method 'public void moveToSuper()' has been added", Severity.INFO, "testlib.ComplexMethodMoveBase", "public void moveToSuper()", null), new ExpectedDiff("Method 'public void moveToSuper()' is now implemented in superclass testlib.ComplexMethodMoveBase", Severity.INFO, "testlib.ComplexMethodMoveSub", "public void moveToSuper()", null), new ExpectedDiff("Abstract method 'public void method()' is now specified by implemented interface testlib.BaseInterface", Severity.INFO, "testlib.AbstractImpl", "public void method()", null), // Constructor changes new ExpectedDiff("Parameter 1 of 'protected MethodsChange(int)' has changed its type to java.lang.Integer", Severity.ERROR, "testlib.MethodsChange", "protected MethodsChange(int)", null), // return type changes new ExpectedDiff("Return type of method 'public java.lang.Number getPrivAsNumber()' has been changed to java.lang.Integer", Severity.ERROR, "testlib.MethodsChange", "public java.lang.Number getPrivAsNumber()", null), // TODO: INFO if method is final new ExpectedDiff("Return type of method 'public java.lang.Integer getPrivAsInteger()' has been changed to java.lang.Number", Severity.ERROR, "testlib.MethodsChange", "public java.lang.Integer getPrivAsInteger()", null), // parameter list changes // Note: This is the current behaviour, not necessarily the spec of the desired behaviour // TODO: need to check assignability of types (and check if method or class is final?) new ExpectedDiff("In method 'public void printPriv()' the number of arguments has changed", Severity.ERROR, "testlib.MethodsChange", "public void printPriv()", null), new ExpectedDiff("Parameter 1 of 'public void strengthenParamType(java.lang.Object)' has changed its type to java.lang.String", Severity.ERROR, "testlib.MethodsChange", "public void strengthenParamType(java.lang.Object)", null), new ExpectedDiff("Parameter 1 of 'public void weakenParamType(java.lang.String)' has changed its type to java.lang.Object", Severity.ERROR, "testlib.MethodsChange", "public void weakenParamType(java.lang.String)", null), new ExpectedDiff("Parameter 1 of 'public void changeParamType(java.lang.String)' has changed its type to java.lang.Integer", Severity.ERROR, "testlib.MethodsChange", "public void changeParamType(java.lang.String)", null), // deprecation changes new ExpectedDiff("Method 'public void becomesDeprecated()' has been deprecated", Severity.INFO, "testlib.MethodsChange", "public void becomesDeprecated()", null), new ExpectedDiff("Method 'public void becomesUndeprecated()' is no longer deprecated", Severity.INFO, "testlib.MethodsChange", "public void becomesUndeprecated()", null), // declared exceptions // TODO }; verify(expected); }
diff --git a/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/host/css/ComputedCSSStyleDeclarationTest.java b/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/host/css/ComputedCSSStyleDeclarationTest.java index af4eb7b04..101cec1cc 100644 --- a/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/host/css/ComputedCSSStyleDeclarationTest.java +++ b/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/host/css/ComputedCSSStyleDeclarationTest.java @@ -1,606 +1,607 @@ /* * Copyright (c) 2002-2012 Gargoyle Software Inc. * * 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.gargoylesoftware.htmlunit.javascript.host.css; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import com.gargoylesoftware.htmlunit.BrowserRunner; import com.gargoylesoftware.htmlunit.BrowserRunner.Alerts; import com.gargoylesoftware.htmlunit.BrowserRunner.Browser; import com.gargoylesoftware.htmlunit.BrowserRunner.Browsers; import com.gargoylesoftware.htmlunit.WebDriverTestCase; /** * Tests for {@link ComputedCSSStyleDeclaration}. * * @version $Revision$ * @author Ahmed Ashour * @author Marc Guillemot * @author Ronald Brill */ @RunWith(BrowserRunner.class) public class ComputedCSSStyleDeclarationTest extends WebDriverTestCase { /** * @throws Exception if the test fails */ @Test @Alerts(FF = "none", IE = "undefined") public void cssFloat() throws Exception { final String html = "<html>\n" + "<head>\n" + "<script>\n" + " function test() {\n" + " var e = document.getElementById('myDiv');\n" + " var s = window.getComputedStyle ? window.getComputedStyle(e,null) : e.currentStyle;\n" + " alert(s.cssFloat);\n" + " }\n" + "</script>\n" + "</head>\n" + "<body onload='test()'>\n" + " <div id='myDiv'></div>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * Compares all style and getComputedStle. * @throws Exception if the test fails */ @Test @Browsers(Browser.FF3_6) public void stringPropertiesFF3_6() throws Exception { final String html = "<html><head><title>First</title><script>\n" + "function test() {\n" + " var e = document.getElementById('myDiv');\n" + " var str = '';\n" + " for (var i in e.style) {\n" + " var s1 = eval('e.style.' + i);\n" + " var s2 = eval('window.getComputedStyle(e,null).' + i);\n" + " if(typeof s1 == 'string')\n" + " str += i + '=' + s1 + ':' + s2 + ',';\n" + " }\n" + " document.getElementById('myTextarea').value = str;\n" + "}\n" + "</script></head>\n" + "<body onload='test()'>\n" + " <div id='myDiv'><br>\n" + " <textarea id='myTextarea' cols='120' rows='20'></textarea>\n" + "</body></html>"; final String expectedText = "opacity=:1,background=:," + "height=:362px,textAlign=:start,right=:auto,bottom=:auto,fontSize=:16px,backgroundColor=:transparent," + "letterSpacing=:normal,verticalAlign=:baseline,color=:rgb(0, 0, 0),top=:auto,width=:1256px," + "display=:block,zIndex=:auto,position=:static,left=:auto,visibility=:visible,cssText=:,azimuth=:," + "backgroundAttachment=:scroll,backgroundImage=:none,backgroundPosition=:0% 0%,backgroundRepeat=:repeat," + "border=:,borderCollapse=:separate,borderColor=:,borderSpacing=:0px 0px,borderStyle=:,borderTop=:," + "borderRight=:,borderBottom=:,borderLeft=:,borderTopColor=:rgb(0, 0, 0),borderRightColor=:rgb(0, 0, 0)," + "borderBottomColor=:rgb(0, 0, 0),borderLeftColor=:rgb(0, 0, 0),borderTopStyle=:none," + "borderRightStyle=:none,borderBottomStyle=:none,borderLeftStyle=:none,borderTopWidth=:0px," + "borderRightWidth=:0px,borderBottomWidth=:0px,borderLeftWidth=:0px,borderWidth=:,captionSide=:top," + "clear=:none,clip=:auto,content=:none,counterIncrement=:none,counterReset=:none,cue=:,cueAfter=:," + "cueBefore=:,cursor=:auto,direction=:ltr,elevation=:,emptyCells=:-moz-show-background,cssFloat=:none," + "font=:,fontFamily=:serif,fontSizeAdjust=:none,fontStretch=:normal,fontStyle=:normal,fontVariant=:normal," + "fontWeight=:400,lineHeight=:20px,listStyle=:,listStyleImage=:none,listStylePosition=:outside," + "listStyleType=:disc,margin=:,marginTop=:0px,marginRight=:0px,marginBottom=:0px,marginLeft=:0px," + "markerOffset=:auto,marks=:,maxHeight=:none,maxWidth=:none,minHeight=:0px,minWidth=:0px,orphans=:," + "outline=:,outlineColor=:rgb(0, 0, 0),outlineStyle=:none,outlineWidth=:0px,overflow=:visible,padding=:," + "paddingTop=:0px,paddingRight=:0px,paddingBottom=:0px,paddingLeft=:0px,page=:,pageBreakAfter=:auto," + "pageBreakBefore=:auto,pageBreakInside=:,pause=:,pauseAfter=:,pauseBefore=:,pitch=:,pitchRange=:," + "quotes=:,richness=:,size=:,speak=:,speakHeader=:," // TODO quotes + "speakNumeral=:,speakPunctuation=:,speechRate=:,stress=:,tableLayout=:auto,textDecoration=:none," + "textIndent=:0px,textShadow=:none,textTransform=:none,unicodeBidi=:embed,voiceFamily=:,volume=:," + "whiteSpace=:normal,widows=:,wordSpacing=:0px,MozAppearance=:none,MozBackgroundClip=:border," + "MozBackgroundInlinePolicy=:continuous,MozBackgroundOrigin=:padding,MozBinding=:none," + "MozBorderBottomColors=:none," + "MozBorderLeftColors=:none,MozBorderRightColors=:none,MozBorderTopColors=:none,MozBorderRadius=:," + "MozBorderRadiusTopleft=:0px,MozBorderRadiusTopright=:0px,MozBorderRadiusBottomleft=:0px," + "MozBorderRadiusBottomright=:0px,MozBoxAlign=:stretch,MozBoxDirection=:normal,MozBoxFlex=:0," + "MozBoxOrient=:horizontal,MozBoxOrdinalGroup=:1,MozBoxPack=:start,MozBoxSizing=:content-box," + "MozColumnCount=:auto,MozColumnWidth=:auto,MozColumnGap=:16px,MozFloatEdge=:content-box," + "MozForceBrokenImageIcon=:0,MozImageRegion=:auto,MozMarginEnd=:,MozMarginStart=:,MozOpacity=:1," + "MozOutline=:,MozOutlineColor=:rgb(0, 0, 0),MozOutlineRadius=:,MozOutlineRadiusTopleft=:0px," + "MozOutlineRadiusTopright=:0px,MozOutlineRadiusBottomleft=:0px,MozOutlineRadiusBottomright=:0px," + "MozOutlineStyle=:none,MozOutlineWidth=:0px," + "MozOutlineOffset=:0px,MozPaddingEnd=:,MozPaddingStart=:,MozUserFocus=:none,MozUserInput=:auto," + "MozUserModify=:read-only,MozUserSelect=:auto,outlineOffset=:0px,overflowX=:visible,overflowY=:visible," + "imeMode=:auto,MozBorderEnd=:,MozBorderEndColor=:,MozBorderEndStyle=:,MozBorderEndWidth=:," + "MozBorderStart=:,MozBorderStartColor=:,MozBorderStartStyle=:,MozBorderStartWidth=:," + "MozStackSizing=:stretch-to-fit,MozBoxShadow=:none,MozBorderImage=:none,MozColumnRule=:," + "MozColumnRuleWidth=:0px,MozColumnRuleStyle=:none," + "MozColumnRuleColor=:rgb(0, 0, 0),wordWrap=:normal,MozTransform=:none,MozTransformOrigin=:50% 50%," + "MozWindowShadow=:default,MozBackgroundSize=:auto auto,pointerEvents=:auto,"; final WebDriver driver = loadPage2(html); final List<String> expectedValues = stringProperties(expectedText); - final List<String> collectedValues = stringProperties(driver.findElement(By.id("myTextarea")).getText()); + final List<String> collectedValues = stringProperties(driver.findElement(By.id("myTextarea")). + getAttribute("value")); assertEquals(expectedValues.toString(), collectedValues.toString()); } private List<String> stringProperties(final String string) throws Exception { final List<String> values = new ArrayList<String>(); if (string.isEmpty()) { return values; } //string.split(",") will not work because we have values of 'rgb(0, 0, 0)' int i = string.indexOf('='); i = string.indexOf('=', i + 1); int p0; for (p0 = 0; i != -1;) { final int p1 = string.lastIndexOf(',', i); values.add(string.substring(p0, p1)); i = string.indexOf('=', i + 1); p0 = p1 + 1; } values.add(string.substring(p0, string.length() - 1)); Collections.sort(values, new Comparator<String>() { public int compare(String o1, String o2) { o1 = o1.substring(0, o1.indexOf('=')); o2 = o2.substring(0, o2.indexOf('=')); return o1.compareToIgnoreCase(o2); } }); return values; } /** * @throws Exception if the test fails */ @Test @Browsers(Browser.FF) @Alerts({"", "", "auto", "pointer" }) public void styleElement() throws Exception { final String html = "<html><head><title>foo</title>\n" + "<style type='text/css'>\n" + " /* <![CDATA[ */\n" + " #myDiv2 {cursor: pointer}\n" + " /* ]]> */\n" + "</style>\n" + "<script>\n" + " function test() {\n" + " var div1 = document.getElementById('myDiv1');\n" + " var div2 = document.getElementById('myDiv2');\n" + " alert(div1.style.cursor);\n" + " alert(div2.style.cursor);\n" + " alert(window.getComputedStyle(div1, null).cursor);\n" + " alert(window.getComputedStyle(div2, null).cursor);\n" + " }\n" + "</script></head><body onload='test()'>\n" + " <div id='myDiv1'/>\n" + " <div id='myDiv2'/>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * Some style tests. There are two points in this case: * <ol> * <li>https://sourceforge.net/tracker/index.php?func=detail&aid=1566274&group_id=82996&atid=567969</li> * <li>the "pointer" value gets inherited by "myDiv2", which is parsed as a child of "style_test_1"</li> * </ol> * @throws Exception if the test fails */ @Test @Browsers(Browser.FF) @Alerts({"", "", "pointer", "pointer" }) public void styleElement2() throws Exception { final String html = "<html><head><title>foo</title>\n" + "<style type='text/css'>\n" + " /* <![CDATA[ */\n" + " #style_test_1 {cursor: pointer}\n" + " /* ]]> */\n" + "</style>\n" + "<script>\n" + " function test() {\n" + " var div1 = document.getElementById('style_test_1');\n" + " var div2 = document.getElementById('myDiv2');\n" + " alert(div1.style.cursor);\n" + " alert(div2.style.cursor);\n" + " alert(window.getComputedStyle(div1, null).cursor);\n" + " alert(window.getComputedStyle(div2, null).cursor);\n" + " }\n" + "</script></head><body onload='test()'>\n" + " <div id='style_test_1'/>\n" + " <div id='myDiv2'/>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * @throws Exception if the test fails */ @Test @Browsers(Browser.IE) @Alerts({ "0", "number" }) public void zIndex() throws Exception { final String html = "<html>\n" + "<head>\n" + "<script>\n" + " function test() {\n" + " var e = document.getElementById('myDiv');\n" + " alert(e.currentStyle['zIndex']);\n" + " alert(typeof e.currentStyle['zIndex']);\n" + " }\n" + "</script>\n" + "</head>\n" + "<body onload='test()'>\n" + " <div id='myDiv'></div>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * @throws Exception if an error occurs */ @Test @Alerts("50px") public void styleAttributePreferredOverStylesheet() throws Exception { final String html = "<html>\n" + "<head><style>div { width: 30px; }</style></head>\n" + "<body>\n" + "<div id='d' style='width:50px'>foo</div>\n" + "<script>\n" + "var d = document.getElementById('d');\n" + "var style = d.currentStyle;\n" + "style = style ? style : window.getComputedStyle(d,'');\n" + "alert(style.width);\n" + "</script>\n" + "</body>\n" + "</html>"; loadPageWithAlerts2(html); } /** * @throws Exception if an error occurs */ @Test @Alerts(IE = { "1em 1em", "1em 1em", "1em 1em", "1em 1em", "1em 1em", "1em 1em", "1em 1em", "1em 1em", "1em 1em", "1em 1em", "1em 1em", "1em 1em", "1em 1em", "1em 1em" }, FF = { "1em 16px", "1em 16px", "1em 16px", "1em 16px", "1em 16px", "1em 16px", "1em 16px", "1em 16px", "1em 16px", "1em 16px", "1em 16px", "1em 16px", "1em 16px", "1em 16px" }) public void lengthsConvertedToPixels() throws Exception { final String html = "<html><body>\n" + "<div id='d' style='width:1em; height:1em; border:1em solid black; padding:1em; margin:1em;'>d</div>\n" + "<script>\n" + "var d = document.getElementById('d');\n" + "var cs = d.currentStyle;\n" + "if(!cs) cs = window.getComputedStyle(d, '');\n" + "alert(d.style.width + ' ' + cs.width);\n" + "alert(d.style.height + ' ' + cs.height);\n" + "alert(d.style.borderBottomWidth + ' ' + cs.borderBottomWidth);\n" + "alert(d.style.borderLeftWidth + ' ' + cs.borderLeftWidth);\n" + "alert(d.style.borderTopWidth + ' ' + cs.borderTopWidth);\n" + "alert(d.style.borderRightWidth + ' ' + cs.borderRightWidth);\n" + "alert(d.style.paddingBottom + ' ' + cs.paddingBottom);\n" + "alert(d.style.paddingLeft + ' ' + cs.paddingLeft);\n" + "alert(d.style.paddingTop + ' ' + cs.paddingTop);\n" + "alert(d.style.paddingRight + ' ' + cs.paddingRight);\n" + "alert(d.style.marginBottom + ' ' + cs.marginBottom);\n" + "alert(d.style.marginLeft + ' ' + cs.marginLeft);\n" + "alert(d.style.marginTop + ' ' + cs.marginTop);\n" + "alert(d.style.marginRight + ' ' + cs.marginRight);\n" + "</script>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * @throws Exception if an error occurs */ @Test @Alerts(IE = "block block block block block block block block block", FF = "table table-header-group table-row-group table-cell table-row table-cell block list-item block") public void defaultDisplayValues() throws Exception { final String html = "<html><body>\n" + " <table id='table'>\n" + " <thead id='thead'><tr id='tr'><th id='th'>header</th></tr></thead>\n" + " <tbody id='tbody'><tr><td id='td'>body</td></tr></tbody>\n" + " </table>\n" + " <ul id='ul'><li id='li'>blah</li></ul>\n" + " <div id='div'></div>\n" + " <script>\n" + " function x(id) {\n" + " var e = document.getElementById(id);\n" + " return e.currentStyle ? e.currentStyle.display : window.getComputedStyle(e, '').display;\n" + " }\n" + " </script>\n" + " <script>\n" + " alert(x('table') + ' ' + x('thead') + ' ' + x('tbody') + ' ' + x('th') + ' ' + x('tr') +\n" + " ' ' + x('td') + ' ' + x('ul') + ' ' + x('li') + ' ' + x('div'));</script>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * @throws Exception if an error occurs */ @Test @Alerts(IE = { "transparent", "red", "white" }, FF = { "transparent", "rgb(255, 0, 0)", "rgb(255, 255, 255)" }) public void backgroundColor() throws Exception { final String html = "<html><body>\n" + "<div id='d0'>div 0</div>\n" + "<div id='d1' style='background: red'>d</div>\n" + "<div id='d2' style='background: white url(http://htmlunit.sf.net/foo.png) repeat-x fixed top right'>" + "second div</div>\n" + "<script>\n" + "function getStyle(x) {\n" + " var d = document.getElementById(x);\n" + " var cs = d.currentStyle;\n" + " if(!cs) cs = window.getComputedStyle(d, '');\n" + " return cs;\n" + "}\n" + "var cs0 = getStyle('d0');\n" + "alert(cs0.backgroundColor);\n" + "var cs1 = getStyle('d1');\n" + "alert(cs1.backgroundColor);\n" + "var cs2 = getStyle('d2');\n" + "alert(cs2.backgroundColor);\n" + "</script>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * @throws Exception if an error occurs */ @Test @Alerts("10px") public void fontSize() throws Exception { final String html = "<html><body>\n" + "<div id='d0' style='font-size: 10px;'>\n" + "<div id='d1'>inside</div>\n" + "</div>\n" + "<script>\n" + "function getStyle(x) {\n" + " var d = document.getElementById(x);\n" + " var cs = d.currentStyle;\n" + " if(!cs) cs = window.getComputedStyle(d, '');\n" + " return cs;\n" + "}\n" + "var cs1 = getStyle('d1');\n" + "alert(cs1.fontSize);\n" + "</script>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * @throws Exception if the test fails */ @Test @Alerts(FF = { "1256px", "auto" }, IE = { "auto", "auto" }) public void computedWidthOfHiddenElements() throws Exception { final String content = "<html><head><title>foo</title><script>\n" + " function test() {\n" + " var div1 = document.getElementById('myDiv1');\n" + " var cs1 = window.getComputedStyle ? window.getComputedStyle(div1, null) : div1.currentStyle;\n" + " alert(cs1.width);\n" + " var div2 = document.getElementById('myDiv2');\n" + " var cs2 = window.getComputedStyle ? window.getComputedStyle(div2, null) : div2.currentStyle;\n" + " alert(cs2.width);\n" + " }\n" + "</script></head><body onload='test()'>\n" + " <div id='myDiv1'></div>\n" + " <div id='myDiv2' style='display:none'/>\n" + "</body></html>"; loadPageWithAlerts2(content); } /** * Verifies that at least one CSS attribute is correctly inherited by default. * Required by the MochiKit tests. * @throws Exception if an error occurs */ @Test @Alerts({ ",", "separate,separate", "collapse,", "collapse,collapse" }) public void inheritedImplicitly() throws Exception { final String html = "<html><body><table id='a'><tr id='b'><td>a</td></tr></table><script>\n" + "var a = document.getElementById('a');\n" + "var b = document.getElementById('b');\n" + "var as = a.style;\n" + "var bs = b.style;\n" + "var acs = window.getComputedStyle ? window.getComputedStyle(a,null) : a.currentStyle;\n" + "var bcs = window.getComputedStyle ? window.getComputedStyle(b,null) : b.currentStyle;\n" + "alert(as.borderCollapse + ',' + bs.borderCollapse);\n" + "alert(acs.borderCollapse + ',' + bcs.borderCollapse);\n" + "as.borderCollapse = 'collapse';\n" + "alert(as.borderCollapse + ',' + bs.borderCollapse);\n" + "alert(acs.borderCollapse + ',' + bcs.borderCollapse);\n" + "</script></body></html>"; loadPageWithAlerts2(html); } /** * Verifies that when the class of an ancestor node matters for the effective style, * it is recomputed if the class of the ancestor node changes. * @throws Exception if an error occurs */ @Test @Alerts(FF = { "underline", "none", "underline" }, IE = { "underline", "underline", "underline" }) public void changeInParentClassNodeReferencedByRule() throws Exception { final String html = "<html><head>\n" + "<script>\n" + "function readDecoration(id) {\n" + " var e = document.getElementById(id);\n" + " var s = window.getComputedStyle ? window.getComputedStyle(e,null) : e.currentStyle;\n" + " alert(s.textDecoration)\n" + "}\n" + "function test() {\n" + " var fooA = document.getElementById('fooA');\n" + " readDecoration('fooB')\n" + " fooA.setAttribute('class', '');\n" + " readDecoration('fooB')\n" + " fooA.setAttribute('class', 'A');\n" + " readDecoration('fooB')\n" + "}\n" + "</script>\n" + "<style>\n" + ".A .B { text-decoration: underline }\n" + "</style>\n" + "</head><body onload='test()'>\n" + "<div class='A' id='fooA'>A\n" + "<div class='B' id='fooB'>B</div></div>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * @throws Exception if an error occurs */ @Test @Alerts(FF = { "200px,400px", "200,400", "200px,400px", "50%,25%", "100,100", "100px,100px" }, IE = { "200px,400px", "200,400", "200px,400px", "50%,25%", "100,100", "50%,25%" }) public void widthAndHeightPercentagesAndPx() throws Exception { final String html = "<html><body onload='test()'>\n" + "<div id='d1' style='width:200px;height:400px'><div id='d2' style='width:50%;height:25%'></div></div>\n" + "<script>\n" + " function test(){\n" + " var d1 = document.getElementById('d1');\n" + " var s1 = window.getComputedStyle ? window.getComputedStyle(d1, null) : d1.currentStyle;\n" + " var d2 = document.getElementById('d2');\n" + " var s2 = window.getComputedStyle ? window.getComputedStyle(d2, null) : d2.currentStyle;\n" + " alert(d1.style.width + ',' + d1.style.height);\n" + " alert(d1.offsetWidth + ',' + d1.offsetHeight);\n" + " alert(s1.width + ',' + s1.height);\n" + " alert(d2.style.width + ',' + d2.style.height);\n" + " alert(d2.offsetWidth + ',' + d2.offsetHeight);\n" + " alert(s2.width + ',' + s2.height);\n" + " }\n" + "</script>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * @throws Exception if an error occurs */ @Test @Alerts(FF = { "10em,20em", "160,320", "160px,320px", "50%,25%", "80,80", "80px,80px" }, IE = { "10em,20em", "160,320", "10em,20em", "50%,25%", "80,80", "50%,25%" }) public void widthAndHeightPercentagesAndEm() throws Exception { final String html = "<html><body onload='test()'>\n" + "<div id='d1' style='width:10em;height:20em'><div id='d2' style='width:50%;height:25%'></div></div>\n" + "<script>\n" + " function test(){\n" + " var d1 = document.getElementById('d1');\n" + " var s1 = window.getComputedStyle ? window.getComputedStyle(d1, null) : d1.currentStyle;\n" + " var d2 = document.getElementById('d2');\n" + " var s2 = window.getComputedStyle ? window.getComputedStyle(d2, null) : d2.currentStyle;\n" + " alert(d1.style.width + ',' + d1.style.height);\n" + " alert(d1.offsetWidth + ',' + d1.offsetHeight);\n" + " alert(s1.width + ',' + s1.height);\n" + " alert(d2.style.width + ',' + d2.style.height);\n" + " alert(d2.offsetWidth + ',' + d2.offsetHeight);\n" + " alert(s2.width + ',' + s2.height);\n" + " }\n" + "</script>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * NullPointerException occurred in offsetX computation in HtmlUnit-2.7-SNAPSHOT (19.01.2010). * @throws Exception if an error occurs */ @Test @Alerts({ "true", "true" }) public void widthAndHeightPercentagesHTML() throws Exception { final String html = "<html style='height: 100%'>\n" + "<body>\n" + "<script>\n" + " var h = document.documentElement;\n" + " alert(h.offsetWidth > 0);\n" + " alert(h.offsetHeight > 0);\n" + "</script>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * @throws Exception if the test fails */ @Test @Browsers(Browser.FF) @Alerts({ "red", "blue" }) public void getPropertyValue() throws Exception { final String html = "<html><head><title>First</title><script>\n" + "function doTest() {\n" + " var d = document.getElementById('div1');\n" + " var s = window.getComputedStyle(d, null);\n" + " alert(s.getPropertyValue('test'));\n" + " alert(s.getPropertyValue('color'));\n" + "}\n" + "</script>\n" + "<style>#div1 { test: red }</style>\n" + "</head>\n" + "<body onload='doTest()'>\n" + "<div id='div1' style='color: blue'>foo</div></body></html>"; loadPageWithAlerts2(html); } /** * @throws Exception if the test fails */ @Test @Alerts({ "roman", "swiss", "roman" }) public void handleImportant() throws Exception { final String html = "<html><head><title>First</title><script>\n" + " function doTest() {\n" + " alertFF(document.getElementById('div1'));\n" + " alertFF(document.getElementById('div2'));\n" + " alertFF(document.getElementById('div3'));\n" + " }\n" + " function alertFF(e) {\n" + " if (window.getComputedStyle) {\n" + " var s = window.getComputedStyle(e, null);\n" + " alert(s.getPropertyValue('font-family'));\n" + " } else {\n" + " alert(e.currentStyle.fontFamily);\n" + " }\n" + " }\n" + "</script>\n" + " <style>#div1 { font-family: swiss }</style>\n" + " <style>#div2 { font-family: swiss !important }</style>\n" + " <style>#div3 { font-family: swiss !important }</style>\n" + "</head>\n" + "<body onload='doTest()'>\n" + " <div id='div1' style='font-family: roman'>foo</div>" + " <div id='div2' style='font-family: roman'>foo</div>" + " <div id='div3' style='font-family: roman !important'>foo</div>" + "</body></html>"; loadPageWithAlerts2(html); } }
true
true
public void stringPropertiesFF3_6() throws Exception { final String html = "<html><head><title>First</title><script>\n" + "function test() {\n" + " var e = document.getElementById('myDiv');\n" + " var str = '';\n" + " for (var i in e.style) {\n" + " var s1 = eval('e.style.' + i);\n" + " var s2 = eval('window.getComputedStyle(e,null).' + i);\n" + " if(typeof s1 == 'string')\n" + " str += i + '=' + s1 + ':' + s2 + ',';\n" + " }\n" + " document.getElementById('myTextarea').value = str;\n" + "}\n" + "</script></head>\n" + "<body onload='test()'>\n" + " <div id='myDiv'><br>\n" + " <textarea id='myTextarea' cols='120' rows='20'></textarea>\n" + "</body></html>"; final String expectedText = "opacity=:1,background=:," + "height=:362px,textAlign=:start,right=:auto,bottom=:auto,fontSize=:16px,backgroundColor=:transparent," + "letterSpacing=:normal,verticalAlign=:baseline,color=:rgb(0, 0, 0),top=:auto,width=:1256px," + "display=:block,zIndex=:auto,position=:static,left=:auto,visibility=:visible,cssText=:,azimuth=:," + "backgroundAttachment=:scroll,backgroundImage=:none,backgroundPosition=:0% 0%,backgroundRepeat=:repeat," + "border=:,borderCollapse=:separate,borderColor=:,borderSpacing=:0px 0px,borderStyle=:,borderTop=:," + "borderRight=:,borderBottom=:,borderLeft=:,borderTopColor=:rgb(0, 0, 0),borderRightColor=:rgb(0, 0, 0)," + "borderBottomColor=:rgb(0, 0, 0),borderLeftColor=:rgb(0, 0, 0),borderTopStyle=:none," + "borderRightStyle=:none,borderBottomStyle=:none,borderLeftStyle=:none,borderTopWidth=:0px," + "borderRightWidth=:0px,borderBottomWidth=:0px,borderLeftWidth=:0px,borderWidth=:,captionSide=:top," + "clear=:none,clip=:auto,content=:none,counterIncrement=:none,counterReset=:none,cue=:,cueAfter=:," + "cueBefore=:,cursor=:auto,direction=:ltr,elevation=:,emptyCells=:-moz-show-background,cssFloat=:none," + "font=:,fontFamily=:serif,fontSizeAdjust=:none,fontStretch=:normal,fontStyle=:normal,fontVariant=:normal," + "fontWeight=:400,lineHeight=:20px,listStyle=:,listStyleImage=:none,listStylePosition=:outside," + "listStyleType=:disc,margin=:,marginTop=:0px,marginRight=:0px,marginBottom=:0px,marginLeft=:0px," + "markerOffset=:auto,marks=:,maxHeight=:none,maxWidth=:none,minHeight=:0px,minWidth=:0px,orphans=:," + "outline=:,outlineColor=:rgb(0, 0, 0),outlineStyle=:none,outlineWidth=:0px,overflow=:visible,padding=:," + "paddingTop=:0px,paddingRight=:0px,paddingBottom=:0px,paddingLeft=:0px,page=:,pageBreakAfter=:auto," + "pageBreakBefore=:auto,pageBreakInside=:,pause=:,pauseAfter=:,pauseBefore=:,pitch=:,pitchRange=:," + "quotes=:,richness=:,size=:,speak=:,speakHeader=:," // TODO quotes + "speakNumeral=:,speakPunctuation=:,speechRate=:,stress=:,tableLayout=:auto,textDecoration=:none," + "textIndent=:0px,textShadow=:none,textTransform=:none,unicodeBidi=:embed,voiceFamily=:,volume=:," + "whiteSpace=:normal,widows=:,wordSpacing=:0px,MozAppearance=:none,MozBackgroundClip=:border," + "MozBackgroundInlinePolicy=:continuous,MozBackgroundOrigin=:padding,MozBinding=:none," + "MozBorderBottomColors=:none," + "MozBorderLeftColors=:none,MozBorderRightColors=:none,MozBorderTopColors=:none,MozBorderRadius=:," + "MozBorderRadiusTopleft=:0px,MozBorderRadiusTopright=:0px,MozBorderRadiusBottomleft=:0px," + "MozBorderRadiusBottomright=:0px,MozBoxAlign=:stretch,MozBoxDirection=:normal,MozBoxFlex=:0," + "MozBoxOrient=:horizontal,MozBoxOrdinalGroup=:1,MozBoxPack=:start,MozBoxSizing=:content-box," + "MozColumnCount=:auto,MozColumnWidth=:auto,MozColumnGap=:16px,MozFloatEdge=:content-box," + "MozForceBrokenImageIcon=:0,MozImageRegion=:auto,MozMarginEnd=:,MozMarginStart=:,MozOpacity=:1," + "MozOutline=:,MozOutlineColor=:rgb(0, 0, 0),MozOutlineRadius=:,MozOutlineRadiusTopleft=:0px," + "MozOutlineRadiusTopright=:0px,MozOutlineRadiusBottomleft=:0px,MozOutlineRadiusBottomright=:0px," + "MozOutlineStyle=:none,MozOutlineWidth=:0px," + "MozOutlineOffset=:0px,MozPaddingEnd=:,MozPaddingStart=:,MozUserFocus=:none,MozUserInput=:auto," + "MozUserModify=:read-only,MozUserSelect=:auto,outlineOffset=:0px,overflowX=:visible,overflowY=:visible," + "imeMode=:auto,MozBorderEnd=:,MozBorderEndColor=:,MozBorderEndStyle=:,MozBorderEndWidth=:," + "MozBorderStart=:,MozBorderStartColor=:,MozBorderStartStyle=:,MozBorderStartWidth=:," + "MozStackSizing=:stretch-to-fit,MozBoxShadow=:none,MozBorderImage=:none,MozColumnRule=:," + "MozColumnRuleWidth=:0px,MozColumnRuleStyle=:none," + "MozColumnRuleColor=:rgb(0, 0, 0),wordWrap=:normal,MozTransform=:none,MozTransformOrigin=:50% 50%," + "MozWindowShadow=:default,MozBackgroundSize=:auto auto,pointerEvents=:auto,"; final WebDriver driver = loadPage2(html); final List<String> expectedValues = stringProperties(expectedText); final List<String> collectedValues = stringProperties(driver.findElement(By.id("myTextarea")).getText()); assertEquals(expectedValues.toString(), collectedValues.toString()); }
public void stringPropertiesFF3_6() throws Exception { final String html = "<html><head><title>First</title><script>\n" + "function test() {\n" + " var e = document.getElementById('myDiv');\n" + " var str = '';\n" + " for (var i in e.style) {\n" + " var s1 = eval('e.style.' + i);\n" + " var s2 = eval('window.getComputedStyle(e,null).' + i);\n" + " if(typeof s1 == 'string')\n" + " str += i + '=' + s1 + ':' + s2 + ',';\n" + " }\n" + " document.getElementById('myTextarea').value = str;\n" + "}\n" + "</script></head>\n" + "<body onload='test()'>\n" + " <div id='myDiv'><br>\n" + " <textarea id='myTextarea' cols='120' rows='20'></textarea>\n" + "</body></html>"; final String expectedText = "opacity=:1,background=:," + "height=:362px,textAlign=:start,right=:auto,bottom=:auto,fontSize=:16px,backgroundColor=:transparent," + "letterSpacing=:normal,verticalAlign=:baseline,color=:rgb(0, 0, 0),top=:auto,width=:1256px," + "display=:block,zIndex=:auto,position=:static,left=:auto,visibility=:visible,cssText=:,azimuth=:," + "backgroundAttachment=:scroll,backgroundImage=:none,backgroundPosition=:0% 0%,backgroundRepeat=:repeat," + "border=:,borderCollapse=:separate,borderColor=:,borderSpacing=:0px 0px,borderStyle=:,borderTop=:," + "borderRight=:,borderBottom=:,borderLeft=:,borderTopColor=:rgb(0, 0, 0),borderRightColor=:rgb(0, 0, 0)," + "borderBottomColor=:rgb(0, 0, 0),borderLeftColor=:rgb(0, 0, 0),borderTopStyle=:none," + "borderRightStyle=:none,borderBottomStyle=:none,borderLeftStyle=:none,borderTopWidth=:0px," + "borderRightWidth=:0px,borderBottomWidth=:0px,borderLeftWidth=:0px,borderWidth=:,captionSide=:top," + "clear=:none,clip=:auto,content=:none,counterIncrement=:none,counterReset=:none,cue=:,cueAfter=:," + "cueBefore=:,cursor=:auto,direction=:ltr,elevation=:,emptyCells=:-moz-show-background,cssFloat=:none," + "font=:,fontFamily=:serif,fontSizeAdjust=:none,fontStretch=:normal,fontStyle=:normal,fontVariant=:normal," + "fontWeight=:400,lineHeight=:20px,listStyle=:,listStyleImage=:none,listStylePosition=:outside," + "listStyleType=:disc,margin=:,marginTop=:0px,marginRight=:0px,marginBottom=:0px,marginLeft=:0px," + "markerOffset=:auto,marks=:,maxHeight=:none,maxWidth=:none,minHeight=:0px,minWidth=:0px,orphans=:," + "outline=:,outlineColor=:rgb(0, 0, 0),outlineStyle=:none,outlineWidth=:0px,overflow=:visible,padding=:," + "paddingTop=:0px,paddingRight=:0px,paddingBottom=:0px,paddingLeft=:0px,page=:,pageBreakAfter=:auto," + "pageBreakBefore=:auto,pageBreakInside=:,pause=:,pauseAfter=:,pauseBefore=:,pitch=:,pitchRange=:," + "quotes=:,richness=:,size=:,speak=:,speakHeader=:," // TODO quotes + "speakNumeral=:,speakPunctuation=:,speechRate=:,stress=:,tableLayout=:auto,textDecoration=:none," + "textIndent=:0px,textShadow=:none,textTransform=:none,unicodeBidi=:embed,voiceFamily=:,volume=:," + "whiteSpace=:normal,widows=:,wordSpacing=:0px,MozAppearance=:none,MozBackgroundClip=:border," + "MozBackgroundInlinePolicy=:continuous,MozBackgroundOrigin=:padding,MozBinding=:none," + "MozBorderBottomColors=:none," + "MozBorderLeftColors=:none,MozBorderRightColors=:none,MozBorderTopColors=:none,MozBorderRadius=:," + "MozBorderRadiusTopleft=:0px,MozBorderRadiusTopright=:0px,MozBorderRadiusBottomleft=:0px," + "MozBorderRadiusBottomright=:0px,MozBoxAlign=:stretch,MozBoxDirection=:normal,MozBoxFlex=:0," + "MozBoxOrient=:horizontal,MozBoxOrdinalGroup=:1,MozBoxPack=:start,MozBoxSizing=:content-box," + "MozColumnCount=:auto,MozColumnWidth=:auto,MozColumnGap=:16px,MozFloatEdge=:content-box," + "MozForceBrokenImageIcon=:0,MozImageRegion=:auto,MozMarginEnd=:,MozMarginStart=:,MozOpacity=:1," + "MozOutline=:,MozOutlineColor=:rgb(0, 0, 0),MozOutlineRadius=:,MozOutlineRadiusTopleft=:0px," + "MozOutlineRadiusTopright=:0px,MozOutlineRadiusBottomleft=:0px,MozOutlineRadiusBottomright=:0px," + "MozOutlineStyle=:none,MozOutlineWidth=:0px," + "MozOutlineOffset=:0px,MozPaddingEnd=:,MozPaddingStart=:,MozUserFocus=:none,MozUserInput=:auto," + "MozUserModify=:read-only,MozUserSelect=:auto,outlineOffset=:0px,overflowX=:visible,overflowY=:visible," + "imeMode=:auto,MozBorderEnd=:,MozBorderEndColor=:,MozBorderEndStyle=:,MozBorderEndWidth=:," + "MozBorderStart=:,MozBorderStartColor=:,MozBorderStartStyle=:,MozBorderStartWidth=:," + "MozStackSizing=:stretch-to-fit,MozBoxShadow=:none,MozBorderImage=:none,MozColumnRule=:," + "MozColumnRuleWidth=:0px,MozColumnRuleStyle=:none," + "MozColumnRuleColor=:rgb(0, 0, 0),wordWrap=:normal,MozTransform=:none,MozTransformOrigin=:50% 50%," + "MozWindowShadow=:default,MozBackgroundSize=:auto auto,pointerEvents=:auto,"; final WebDriver driver = loadPage2(html); final List<String> expectedValues = stringProperties(expectedText); final List<String> collectedValues = stringProperties(driver.findElement(By.id("myTextarea")). getAttribute("value")); assertEquals(expectedValues.toString(), collectedValues.toString()); }
diff --git a/src/android2iphone/android/view/Window.java b/src/android2iphone/android/view/Window.java index 4c7a6f78..7205d7f7 100644 --- a/src/android2iphone/android/view/Window.java +++ b/src/android2iphone/android/view/Window.java @@ -1,175 +1,175 @@ /* * Copyright (c) 2004-2009 XMLVM --- An XML-based Programming Language * * 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., 675 Mass * Ave, Cambridge, MA 02139, USA. * * For more information, visit the XMLVM Home Page at http://www.xmlvm.org */ package android.view; import org.xmlvm.iphone.CGAffineTransform; import org.xmlvm.iphone.CGRect; import org.xmlvm.iphone.UIApplication; import org.xmlvm.iphone.UIColor; import org.xmlvm.iphone.UIScreen; import org.xmlvm.iphone.UIWindow; import android.app.Activity; import android.content.pm.ActivityInfo; import android.internal.LayoutManager; import android.view.View.MeasureSpec; import android.view.ViewGroup.LayoutParams; /** * iPhone Implementation of Android's Window class. * * @see http://developer.android.com/reference/android/view/Window.html */ public class Window { public static final int FEATURE_NO_TITLE = 1; private Activity activity; private UIWindow iWindow; private CGRect rect; private View contentView; public Window(Activity parent) { this.activity = parent; UIScreen screen = UIScreen.mainScreen(); rect = screen.getApplicationFrame(); iWindow = new UIWindow(rect); iWindow.setBackgroundColor(UIColor.colorWithRGBA(0.0941f, 0.0941f, 0.0941f, 1.0f)); } public void setContentView(View view) { if (contentView != null) { xmlvmSetHidden(true); contentView.xmlvmGetUIView().removeFromSuperview(); contentView.xmlvmSetParent(null); } contentView = view; adjustFrameSize(); CGRect viewRect = new CGRect(rect); viewRect.origin.x = viewRect.origin.y = 0; view.xmlvmGetUIView().setFrame(viewRect); iWindow.addSubview(view.xmlvmGetUIView()); } public void setContentView(int id) { View v = LayoutManager.getLayout(activity, id); setContentView(v); } public void setFlags(int flags, int mask) { int maskedFlags = (flags & mask); if ((maskedFlags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0) { UIApplication.sharedApplication().setStatusBarHidden(true); adjustFrameSize(); } } public void xmlvmSetHidden(boolean flag) { if (flag) { iWindow.setHidden(true); } else { iWindow.makeKeyAndVisible(); iWindow.setHidden(false); } } public void xmlvmRemoveWindow() { xmlvmSetHidden(true); if (contentView != null) { contentView.xmlvmGetUIView().removeFromSuperview(); contentView.xmlvmSetParent(null); } iWindow = null; } /** * Internal. Not part of Android API. Called whenever the size or * orientation of the top-level window has changed (e.g., when the status * bar is made invisible). */ public void adjustFrameSize() { UIScreen screen = UIScreen.mainScreen(); rect = screen.getApplicationFrame(); iWindow.setTransform(null); iWindow.setFrame(rect); if (activity.getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { float t = rect.size.height; rect.size.height = rect.size.width; rect.size.width = t; iWindow.setFrame(rect); CGAffineTransform rotation = CGAffineTransform .makeRotation((float) ((Math.PI / 180) * 90)); // TODO Translate should be 90, 90 for visible status bar (i.e., // non-fullscreen) CGAffineTransform translation = CGAffineTransform.translate(rotation, 80, 80); iWindow.setTransform(translation); } if (contentView != null) { layoutContentView(); } } private void layoutContentView() { int widthMeasureSpec; int heightMeasureSpec; LayoutParams lp = contentView.getLayoutParams(); - if (lp == null || lp.width != LayoutParams.FILL_PARENT) { + if (lp == null || lp.width == LayoutParams.WRAP_CONTENT) { widthMeasureSpec = MeasureSpec.makeMeasureSpec((int) rect.size.width, MeasureSpec.AT_MOST); } else { widthMeasureSpec = MeasureSpec.makeMeasureSpec((int) rect.size.width, MeasureSpec.EXACTLY); } - if (lp == null || lp.height != LayoutParams.FILL_PARENT) { + if (lp == null || lp.height == LayoutParams.WRAP_CONTENT) { heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) rect.size.height, MeasureSpec.AT_MOST); } else { heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) rect.size.height, MeasureSpec.EXACTLY); } contentView.measure(widthMeasureSpec, heightMeasureSpec); contentView.layout(0, 0, contentView.getMeasuredWidth(), contentView.getMeasuredHeight()); } /** * Internal. Not part of Android API. */ public CGRect getCGRect() { return rect; } /** * @param id * @return */ public View findViewById(int id) { if (contentView instanceof ViewGroup) { ViewGroup vg = (ViewGroup) contentView; return vg.findViewById(id); } else if (contentView.getId() == id) { return contentView; } else { return null; } } }
false
true
private void layoutContentView() { int widthMeasureSpec; int heightMeasureSpec; LayoutParams lp = contentView.getLayoutParams(); if (lp == null || lp.width != LayoutParams.FILL_PARENT) { widthMeasureSpec = MeasureSpec.makeMeasureSpec((int) rect.size.width, MeasureSpec.AT_MOST); } else { widthMeasureSpec = MeasureSpec.makeMeasureSpec((int) rect.size.width, MeasureSpec.EXACTLY); } if (lp == null || lp.height != LayoutParams.FILL_PARENT) { heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) rect.size.height, MeasureSpec.AT_MOST); } else { heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) rect.size.height, MeasureSpec.EXACTLY); } contentView.measure(widthMeasureSpec, heightMeasureSpec); contentView.layout(0, 0, contentView.getMeasuredWidth(), contentView.getMeasuredHeight()); }
private void layoutContentView() { int widthMeasureSpec; int heightMeasureSpec; LayoutParams lp = contentView.getLayoutParams(); if (lp == null || lp.width == LayoutParams.WRAP_CONTENT) { widthMeasureSpec = MeasureSpec.makeMeasureSpec((int) rect.size.width, MeasureSpec.AT_MOST); } else { widthMeasureSpec = MeasureSpec.makeMeasureSpec((int) rect.size.width, MeasureSpec.EXACTLY); } if (lp == null || lp.height == LayoutParams.WRAP_CONTENT) { heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) rect.size.height, MeasureSpec.AT_MOST); } else { heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) rect.size.height, MeasureSpec.EXACTLY); } contentView.measure(widthMeasureSpec, heightMeasureSpec); contentView.layout(0, 0, contentView.getMeasuredWidth(), contentView.getMeasuredHeight()); }
diff --git a/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java b/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java index a49960435..77cee4cc7 100644 --- a/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java +++ b/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java @@ -1,449 +1,451 @@ package net.aufdemrand.denizen.objects; import net.aufdemrand.denizen.flags.FlagManager; import net.aufdemrand.denizen.tags.Attribute; import net.aufdemrand.denizen.tags.core.PlayerTags; import net.aufdemrand.denizen.utilities.DenizenAPI; import net.aufdemrand.denizen.utilities.debugging.dB; import net.aufdemrand.denizen.utilities.depends.Depends; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; import java.util.HashMap; import java.util.Map; public class dPlayer implements dObject { ///////////////////// // STATIC METHODS ///////////////// static Map<String, dPlayer> players = new HashMap<String, dPlayer>(); public static dPlayer mirrorBukkitPlayer(Player player) { if (players.containsKey(player.getName())) return players.get(player.getName()); else return new dPlayer(player); } ///////////////////// // OBJECT FETCHER ///////////////// @ObjectFetcher("p") public static dPlayer valueOf(String string) { if (string == null) return null; string = string.replace("p@", ""); //////// // Match player name OfflinePlayer returnable = null; for (OfflinePlayer player : Bukkit.getOfflinePlayers()) if (player.getName().equalsIgnoreCase(string)) { returnable = player; break; } if (returnable != null) { if (players.containsKey(returnable.getName())) return players.get(returnable.getName()); else return new dPlayer(returnable); } else dB.echoError("Invalid Player! '" + string + "' could not be found. Has the player logged off?"); return null; } public static boolean matches(String arg) { arg = arg.replace("p@", ""); OfflinePlayer returnable = null; for (OfflinePlayer player : Bukkit.getOfflinePlayers()) if (player.getName().equalsIgnoreCase(arg)) { returnable = player; break; } if (returnable != null) return true; return false; } ///////////////////// // STATIC CONSTRUCTORS ///////////////// public dPlayer(OfflinePlayer player) { if (player == null) return; this.player_name = player.getName(); // Keep in a map to avoid multiple instances of a dPlayer per player. players.put(this.player_name, this); } ///////////////////// // INSTANCE FIELDS/METHODS ///////////////// String player_name; public Player getPlayerEntity() { return Bukkit.getPlayer(player_name); } public OfflinePlayer getOfflinePlayer() { return Bukkit.getOfflinePlayer(player_name); } public String getName() { return player_name; } public dLocation getLocation() { if (isOnline()) return new dLocation(getPlayerEntity().getLocation()); else return null; } public boolean isOnline() { if (Bukkit.getPlayer(player_name) != null) return true; return false; } ///////////////////// // DSCRIPTARGUMENT METHODS ///////////////// private String prefix = "Player"; @Override public String getPrefix() { return prefix; } @Override public dPlayer setPrefix(String prefix) { this.prefix = prefix; return this; } @Override public String debug() { return (prefix + "='<A>" + identify() + "<G>' "); } @Override public boolean isUnique() { return true; } @Override public String getType() { return "player"; } @Override public String identify() { return "p@" + player_name; } @Override public String toString() { return identify(); } @Override public String getAttribute(Attribute attribute) { if (attribute == null) return "null"; dB.log("getAttribute: " + getType() + " ---> " + attribute.attributes.toString()); if (attribute.startsWith("has_played_before")) return new Element(String.valueOf(getOfflinePlayer().hasPlayedBefore())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_op")) return new Element(String.valueOf(getOfflinePlayer().isOp())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("first_played")) return new Element(String.valueOf(getOfflinePlayer().getFirstPlayed())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("last_played")) return new Element(String.valueOf(getOfflinePlayer().getLastPlayed())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_banned")) return new Element(String.valueOf(getOfflinePlayer().isBanned())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_whitelisted")) return new Element(String.valueOf(getOfflinePlayer().isWhitelisted())) .getAttribute(attribute.fulfill(1)); // This can be parsed later with more detail if the player is online, so only check for offline. if (attribute.startsWith("name") && !isOnline()) return new Element(player_name).getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_online")) return new Element(String.valueOf(isOnline())).getAttribute(attribute.fulfill(1)); if (attribute.startsWith("chat_history_list")) return new dList(PlayerTags.playerChatHistory.get(player_name)) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("chat_history")) { int x = 1; if (attribute.hasContext(1) && aH.matchesInteger(attribute.getContext(1))) x = attribute.getIntContext(1); return new Element(PlayerTags.playerChatHistory.get(player_name).get(x - 1)) .getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("location.bed_spawn")) return new dLocation(getOfflinePlayer().getBedSpawnLocation()) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("money")) { if(Depends.economy != null) { if (attribute.startsWith("money.currency_singular")) return new Element(Depends.economy.currencyNameSingular()) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("money.currency")) return new Element(Depends.economy.currencyNamePlural()) .getAttribute(attribute.fulfill(2)); return new Element(String.valueOf(Depends.economy.getBalance(player_name))) .getAttribute(attribute.fulfill(1)); } else { dB.echoError("No economy loaded! Have you installed Vault and a compatible economy plugin?"); return null; } } if (!isOnline()) return new Element(identify()).getAttribute(attribute); // Player is required to be online after this point... if (attribute.startsWith("xp.to_next_level")) return new Element(String.valueOf(getPlayerEntity().getExpToLevel())) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("xp.total")) return new Element(String.valueOf(getPlayerEntity().getTotalExperience())) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("xp.level")) return new Element(getPlayerEntity().getLevel()) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("xp")) return new Element(String.valueOf(getPlayerEntity().getExp() * 100)) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("equipment")) // The only way to return correct size for dInventory // created from equipment is to use a CRAFTING type // that has the expected 4 slots return new dInventory(InventoryType.CRAFTING).add(getPlayerEntity().getInventory().getArmorContents()) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("inventory")) return new dInventory(getPlayerEntity().getInventory()) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("item_in_hand")) return new dItem(getPlayerEntity().getItemInHand()) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("name.display")) return new Element(getPlayerEntity().getDisplayName()) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("name.list")) return new Element(getPlayerEntity().getPlayerListName()) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("name")) return new Element(player_name).getAttribute(attribute.fulfill(1)); if (attribute.startsWith("location.compass_target")) return new dLocation(getPlayerEntity().getCompassTarget()) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("location")) return new dLocation(getPlayerEntity().getLocation()) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("food_level.formatted")) { int maxHunger = getPlayerEntity().getMaxHealth(); if (attribute.hasContext(2)) maxHunger = attribute.getIntContext(2); if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .10) return new Element("starving").getAttribute(attribute.fulfill(2)); else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .40) return new Element("famished").getAttribute(attribute.fulfill(2)); else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .75) return new Element("parched").getAttribute(attribute.fulfill(2)); else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < 1) return new Element("hungry").getAttribute(attribute.fulfill(2)); else return new Element("healthy").getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("food_level")) return new Element(String.valueOf(getPlayerEntity().getFoodLevel())) .getAttribute(attribute.fulfill(1)); - if (attribute.startsWith("permission")) { + if (attribute.startsWith("permission") + || attribute.startsWith("has_permission")) { if (Depends.permissions == null) { dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?"); return null; } String permission = attribute.getContext(1); // Non-world specific permission - if (attribute.startsWith("permission.global")) + if (attribute.getAttribute(2).startsWith("global")) return new Element(String.valueOf(Depends.permissions.has((World) null, player_name, permission))) .getAttribute(attribute.fulfill(2)); // Permission in current world return new Element(String.valueOf(Depends.permissions.has(getPlayerEntity(), permission))) .getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("flag")) { if (attribute.hasContext(1)) { if (FlagManager.playerHasFlag(this, attribute.getContext(1))) return new dList(DenizenAPI.getCurrentInstance().flagManager() .getPlayerFlag(getName(), attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); return "null"; } else return null; } - if (attribute.startsWith("group")) { + if (attribute.startsWith("group") + || attribute.startsWith("in_group")) { if (Depends.permissions == null) { dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?"); return "null"; } String group = attribute.getContext(1); // Non-world specific permission - if (attribute.startsWith("group.global")) + if (attribute.getAttribute(2).startsWith("global")) return new Element(String.valueOf(Depends.permissions.playerInGroup((World) null, player_name, group))) .getAttribute(attribute.fulfill(2)); // Permission in current world return new Element(String.valueOf(Depends.permissions.playerInGroup(getPlayerEntity(), group))) .getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("is_flying")) return new Element(String.valueOf(getPlayerEntity().isFlying())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_sneaking")) return new Element(String.valueOf(getPlayerEntity().isSneaking())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_blocking")) return new Element(String.valueOf(getPlayerEntity().isBlocking())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_sleeping")) return new Element(String.valueOf(getPlayerEntity().isSleeping())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_sprinting")) return new Element(String.valueOf(getPlayerEntity().isSprinting())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("gamemode.id")) return new Element(String.valueOf(getPlayerEntity().getGameMode().getValue())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("gamemode")) return new Element(String.valueOf(getPlayerEntity().getGameMode().toString())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("item_on_cursor")) return new dItem(getPlayerEntity().getItemOnCursor()) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("selected_npc")) { if (getPlayerEntity().hasMetadata("selected")) - return dNPC.valueOf(String.valueOf(getPlayerEntity().getMetadata("selected").get(0))) + return dNPC.valueOf(getPlayerEntity().getMetadata("selected").get(0).asString()) .getAttribute(attribute.fulfill(1)); else return "null"; } if (attribute.startsWith("allowed_flight")) return new Element(String.valueOf(getPlayerEntity().getAllowFlight())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("host_name")) return new Element(String.valueOf(getPlayerEntity().getAddress().getHostName())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("time_asleep")) return new Duration(getPlayerEntity().getSleepTicks() / 20) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("player_time")) return new Element(String.valueOf(getPlayerEntity().getPlayerTime())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("player_time_offset")) return new Element(String.valueOf(getPlayerEntity().getPlayerTimeOffset())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("prefix")) return new Element(prefix) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("debug.log")) { dB.log(debug()); return new Element(Boolean.TRUE.toString()) .getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("debug.no_color")) { return new Element(ChatColor.stripColor(debug())) .getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("debug")) { return new Element(debug()) .getAttribute(attribute.fulfill(1)); } return new dEntity(getPlayerEntity()).getAttribute(attribute.fulfill(0)); } }
false
true
public String getAttribute(Attribute attribute) { if (attribute == null) return "null"; dB.log("getAttribute: " + getType() + " ---> " + attribute.attributes.toString()); if (attribute.startsWith("has_played_before")) return new Element(String.valueOf(getOfflinePlayer().hasPlayedBefore())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_op")) return new Element(String.valueOf(getOfflinePlayer().isOp())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("first_played")) return new Element(String.valueOf(getOfflinePlayer().getFirstPlayed())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("last_played")) return new Element(String.valueOf(getOfflinePlayer().getLastPlayed())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_banned")) return new Element(String.valueOf(getOfflinePlayer().isBanned())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_whitelisted")) return new Element(String.valueOf(getOfflinePlayer().isWhitelisted())) .getAttribute(attribute.fulfill(1)); // This can be parsed later with more detail if the player is online, so only check for offline. if (attribute.startsWith("name") && !isOnline()) return new Element(player_name).getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_online")) return new Element(String.valueOf(isOnline())).getAttribute(attribute.fulfill(1)); if (attribute.startsWith("chat_history_list")) return new dList(PlayerTags.playerChatHistory.get(player_name)) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("chat_history")) { int x = 1; if (attribute.hasContext(1) && aH.matchesInteger(attribute.getContext(1))) x = attribute.getIntContext(1); return new Element(PlayerTags.playerChatHistory.get(player_name).get(x - 1)) .getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("location.bed_spawn")) return new dLocation(getOfflinePlayer().getBedSpawnLocation()) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("money")) { if(Depends.economy != null) { if (attribute.startsWith("money.currency_singular")) return new Element(Depends.economy.currencyNameSingular()) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("money.currency")) return new Element(Depends.economy.currencyNamePlural()) .getAttribute(attribute.fulfill(2)); return new Element(String.valueOf(Depends.economy.getBalance(player_name))) .getAttribute(attribute.fulfill(1)); } else { dB.echoError("No economy loaded! Have you installed Vault and a compatible economy plugin?"); return null; } } if (!isOnline()) return new Element(identify()).getAttribute(attribute); // Player is required to be online after this point... if (attribute.startsWith("xp.to_next_level")) return new Element(String.valueOf(getPlayerEntity().getExpToLevel())) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("xp.total")) return new Element(String.valueOf(getPlayerEntity().getTotalExperience())) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("xp.level")) return new Element(getPlayerEntity().getLevel()) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("xp")) return new Element(String.valueOf(getPlayerEntity().getExp() * 100)) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("equipment")) // The only way to return correct size for dInventory // created from equipment is to use a CRAFTING type // that has the expected 4 slots return new dInventory(InventoryType.CRAFTING).add(getPlayerEntity().getInventory().getArmorContents()) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("inventory")) return new dInventory(getPlayerEntity().getInventory()) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("item_in_hand")) return new dItem(getPlayerEntity().getItemInHand()) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("name.display")) return new Element(getPlayerEntity().getDisplayName()) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("name.list")) return new Element(getPlayerEntity().getPlayerListName()) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("name")) return new Element(player_name).getAttribute(attribute.fulfill(1)); if (attribute.startsWith("location.compass_target")) return new dLocation(getPlayerEntity().getCompassTarget()) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("location")) return new dLocation(getPlayerEntity().getLocation()) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("food_level.formatted")) { int maxHunger = getPlayerEntity().getMaxHealth(); if (attribute.hasContext(2)) maxHunger = attribute.getIntContext(2); if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .10) return new Element("starving").getAttribute(attribute.fulfill(2)); else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .40) return new Element("famished").getAttribute(attribute.fulfill(2)); else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .75) return new Element("parched").getAttribute(attribute.fulfill(2)); else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < 1) return new Element("hungry").getAttribute(attribute.fulfill(2)); else return new Element("healthy").getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("food_level")) return new Element(String.valueOf(getPlayerEntity().getFoodLevel())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("permission")) { if (Depends.permissions == null) { dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?"); return null; } String permission = attribute.getContext(1); // Non-world specific permission if (attribute.startsWith("permission.global")) return new Element(String.valueOf(Depends.permissions.has((World) null, player_name, permission))) .getAttribute(attribute.fulfill(2)); // Permission in current world return new Element(String.valueOf(Depends.permissions.has(getPlayerEntity(), permission))) .getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("flag")) { if (attribute.hasContext(1)) { if (FlagManager.playerHasFlag(this, attribute.getContext(1))) return new dList(DenizenAPI.getCurrentInstance().flagManager() .getPlayerFlag(getName(), attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); return "null"; } else return null; } if (attribute.startsWith("group")) { if (Depends.permissions == null) { dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?"); return "null"; } String group = attribute.getContext(1); // Non-world specific permission if (attribute.startsWith("group.global")) return new Element(String.valueOf(Depends.permissions.playerInGroup((World) null, player_name, group))) .getAttribute(attribute.fulfill(2)); // Permission in current world return new Element(String.valueOf(Depends.permissions.playerInGroup(getPlayerEntity(), group))) .getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("is_flying")) return new Element(String.valueOf(getPlayerEntity().isFlying())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_sneaking")) return new Element(String.valueOf(getPlayerEntity().isSneaking())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_blocking")) return new Element(String.valueOf(getPlayerEntity().isBlocking())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_sleeping")) return new Element(String.valueOf(getPlayerEntity().isSleeping())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_sprinting")) return new Element(String.valueOf(getPlayerEntity().isSprinting())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("gamemode.id")) return new Element(String.valueOf(getPlayerEntity().getGameMode().getValue())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("gamemode")) return new Element(String.valueOf(getPlayerEntity().getGameMode().toString())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("item_on_cursor")) return new dItem(getPlayerEntity().getItemOnCursor()) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("selected_npc")) { if (getPlayerEntity().hasMetadata("selected")) return dNPC.valueOf(String.valueOf(getPlayerEntity().getMetadata("selected").get(0))) .getAttribute(attribute.fulfill(1)); else return "null"; } if (attribute.startsWith("allowed_flight")) return new Element(String.valueOf(getPlayerEntity().getAllowFlight())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("host_name")) return new Element(String.valueOf(getPlayerEntity().getAddress().getHostName())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("time_asleep")) return new Duration(getPlayerEntity().getSleepTicks() / 20) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("player_time")) return new Element(String.valueOf(getPlayerEntity().getPlayerTime())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("player_time_offset")) return new Element(String.valueOf(getPlayerEntity().getPlayerTimeOffset())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("prefix")) return new Element(prefix) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("debug.log")) { dB.log(debug()); return new Element(Boolean.TRUE.toString()) .getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("debug.no_color")) { return new Element(ChatColor.stripColor(debug())) .getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("debug")) { return new Element(debug()) .getAttribute(attribute.fulfill(1)); } return new dEntity(getPlayerEntity()).getAttribute(attribute.fulfill(0)); }
public String getAttribute(Attribute attribute) { if (attribute == null) return "null"; dB.log("getAttribute: " + getType() + " ---> " + attribute.attributes.toString()); if (attribute.startsWith("has_played_before")) return new Element(String.valueOf(getOfflinePlayer().hasPlayedBefore())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_op")) return new Element(String.valueOf(getOfflinePlayer().isOp())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("first_played")) return new Element(String.valueOf(getOfflinePlayer().getFirstPlayed())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("last_played")) return new Element(String.valueOf(getOfflinePlayer().getLastPlayed())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_banned")) return new Element(String.valueOf(getOfflinePlayer().isBanned())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_whitelisted")) return new Element(String.valueOf(getOfflinePlayer().isWhitelisted())) .getAttribute(attribute.fulfill(1)); // This can be parsed later with more detail if the player is online, so only check for offline. if (attribute.startsWith("name") && !isOnline()) return new Element(player_name).getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_online")) return new Element(String.valueOf(isOnline())).getAttribute(attribute.fulfill(1)); if (attribute.startsWith("chat_history_list")) return new dList(PlayerTags.playerChatHistory.get(player_name)) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("chat_history")) { int x = 1; if (attribute.hasContext(1) && aH.matchesInteger(attribute.getContext(1))) x = attribute.getIntContext(1); return new Element(PlayerTags.playerChatHistory.get(player_name).get(x - 1)) .getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("location.bed_spawn")) return new dLocation(getOfflinePlayer().getBedSpawnLocation()) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("money")) { if(Depends.economy != null) { if (attribute.startsWith("money.currency_singular")) return new Element(Depends.economy.currencyNameSingular()) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("money.currency")) return new Element(Depends.economy.currencyNamePlural()) .getAttribute(attribute.fulfill(2)); return new Element(String.valueOf(Depends.economy.getBalance(player_name))) .getAttribute(attribute.fulfill(1)); } else { dB.echoError("No economy loaded! Have you installed Vault and a compatible economy plugin?"); return null; } } if (!isOnline()) return new Element(identify()).getAttribute(attribute); // Player is required to be online after this point... if (attribute.startsWith("xp.to_next_level")) return new Element(String.valueOf(getPlayerEntity().getExpToLevel())) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("xp.total")) return new Element(String.valueOf(getPlayerEntity().getTotalExperience())) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("xp.level")) return new Element(getPlayerEntity().getLevel()) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("xp")) return new Element(String.valueOf(getPlayerEntity().getExp() * 100)) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("equipment")) // The only way to return correct size for dInventory // created from equipment is to use a CRAFTING type // that has the expected 4 slots return new dInventory(InventoryType.CRAFTING).add(getPlayerEntity().getInventory().getArmorContents()) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("inventory")) return new dInventory(getPlayerEntity().getInventory()) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("item_in_hand")) return new dItem(getPlayerEntity().getItemInHand()) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("name.display")) return new Element(getPlayerEntity().getDisplayName()) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("name.list")) return new Element(getPlayerEntity().getPlayerListName()) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("name")) return new Element(player_name).getAttribute(attribute.fulfill(1)); if (attribute.startsWith("location.compass_target")) return new dLocation(getPlayerEntity().getCompassTarget()) .getAttribute(attribute.fulfill(2)); if (attribute.startsWith("location")) return new dLocation(getPlayerEntity().getLocation()) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("food_level.formatted")) { int maxHunger = getPlayerEntity().getMaxHealth(); if (attribute.hasContext(2)) maxHunger = attribute.getIntContext(2); if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .10) return new Element("starving").getAttribute(attribute.fulfill(2)); else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .40) return new Element("famished").getAttribute(attribute.fulfill(2)); else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .75) return new Element("parched").getAttribute(attribute.fulfill(2)); else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < 1) return new Element("hungry").getAttribute(attribute.fulfill(2)); else return new Element("healthy").getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("food_level")) return new Element(String.valueOf(getPlayerEntity().getFoodLevel())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("permission") || attribute.startsWith("has_permission")) { if (Depends.permissions == null) { dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?"); return null; } String permission = attribute.getContext(1); // Non-world specific permission if (attribute.getAttribute(2).startsWith("global")) return new Element(String.valueOf(Depends.permissions.has((World) null, player_name, permission))) .getAttribute(attribute.fulfill(2)); // Permission in current world return new Element(String.valueOf(Depends.permissions.has(getPlayerEntity(), permission))) .getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("flag")) { if (attribute.hasContext(1)) { if (FlagManager.playerHasFlag(this, attribute.getContext(1))) return new dList(DenizenAPI.getCurrentInstance().flagManager() .getPlayerFlag(getName(), attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); return "null"; } else return null; } if (attribute.startsWith("group") || attribute.startsWith("in_group")) { if (Depends.permissions == null) { dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?"); return "null"; } String group = attribute.getContext(1); // Non-world specific permission if (attribute.getAttribute(2).startsWith("global")) return new Element(String.valueOf(Depends.permissions.playerInGroup((World) null, player_name, group))) .getAttribute(attribute.fulfill(2)); // Permission in current world return new Element(String.valueOf(Depends.permissions.playerInGroup(getPlayerEntity(), group))) .getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("is_flying")) return new Element(String.valueOf(getPlayerEntity().isFlying())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_sneaking")) return new Element(String.valueOf(getPlayerEntity().isSneaking())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_blocking")) return new Element(String.valueOf(getPlayerEntity().isBlocking())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_sleeping")) return new Element(String.valueOf(getPlayerEntity().isSleeping())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("is_sprinting")) return new Element(String.valueOf(getPlayerEntity().isSprinting())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("gamemode.id")) return new Element(String.valueOf(getPlayerEntity().getGameMode().getValue())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("gamemode")) return new Element(String.valueOf(getPlayerEntity().getGameMode().toString())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("item_on_cursor")) return new dItem(getPlayerEntity().getItemOnCursor()) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("selected_npc")) { if (getPlayerEntity().hasMetadata("selected")) return dNPC.valueOf(getPlayerEntity().getMetadata("selected").get(0).asString()) .getAttribute(attribute.fulfill(1)); else return "null"; } if (attribute.startsWith("allowed_flight")) return new Element(String.valueOf(getPlayerEntity().getAllowFlight())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("host_name")) return new Element(String.valueOf(getPlayerEntity().getAddress().getHostName())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("time_asleep")) return new Duration(getPlayerEntity().getSleepTicks() / 20) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("player_time")) return new Element(String.valueOf(getPlayerEntity().getPlayerTime())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("player_time_offset")) return new Element(String.valueOf(getPlayerEntity().getPlayerTimeOffset())) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("prefix")) return new Element(prefix) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("debug.log")) { dB.log(debug()); return new Element(Boolean.TRUE.toString()) .getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("debug.no_color")) { return new Element(ChatColor.stripColor(debug())) .getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("debug")) { return new Element(debug()) .getAttribute(attribute.fulfill(1)); } return new dEntity(getPlayerEntity()).getAttribute(attribute.fulfill(0)); }
diff --git a/src/main/java/org/atlasapi/remotesite/bbc/BbcBrandExtractor.java b/src/main/java/org/atlasapi/remotesite/bbc/BbcBrandExtractor.java index fcf0d89ee..1b50bbc3c 100644 --- a/src/main/java/org/atlasapi/remotesite/bbc/BbcBrandExtractor.java +++ b/src/main/java/org/atlasapi/remotesite/bbc/BbcBrandExtractor.java @@ -1,134 +1,134 @@ package org.atlasapi.remotesite.bbc; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.atlasapi.media.entity.Brand; import org.atlasapi.media.entity.Content; import org.atlasapi.media.entity.Item; import org.atlasapi.media.entity.Playlist; import org.atlasapi.media.entity.Publisher; import org.atlasapi.media.entity.Series; import org.atlasapi.persistence.logging.AdapterLog; import org.atlasapi.persistence.logging.AdapterLogEntry; import org.atlasapi.persistence.logging.AdapterLogEntry.Severity; import org.atlasapi.remotesite.bbc.SlashProgrammesRdf.SlashProgrammesBase; import org.atlasapi.remotesite.bbc.SlashProgrammesRdf.SlashProgrammesContainerRef; import org.atlasapi.remotesite.bbc.SlashProgrammesRdf.SlashProgrammesSeriesContainer; import org.atlasapi.remotesite.bbc.SlashProgrammesRdf.SlashProgrammesSeriesRef; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; public class BbcBrandExtractor { // Some Brands have a lot of episodes, if there are more than this number we // only look at the most recent episodes private static final int MAX_EPISODES = 1000; private static final BbcProgrammesGenreMap genreMap = new BbcProgrammesGenreMap(); private static final Pattern IMAGE_STEM = Pattern.compile("^(.+)_[0-9]+_[0-9]+\\.[a-zA-Z]+$"); private final BbcProgrammeAdapter subContentExtractor; private final AdapterLog log; public BbcBrandExtractor(BbcProgrammeAdapter subContentExtractor, AdapterLog log) { this.subContentExtractor = subContentExtractor; this.log = log; } public Series extractSeriesFrom(SlashProgrammesSeriesContainer rdfSeries) { Series series = new Series(); populatePlaylistAttributes(series, rdfSeries); List<String> episodeUris = episodesFrom(rdfSeries.episodeResourceUris()); addDirectlyIncludedEpisodesTo(series, episodeUris); return series; } public Brand extractBrandFrom(SlashProgrammesContainerRef brandRef) { Brand brand = new Brand(); populatePlaylistAttributes(brand, brandRef); List<String> episodes = brandRef.episodes == null ? ImmutableList.<String>of() : episodesFrom(brandRef.episodeResourceUris()); addDirectlyIncludedEpisodesTo(brand, episodes); if (brandRef.series != null) { for (SlashProgrammesSeriesRef seriesRef : brandRef.series) { String seriesPid = BbcFeeds.pidFrom(seriesRef.resourceUri()); if (seriesPid == null) { log.record(new AdapterLogEntry(Severity.WARN).withSource(getClass()).withUri(seriesRef.resourceUri()).withDescription("Could not extract PID from series ref " + seriesRef.resourceUri() + " for brand with uri " + brand.getCanonicalUri())); continue; } String uri = "http://www.bbc.co.uk/programmes/" + seriesPid; Series series = (Series) subContentExtractor.fetch(uri); if (series == null || series.getContentType() == null || brand == null || brand.getContentType() == null) { log.record(new AdapterLogEntry(Severity.WARN).withSource(getClass()).withUri(uri).withDescription("Could not load series with uri " + uri + " for brand with uri " + brand.getCanonicalUri())); continue; } if (!series.getContentType().equals(brand.getContentType())) { series.setContentType(brand.getContentType()); } for (Item item : series.getItems()) { - if(!item.getContentType().equals(brand.getContentType())) { + if(brand.getContentType() != null && !brand.getContentType().equals(item.getContentType())) { item.setContentType(brand.getContentType()); } brand.addItem(item); } } } return brand; } private void addDirectlyIncludedEpisodesTo(Playlist playlist, List<String> episodes) { for (String episodeUri : mostRecent(episodes)) { Content found = subContentExtractor.fetch(episodeUri); if (!(found instanceof Item)) { log.record(new AdapterLogEntry(Severity.WARN).withUri(episodeUri).withSource(getClass()).withDescription("Expected Item for PID: " + episodeUri)); continue; } playlist.addItem((Item) found); } } private List<String> episodesFrom(List<String> uriFragments) { List<String> uris = Lists.newArrayListWithCapacity(uriFragments.size()); for (String uri : uriFragments) { String pid = BbcFeeds.pidFrom(uri); if (pid == null) { log.record(new AdapterLogEntry(Severity.WARN).withUri(uri).withSource(getClass()).withDescription("Could not extract PID from: " + uri)); continue; } uris.add("http://www.bbc.co.uk/programmes/" + pid); } return uris; } private <T> List<T> mostRecent(List<T> episodes) { if (episodes.size() < MAX_EPISODES) { return episodes; } return episodes.subList(episodes.size() - MAX_EPISODES, episodes.size()); } private void populatePlaylistAttributes(Playlist container, SlashProgrammesBase brandRef) { String brandUri = brandRef.uri(); container.setCanonicalUri(brandUri); container.setCurie(BbcUriCanonicaliser.curieFor(brandUri)); container.setPublisher(Publisher.BBC); container.setTitle(brandRef.title()); if (brandRef.getMasterbrand() != null) { container.setContentType(BbcMasterbrandContentTypeMap.lookup(brandRef.getMasterbrand().getResourceUri()).valueOrNull()); } if (brandRef.getDepiction() != null) { Matcher matcher = IMAGE_STEM.matcher(brandRef.getDepiction().resourceUri()); if (matcher.matches()) { String base = matcher.group(1); container.setImage(base + BbcProgrammeGraphExtractor.FULL_IMAGE_EXTENSION); container.setThumbnail(base + BbcProgrammeGraphExtractor.THUMBNAIL_EXTENSION); } } container.setGenres(genreMap.map(brandRef.genreUris())); container.setDescription(brandRef.description()); } }
true
true
public Brand extractBrandFrom(SlashProgrammesContainerRef brandRef) { Brand brand = new Brand(); populatePlaylistAttributes(brand, brandRef); List<String> episodes = brandRef.episodes == null ? ImmutableList.<String>of() : episodesFrom(brandRef.episodeResourceUris()); addDirectlyIncludedEpisodesTo(brand, episodes); if (brandRef.series != null) { for (SlashProgrammesSeriesRef seriesRef : brandRef.series) { String seriesPid = BbcFeeds.pidFrom(seriesRef.resourceUri()); if (seriesPid == null) { log.record(new AdapterLogEntry(Severity.WARN).withSource(getClass()).withUri(seriesRef.resourceUri()).withDescription("Could not extract PID from series ref " + seriesRef.resourceUri() + " for brand with uri " + brand.getCanonicalUri())); continue; } String uri = "http://www.bbc.co.uk/programmes/" + seriesPid; Series series = (Series) subContentExtractor.fetch(uri); if (series == null || series.getContentType() == null || brand == null || brand.getContentType() == null) { log.record(new AdapterLogEntry(Severity.WARN).withSource(getClass()).withUri(uri).withDescription("Could not load series with uri " + uri + " for brand with uri " + brand.getCanonicalUri())); continue; } if (!series.getContentType().equals(brand.getContentType())) { series.setContentType(brand.getContentType()); } for (Item item : series.getItems()) { if(!item.getContentType().equals(brand.getContentType())) { item.setContentType(brand.getContentType()); } brand.addItem(item); } } } return brand; }
public Brand extractBrandFrom(SlashProgrammesContainerRef brandRef) { Brand brand = new Brand(); populatePlaylistAttributes(brand, brandRef); List<String> episodes = brandRef.episodes == null ? ImmutableList.<String>of() : episodesFrom(brandRef.episodeResourceUris()); addDirectlyIncludedEpisodesTo(brand, episodes); if (brandRef.series != null) { for (SlashProgrammesSeriesRef seriesRef : brandRef.series) { String seriesPid = BbcFeeds.pidFrom(seriesRef.resourceUri()); if (seriesPid == null) { log.record(new AdapterLogEntry(Severity.WARN).withSource(getClass()).withUri(seriesRef.resourceUri()).withDescription("Could not extract PID from series ref " + seriesRef.resourceUri() + " for brand with uri " + brand.getCanonicalUri())); continue; } String uri = "http://www.bbc.co.uk/programmes/" + seriesPid; Series series = (Series) subContentExtractor.fetch(uri); if (series == null || series.getContentType() == null || brand == null || brand.getContentType() == null) { log.record(new AdapterLogEntry(Severity.WARN).withSource(getClass()).withUri(uri).withDescription("Could not load series with uri " + uri + " for brand with uri " + brand.getCanonicalUri())); continue; } if (!series.getContentType().equals(brand.getContentType())) { series.setContentType(brand.getContentType()); } for (Item item : series.getItems()) { if(brand.getContentType() != null && !brand.getContentType().equals(item.getContentType())) { item.setContentType(brand.getContentType()); } brand.addItem(item); } } } return brand; }
diff --git a/crypto/src/org/bouncycastle/asn1/DLSequence.java b/crypto/src/org/bouncycastle/asn1/DLSequence.java index 24c8560a..26da6f6b 100644 --- a/crypto/src/org/bouncycastle/asn1/DLSequence.java +++ b/crypto/src/org/bouncycastle/asn1/DLSequence.java @@ -1,89 +1,89 @@ package org.bouncycastle.asn1; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Enumeration; public class DLSequence extends ASN1Sequence { /** * create an empty sequence */ public DLSequence() { } /** * create a sequence containing one object */ public DLSequence( DEREncodable obj) { addObject(obj); } /** * create a sequence containing a vector of objects. */ public DLSequence( ASN1EncodableVector v) { for (int i = 0; i != v.size(); i++) { this.addObject(v.get(i)); } } /* * A note on the implementation: * <p> * As DER requires the constructed, definite-length model to * be used for structured types, this varies slightly from the * ASN.1 descriptions given. Rather than just outputting SEQUENCE, * we also have to specify CONSTRUCTED, and the objects length. */ void encode(DEROutputStream out) throws IOException { // TODO Intermediate buffer could be avoided if we could calculate expected length if (out instanceof ASN1OutputStream) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - DLOutputStream dOut = new DLOutputStream(bOut); + ASN1OutputStream dOut = new ASN1OutputStream(bOut); Enumeration e = this.getObjects(); while (e.hasMoreElements()) { Object obj = e.nextElement(); dOut.writeObject((ASN1Encodable)obj); } dOut.close(); byte[] bytes = bOut.toByteArray(); out.writeEncoded(DERTags.SEQUENCE | DERTags.CONSTRUCTED, bytes); } else { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); Enumeration e = this.getObjects(); while (e.hasMoreElements()) { Object obj = e.nextElement(); dOut.writeObject(obj); } dOut.close(); byte[] bytes = bOut.toByteArray(); out.writeEncoded(DERTags.SEQUENCE | DERTags.CONSTRUCTED, bytes); } } }
true
true
void encode(DEROutputStream out) throws IOException { // TODO Intermediate buffer could be avoided if we could calculate expected length if (out instanceof ASN1OutputStream) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DLOutputStream dOut = new DLOutputStream(bOut); Enumeration e = this.getObjects(); while (e.hasMoreElements()) { Object obj = e.nextElement(); dOut.writeObject((ASN1Encodable)obj); } dOut.close(); byte[] bytes = bOut.toByteArray(); out.writeEncoded(DERTags.SEQUENCE | DERTags.CONSTRUCTED, bytes); } else { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); Enumeration e = this.getObjects(); while (e.hasMoreElements()) { Object obj = e.nextElement(); dOut.writeObject(obj); } dOut.close(); byte[] bytes = bOut.toByteArray(); out.writeEncoded(DERTags.SEQUENCE | DERTags.CONSTRUCTED, bytes); } }
void encode(DEROutputStream out) throws IOException { // TODO Intermediate buffer could be avoided if we could calculate expected length if (out instanceof ASN1OutputStream) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream dOut = new ASN1OutputStream(bOut); Enumeration e = this.getObjects(); while (e.hasMoreElements()) { Object obj = e.nextElement(); dOut.writeObject((ASN1Encodable)obj); } dOut.close(); byte[] bytes = bOut.toByteArray(); out.writeEncoded(DERTags.SEQUENCE | DERTags.CONSTRUCTED, bytes); } else { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); Enumeration e = this.getObjects(); while (e.hasMoreElements()) { Object obj = e.nextElement(); dOut.writeObject(obj); } dOut.close(); byte[] bytes = bOut.toByteArray(); out.writeEncoded(DERTags.SEQUENCE | DERTags.CONSTRUCTED, bytes); } }
diff --git a/android/src/com/xenon/greenup/CommentAdapter.java b/android/src/com/xenon/greenup/CommentAdapter.java index e9d886c..fbb0e8b 100644 --- a/android/src/com/xenon/greenup/CommentAdapter.java +++ b/android/src/com/xenon/greenup/CommentAdapter.java @@ -1,169 +1,173 @@ /** * */ package com.xenon.greenup; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import android.app.Activity; import android.graphics.Matrix; import android.graphics.Shader.TileMode; import android.graphics.drawable.BitmapDrawable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.xenon.greenup.api.Comment; /** * @author Ethan Joachim Eldridge *This is an array adapter class designed for performance using the *guidelines specified by http://www.vogella.com/articles/AndroidListView/article.html#listsactivity_performance */ public class CommentAdapter extends ArrayAdapter<Comment> { private final Activity context; private ArrayList<Comment> comments; static class ViewHolder { public TextView text; //icon is center public ImageView bottom; public ImageView top; } public CommentAdapter(Activity feedSectionFragment, ArrayList<Comment> comments){ super(feedSectionFragment, R.layout.comment,comments); this.context = feedSectionFragment; this.comments = comments; } /** * Returns an array of the top,center, and bottom. In that order * @param typeOfComment * @return */ private int[] getResourceByType(String typeOfComment){ //TODO Match types to colors for drawables if("FORUM".equalsIgnoreCase(typeOfComment)){ return new int[]{R.drawable.bubble_blue_top, R.drawable.bubble_blue_center,R.drawable.bubble_blue_bottom}; } if("GENERAL MESSAGE".equalsIgnoreCase(typeOfComment)){ return new int[]{R.drawable.bubble_green_top, R.drawable.bubble_green_center,R.drawable.bubble_green_bottom}; } if("TRASH PICKUP".equalsIgnoreCase(typeOfComment)){ return new int[]{R.drawable.bubble_orange_top, R.drawable.bubble_orange_center,R.drawable.bubble_orange_bottom}; } //Default/Help needed return new int[]{R.drawable.bubble_blue_top, R.drawable.bubble_blue_center,R.drawable.bubble_blue_bottom}; } private int getReverseOf(int resource){ switch(resource){ case R.drawable.bubble_orange_bottom: return R.drawable.bubble_orange_bottom_reverse; case R.drawable.bubble_green_bottom: return R.drawable.bubble_green_bottom_reverse; case R.drawable.bubble_blue_bottom: default: return R.drawable.bubble_blue_bottom_reverse; } } @Override public View getView(int position, View convertView, ViewGroup parent) { View rowView = convertView; if (rowView == null) { LayoutInflater inflater = context.getLayoutInflater(); rowView = inflater.inflate(R.layout.comment, null); ViewHolder viewHolder = new ViewHolder(); viewHolder.text = (TextView) rowView.findViewById(R.id.comment_grid_center_text); viewHolder.bottom= (ImageView) rowView.findViewById(R.id.comment_grid_bottom); viewHolder.top = (ImageView) rowView.findViewById(R.id.comment_grid_top); rowView.setTag(viewHolder); } ViewHolder holder = (ViewHolder) rowView.getTag(); Comment comment= comments.get(position); StringBuilder sb = new StringBuilder(); sb.append(comment.getMessage()); sb.append( System.getProperty("line.separator")); //Determine the twitter-esk stamp SimpleDateFormat sdf = new SimpleDateFormat("E LLL d kk:mm:ss yyyy",Locale.US); //The app engines timestamps are GMT sdf.setTimeZone(TimeZone.getTimeZone("GMT+4")); Date fromStamp = null; try { - fromStamp = sdf.parse(comment.getTimestamp()); + String ts = comment.getTimestamp(); + //Make sure that we have a timestamp or we'll have an NPE + if(ts != null) + fromStamp = sdf.parse(ts); } catch (ParseException e) { // TODO handle the bad parse of the date? e.printStackTrace(); } //Get the difference String difference; if(fromStamp != null) { long timeDiffInMilli = abs(new Date().getTime() - fromStamp.getTime()); Log.i("time",""+timeDiffInMilli); long daysAgo = timeDiffInMilli/86400000; long hoursAgo = ((timeDiffInMilli/(1000*60*60)) % 24); long minutesAgo = (long) (timeDiffInMilli/(1000*60)) % 60; long secondsAgo = (long) (timeDiffInMilli/1000) % 60; Log.i("time", "Hours ago: "+hoursAgo); Log.i("time", "Minutes ago: " + minutesAgo); if(daysAgo > 0) { difference = String.format(Locale.US,"%d days ago",daysAgo); } else if(hoursAgo > 0){ if (hoursAgo == 1) { difference = String.format(Locale.US,"%d hour, %d minutes ago", hoursAgo,minutesAgo); } else { difference = String.format(Locale.US,"%d hours, %d minutes ago", hoursAgo,minutesAgo); } } else { difference = String.format(Locale.US, "%d minutes and %d seconds ago",minutesAgo,secondsAgo); } }else{ //For a default if we can't figure it out we'll just give em the timestamp - difference = comment.getTimestamp(); + //Also check for null in the case one was never set above + difference = comment.getTimestamp() == null ? "" : comment.getTimestamp(); } sb.append(difference); holder.text.setText(sb.toString()); //Use the type of the comment to determine what color it shall be int [] topCenterBottomResourceIds = getResourceByType(comment.getType()); holder.top.setBackgroundResource(topCenterBottomResourceIds[0]); //Tile the center background BitmapDrawable background = (BitmapDrawable)this.context.getResources().getDrawable(topCenterBottomResourceIds[1]); background.setTileModeXY(TileMode.REPEAT,TileMode.REPEAT); holder.text.setBackground(background); //holder.text.setBackgroundResource((); if(position % 2 == 0) { holder.bottom.setBackgroundResource(getReverseOf(topCenterBottomResourceIds[2])); } else { holder.bottom.setBackgroundResource(topCenterBottomResourceIds[2]); } return rowView; } private long abs(long l) { if(l < 0){ return l*-1; } return l; } }
false
true
public View getView(int position, View convertView, ViewGroup parent) { View rowView = convertView; if (rowView == null) { LayoutInflater inflater = context.getLayoutInflater(); rowView = inflater.inflate(R.layout.comment, null); ViewHolder viewHolder = new ViewHolder(); viewHolder.text = (TextView) rowView.findViewById(R.id.comment_grid_center_text); viewHolder.bottom= (ImageView) rowView.findViewById(R.id.comment_grid_bottom); viewHolder.top = (ImageView) rowView.findViewById(R.id.comment_grid_top); rowView.setTag(viewHolder); } ViewHolder holder = (ViewHolder) rowView.getTag(); Comment comment= comments.get(position); StringBuilder sb = new StringBuilder(); sb.append(comment.getMessage()); sb.append( System.getProperty("line.separator")); //Determine the twitter-esk stamp SimpleDateFormat sdf = new SimpleDateFormat("E LLL d kk:mm:ss yyyy",Locale.US); //The app engines timestamps are GMT sdf.setTimeZone(TimeZone.getTimeZone("GMT+4")); Date fromStamp = null; try { fromStamp = sdf.parse(comment.getTimestamp()); } catch (ParseException e) { // TODO handle the bad parse of the date? e.printStackTrace(); } //Get the difference String difference; if(fromStamp != null) { long timeDiffInMilli = abs(new Date().getTime() - fromStamp.getTime()); Log.i("time",""+timeDiffInMilli); long daysAgo = timeDiffInMilli/86400000; long hoursAgo = ((timeDiffInMilli/(1000*60*60)) % 24); long minutesAgo = (long) (timeDiffInMilli/(1000*60)) % 60; long secondsAgo = (long) (timeDiffInMilli/1000) % 60; Log.i("time", "Hours ago: "+hoursAgo); Log.i("time", "Minutes ago: " + minutesAgo); if(daysAgo > 0) { difference = String.format(Locale.US,"%d days ago",daysAgo); } else if(hoursAgo > 0){ if (hoursAgo == 1) { difference = String.format(Locale.US,"%d hour, %d minutes ago", hoursAgo,minutesAgo); } else { difference = String.format(Locale.US,"%d hours, %d minutes ago", hoursAgo,minutesAgo); } } else { difference = String.format(Locale.US, "%d minutes and %d seconds ago",minutesAgo,secondsAgo); } }else{ //For a default if we can't figure it out we'll just give em the timestamp difference = comment.getTimestamp(); } sb.append(difference); holder.text.setText(sb.toString()); //Use the type of the comment to determine what color it shall be int [] topCenterBottomResourceIds = getResourceByType(comment.getType()); holder.top.setBackgroundResource(topCenterBottomResourceIds[0]); //Tile the center background BitmapDrawable background = (BitmapDrawable)this.context.getResources().getDrawable(topCenterBottomResourceIds[1]); background.setTileModeXY(TileMode.REPEAT,TileMode.REPEAT); holder.text.setBackground(background); //holder.text.setBackgroundResource((); if(position % 2 == 0) { holder.bottom.setBackgroundResource(getReverseOf(topCenterBottomResourceIds[2])); } else { holder.bottom.setBackgroundResource(topCenterBottomResourceIds[2]); } return rowView; }
public View getView(int position, View convertView, ViewGroup parent) { View rowView = convertView; if (rowView == null) { LayoutInflater inflater = context.getLayoutInflater(); rowView = inflater.inflate(R.layout.comment, null); ViewHolder viewHolder = new ViewHolder(); viewHolder.text = (TextView) rowView.findViewById(R.id.comment_grid_center_text); viewHolder.bottom= (ImageView) rowView.findViewById(R.id.comment_grid_bottom); viewHolder.top = (ImageView) rowView.findViewById(R.id.comment_grid_top); rowView.setTag(viewHolder); } ViewHolder holder = (ViewHolder) rowView.getTag(); Comment comment= comments.get(position); StringBuilder sb = new StringBuilder(); sb.append(comment.getMessage()); sb.append( System.getProperty("line.separator")); //Determine the twitter-esk stamp SimpleDateFormat sdf = new SimpleDateFormat("E LLL d kk:mm:ss yyyy",Locale.US); //The app engines timestamps are GMT sdf.setTimeZone(TimeZone.getTimeZone("GMT+4")); Date fromStamp = null; try { String ts = comment.getTimestamp(); //Make sure that we have a timestamp or we'll have an NPE if(ts != null) fromStamp = sdf.parse(ts); } catch (ParseException e) { // TODO handle the bad parse of the date? e.printStackTrace(); } //Get the difference String difference; if(fromStamp != null) { long timeDiffInMilli = abs(new Date().getTime() - fromStamp.getTime()); Log.i("time",""+timeDiffInMilli); long daysAgo = timeDiffInMilli/86400000; long hoursAgo = ((timeDiffInMilli/(1000*60*60)) % 24); long minutesAgo = (long) (timeDiffInMilli/(1000*60)) % 60; long secondsAgo = (long) (timeDiffInMilli/1000) % 60; Log.i("time", "Hours ago: "+hoursAgo); Log.i("time", "Minutes ago: " + minutesAgo); if(daysAgo > 0) { difference = String.format(Locale.US,"%d days ago",daysAgo); } else if(hoursAgo > 0){ if (hoursAgo == 1) { difference = String.format(Locale.US,"%d hour, %d minutes ago", hoursAgo,minutesAgo); } else { difference = String.format(Locale.US,"%d hours, %d minutes ago", hoursAgo,minutesAgo); } } else { difference = String.format(Locale.US, "%d minutes and %d seconds ago",minutesAgo,secondsAgo); } }else{ //For a default if we can't figure it out we'll just give em the timestamp //Also check for null in the case one was never set above difference = comment.getTimestamp() == null ? "" : comment.getTimestamp(); } sb.append(difference); holder.text.setText(sb.toString()); //Use the type of the comment to determine what color it shall be int [] topCenterBottomResourceIds = getResourceByType(comment.getType()); holder.top.setBackgroundResource(topCenterBottomResourceIds[0]); //Tile the center background BitmapDrawable background = (BitmapDrawable)this.context.getResources().getDrawable(topCenterBottomResourceIds[1]); background.setTileModeXY(TileMode.REPEAT,TileMode.REPEAT); holder.text.setBackground(background); //holder.text.setBackgroundResource((); if(position % 2 == 0) { holder.bottom.setBackgroundResource(getReverseOf(topCenterBottomResourceIds[2])); } else { holder.bottom.setBackgroundResource(topCenterBottomResourceIds[2]); } return rowView; }
diff --git a/src/test/java/org/otto/web/util/RandomDateUtilsTest.java b/src/test/java/org/otto/web/util/RandomDateUtilsTest.java index 04d230e..6fb8282 100644 --- a/src/test/java/org/otto/web/util/RandomDateUtilsTest.java +++ b/src/test/java/org/otto/web/util/RandomDateUtilsTest.java @@ -1,48 +1,48 @@ /* * Copyright 2011 Damien Bourdette * * 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.otto.web.util; import java.util.ArrayList; import java.util.List; import junit.framework.Assert; import org.joda.time.DateMidnight; import org.joda.time.DateTime; import org.junit.Test; /** * @author damien bourdette <a href="https://github.com/dbourdette">dbourdette on github</a> * @version \$Revision$ */ public class RandomDateUtilsTest { @Test public void today() { List<DateTime> dates = new ArrayList<DateTime>(); for (int i = 0; i < 100; i++) { DateTime randomDate = RandomDateUtils.today(); Assert.assertFalse("Same date generated twice", dates.contains(randomDate)); Assert.assertTrue(randomDate.isAfter(new DateMidnight().minus(1))); - Assert.assertTrue(randomDate.isBefore(new DateTime().plus(1))); + Assert.assertTrue(randomDate.isBefore(new DateMidnight().plusDays(1).plus(1))); dates.add(randomDate); } } }
true
true
public void today() { List<DateTime> dates = new ArrayList<DateTime>(); for (int i = 0; i < 100; i++) { DateTime randomDate = RandomDateUtils.today(); Assert.assertFalse("Same date generated twice", dates.contains(randomDate)); Assert.assertTrue(randomDate.isAfter(new DateMidnight().minus(1))); Assert.assertTrue(randomDate.isBefore(new DateTime().plus(1))); dates.add(randomDate); } }
public void today() { List<DateTime> dates = new ArrayList<DateTime>(); for (int i = 0; i < 100; i++) { DateTime randomDate = RandomDateUtils.today(); Assert.assertFalse("Same date generated twice", dates.contains(randomDate)); Assert.assertTrue(randomDate.isAfter(new DateMidnight().minus(1))); Assert.assertTrue(randomDate.isBefore(new DateMidnight().plusDays(1).plus(1))); dates.add(randomDate); } }
diff --git a/src/main/java/sequenceplanner/model/SOP/SopStructure.java b/src/main/java/sequenceplanner/model/SOP/SopStructure.java index 739b0d3..ba66b27 100755 --- a/src/main/java/sequenceplanner/model/SOP/SopStructure.java +++ b/src/main/java/sequenceplanner/model/SOP/SopStructure.java @@ -1,92 +1,92 @@ package sequenceplanner.model.SOP; import java.util.LinkedList; import java.util.ListIterator; import sequenceplanner.model.SOP.SopNodeOperation; import sequenceplanner.view.operationView.graphextension.Cell; /** * * @author Qw4z1 * *Till viktor* * Vi m�ste ha en Linked List f�r varje sekvens d�r ny root "Before ->Operation" * l�ggs till som ny "addFirst". L�ggs en ny operation till "after" s� l�ggs den * i sist i listan. L�ggs en parallell eller alternativ till s� m�ste de l�nkas * ihop i en annan lista via listan. * */ public class SopStructure implements ISopStructure { private ASopNode node; private LinkedList<LinkedList<ASopNode>> sopSeqs = new LinkedList<LinkedList<ASopNode>>(); private LinkedList<ASopNode> sopStructure; private LinkedList<ASopNode> li; public SopStructure() { } /*public SopStructure(Cell cell, ASopNode sopNode, boolean before) { //If the cell exists in the sequence, the new cell should be added //*This is not really true, since the cell can exists within two //sequences in the same OpView. So have to rethink this structure*/ public LinkedList getSopSequence() { return sopStructure; } @Override public void setSopSequence(ASopNode sopNode) { //Create new SOPList sopStructure = new LinkedList<ASopNode>(); sopStructure.add(sopNode); sopSeqs.add(sopStructure); System.out.println("Sequence initiated"); } @Override public void setSopSequence(Cell cell, ASopNode sopNode, boolean before) { //sopStructure.add(sopNode); for (LinkedList sopSeq : sopSeqs) { System.out.println("First: " + sopSeq.getFirst().toString()); System.out.println("Second:" + sopNode.toString()); //Need to figure out how to compare //if (sopSeq.contains(sopNode)) { //If the cell is inserted before an other cell if (before == true) { for (ListIterator<ASopNode> it = sopSeq.listIterator(); it.hasNext();) { //Need to figure out how to compare cell with SopNode - if (it.next().getClass() == SopNodeOperation.class) { + //if (it.next().getUniqueId() == ) { // if (it.next().getOperation() == cell.getValue()) { System.out.println("Adding Sop to list"); it.add(sopNode); break; - } - System.out.println("Going deeper"); + // } + //System.out.println("Going deeper"); //} } //If the cell is inserted after an other cell } else if (before == false) { for (ListIterator<ASopNode> it = sopSeq.listIterator(); it.hasNext();) { if (it.next().getClass() == SopNodeOperation.class) { System.out.println("Node added!"); it.add(sopNode); break; } } } for (ListIterator<ASopNode> it = sopSeq.listIterator(); it.hasNext();) { System.out.println("List: "+it.next().toString()); } //} else { // System.out.println("Something went wrong!"); //} } } }
false
true
public void setSopSequence(Cell cell, ASopNode sopNode, boolean before) { //sopStructure.add(sopNode); for (LinkedList sopSeq : sopSeqs) { System.out.println("First: " + sopSeq.getFirst().toString()); System.out.println("Second:" + sopNode.toString()); //Need to figure out how to compare //if (sopSeq.contains(sopNode)) { //If the cell is inserted before an other cell if (before == true) { for (ListIterator<ASopNode> it = sopSeq.listIterator(); it.hasNext();) { //Need to figure out how to compare cell with SopNode if (it.next().getClass() == SopNodeOperation.class) { // if (it.next().getOperation() == cell.getValue()) { System.out.println("Adding Sop to list"); it.add(sopNode); break; } System.out.println("Going deeper"); //} } //If the cell is inserted after an other cell } else if (before == false) { for (ListIterator<ASopNode> it = sopSeq.listIterator(); it.hasNext();) { if (it.next().getClass() == SopNodeOperation.class) { System.out.println("Node added!"); it.add(sopNode); break; } } } for (ListIterator<ASopNode> it = sopSeq.listIterator(); it.hasNext();) { System.out.println("List: "+it.next().toString()); } //} else { // System.out.println("Something went wrong!"); //} } }
public void setSopSequence(Cell cell, ASopNode sopNode, boolean before) { //sopStructure.add(sopNode); for (LinkedList sopSeq : sopSeqs) { System.out.println("First: " + sopSeq.getFirst().toString()); System.out.println("Second:" + sopNode.toString()); //Need to figure out how to compare //if (sopSeq.contains(sopNode)) { //If the cell is inserted before an other cell if (before == true) { for (ListIterator<ASopNode> it = sopSeq.listIterator(); it.hasNext();) { //Need to figure out how to compare cell with SopNode //if (it.next().getUniqueId() == ) { // if (it.next().getOperation() == cell.getValue()) { System.out.println("Adding Sop to list"); it.add(sopNode); break; // } //System.out.println("Going deeper"); //} } //If the cell is inserted after an other cell } else if (before == false) { for (ListIterator<ASopNode> it = sopSeq.listIterator(); it.hasNext();) { if (it.next().getClass() == SopNodeOperation.class) { System.out.println("Node added!"); it.add(sopNode); break; } } } for (ListIterator<ASopNode> it = sopSeq.listIterator(); it.hasNext();) { System.out.println("List: "+it.next().toString()); } //} else { // System.out.println("Something went wrong!"); //} } }
diff --git a/src/jivko/brain/speech/UtterancesManager.java b/src/jivko/brain/speech/UtterancesManager.java index 0d110f2..e68cb1a 100644 --- a/src/jivko/brain/speech/UtterancesManager.java +++ b/src/jivko/brain/speech/UtterancesManager.java @@ -1,171 +1,171 @@ package jivko.brain.speech; import java.io.File; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import jivko.brain.movement.Command; import jivko.brain.movement.CommandsCenter; import jivko.util.Tree; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * * @author Sergii Smehov (smehov.com) */ public class UtterancesManager { static private final String XML_DOM_NODE_UTTERANCE = "utterance"; static private final String XML_DOM_NODE_UTTERANCES = "utterances"; static private final String XML_DOM_NODE_QUESTION = "question"; static private final String XML_DOM_NODE_ANSWER = "answer"; static private final String FAIL_ANSWER = "Ниче страшного"; private Utterance rootUtterance = new Utterance(); private Utterance currentUtterance = null; public Utterance getRootUtterance() { return rootUtterance; } private void setRootUtterance(Utterance rootUtterance) { this.rootUtterance = rootUtterance; } public Utterance getCurrentUtterance() { return currentUtterance; } public void setCurrentUtterance(Utterance currentUtterance) { this.currentUtterance = currentUtterance; } public void initialize(String path) throws Exception { readDialogList(path); print(); currentUtterance = rootUtterance; } public void reset() { currentUtterance = rootUtterance; } private void readDialogList(String path) throws Exception { DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); f.setValidating(false); DocumentBuilder builder = f.newDocumentBuilder(); Document doc = builder.parse(new File(path)); Node firstUtterancesNode = doc.getFirstChild(); while (firstUtterancesNode.getNodeType() != Document.ELEMENT_NODE && firstUtterancesNode.getNextSibling() != null) firstUtterancesNode = firstUtterancesNode.getNextSibling(); assert XML_DOM_NODE_UTTERANCE.equals(firstUtterancesNode.getNodeName()); readUtterance(firstUtterancesNode, rootUtterance); } private void readUtterance(Node node, Utterance utterance) throws Exception { assert XML_DOM_NODE_UTTERANCE.equals(node.getNodeName()); List<Command> commands = CommandsCenter.getInstance().getCommandsFromXmlElement(node); utterance.setCommands(commands); NodeList nl = node.getChildNodes(); for (int i = 0; i < nl.getLength(); ++i) { Node n = nl.item(i); if (n.getNodeType() != Document.ELEMENT_NODE) continue; String nodeName = n.getNodeName(); switch (nodeName) { case XML_DOM_NODE_QUESTION: { String nodeVal = n.getTextContent(); utterance.setQuestion(nodeVal); break; } case XML_DOM_NODE_ANSWER: { String nodeVal = n.getTextContent(); utterance.setAnswer(nodeVal); break; } case XML_DOM_NODE_UTTERANCES: NodeList nnl = n.getChildNodes(); for (int j = 0; j < nnl.getLength(); ++j) { Node chNode = nnl.item(j); if (chNode.getNodeType() != Document.ELEMENT_NODE - || XML_DOM_NODE_UTTERANCE.equals(chNode.getNodeName())) + || !XML_DOM_NODE_UTTERANCE.equals(chNode.getNodeName())) continue; Utterance chUtterance = new Utterance(); readUtterance(chNode, chUtterance); utterance.addNode(chUtterance); } break; } } } static public String getFailAnswer() { return FAIL_ANSWER; } public String findAnswer(String question) throws Exception { String answer = null; if (question == null) { return getFailAnswer(); } answer = findAnswer(currentUtterance, question); if (answer == null) answer = findAnswer(rootUtterance, question); return answer; } public String findAnswer(Utterance utterance, String question) throws Exception { String answer = null; Utterance uWithAnswer = utterance.findUtteranceWithAnswer(question); if (uWithAnswer != null) { answer = uWithAnswer.getRandomValue(); CommandsCenter.getInstance().executeCommandList(uWithAnswer.getCommands()); //update current pointer if this is a dialog if (uWithAnswer.getNodes() != null) currentUtterance = uWithAnswer; } return answer; } public void print() { String identity = ""; printNode(rootUtterance, identity); } public void printNode(Utterance u, String identity) { String q = u.getQuestion(); String a = u.getRandomValue(); System.out.println(identity + "Question:" + q); System.out.println(identity + "Answer:" + a); identity = identity + " "; List<Tree> chNodes = u.getNodes(); for (Tree t : chNodes) { printNode((Utterance)t, identity); } } }
true
true
private void readUtterance(Node node, Utterance utterance) throws Exception { assert XML_DOM_NODE_UTTERANCE.equals(node.getNodeName()); List<Command> commands = CommandsCenter.getInstance().getCommandsFromXmlElement(node); utterance.setCommands(commands); NodeList nl = node.getChildNodes(); for (int i = 0; i < nl.getLength(); ++i) { Node n = nl.item(i); if (n.getNodeType() != Document.ELEMENT_NODE) continue; String nodeName = n.getNodeName(); switch (nodeName) { case XML_DOM_NODE_QUESTION: { String nodeVal = n.getTextContent(); utterance.setQuestion(nodeVal); break; } case XML_DOM_NODE_ANSWER: { String nodeVal = n.getTextContent(); utterance.setAnswer(nodeVal); break; } case XML_DOM_NODE_UTTERANCES: NodeList nnl = n.getChildNodes(); for (int j = 0; j < nnl.getLength(); ++j) { Node chNode = nnl.item(j); if (chNode.getNodeType() != Document.ELEMENT_NODE || XML_DOM_NODE_UTTERANCE.equals(chNode.getNodeName())) continue; Utterance chUtterance = new Utterance(); readUtterance(chNode, chUtterance); utterance.addNode(chUtterance); } break; } } }
private void readUtterance(Node node, Utterance utterance) throws Exception { assert XML_DOM_NODE_UTTERANCE.equals(node.getNodeName()); List<Command> commands = CommandsCenter.getInstance().getCommandsFromXmlElement(node); utterance.setCommands(commands); NodeList nl = node.getChildNodes(); for (int i = 0; i < nl.getLength(); ++i) { Node n = nl.item(i); if (n.getNodeType() != Document.ELEMENT_NODE) continue; String nodeName = n.getNodeName(); switch (nodeName) { case XML_DOM_NODE_QUESTION: { String nodeVal = n.getTextContent(); utterance.setQuestion(nodeVal); break; } case XML_DOM_NODE_ANSWER: { String nodeVal = n.getTextContent(); utterance.setAnswer(nodeVal); break; } case XML_DOM_NODE_UTTERANCES: NodeList nnl = n.getChildNodes(); for (int j = 0; j < nnl.getLength(); ++j) { Node chNode = nnl.item(j); if (chNode.getNodeType() != Document.ELEMENT_NODE || !XML_DOM_NODE_UTTERANCE.equals(chNode.getNodeName())) continue; Utterance chUtterance = new Utterance(); readUtterance(chNode, chUtterance); utterance.addNode(chUtterance); } break; } } }
diff --git a/src/net/ishchenko/idea/navigatefromliteral/OneWayPsiFileReference.java b/src/net/ishchenko/idea/navigatefromliteral/OneWayPsiFileReference.java index b0398f5..56bd900 100644 --- a/src/net/ishchenko/idea/navigatefromliteral/OneWayPsiFileReference.java +++ b/src/net/ishchenko/idea/navigatefromliteral/OneWayPsiFileReference.java @@ -1,30 +1,30 @@ package net.ishchenko.idea.navigatefromliteral; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; /** * Created with IntelliJ IDEA. * User: Max * Date: 21.09.13 * Time: 20:55 */ public class OneWayPsiFileReference extends OneWayPsiFileReferenceBase<PsiElement> { public OneWayPsiFileReference(PsiElement psiElement) { super(psiElement); } @NotNull @Override protected String computeStringValue() { String text = getElement().getText(); - if (text.startsWith("\"") && text.endsWith("\"") || text.startsWith("'") && text.endsWith("'")) { + if (text.length() >= 2 && text.startsWith("\"") && text.endsWith("\"") || text.startsWith("'") && text.endsWith("'")) { return text.substring(1, text.length() - 1); } else { //Some strange literal, has no quotes. Try anyway return text; } } }
true
true
protected String computeStringValue() { String text = getElement().getText(); if (text.startsWith("\"") && text.endsWith("\"") || text.startsWith("'") && text.endsWith("'")) { return text.substring(1, text.length() - 1); } else { //Some strange literal, has no quotes. Try anyway return text; } }
protected String computeStringValue() { String text = getElement().getText(); if (text.length() >= 2 && text.startsWith("\"") && text.endsWith("\"") || text.startsWith("'") && text.endsWith("'")) { return text.substring(1, text.length() - 1); } else { //Some strange literal, has no quotes. Try anyway return text; } }
diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/filehistory/CVSFileHistory.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/filehistory/CVSFileHistory.java index 9d4ab1a07..f8aa6507a 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/filehistory/CVSFileHistory.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/filehistory/CVSFileHistory.java @@ -1,324 +1,326 @@ /******************************************************************************* * Copyright (c) 2000, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.team.internal.ccvs.core.filehistory; import java.util.ArrayList; import java.util.Iterator; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.osgi.util.NLS; import org.eclipse.team.core.RepositoryProvider; import org.eclipse.team.core.TeamException; import org.eclipse.team.core.history.IFileHistoryProvider; import org.eclipse.team.core.history.IFileRevision; import org.eclipse.team.core.history.provider.FileHistory; import org.eclipse.team.internal.ccvs.core.*; import org.eclipse.team.internal.ccvs.core.client.Session; import org.eclipse.team.internal.ccvs.core.connection.CVSRepositoryLocation; import org.eclipse.team.internal.ccvs.core.resources.CVSWorkspaceRoot; import org.eclipse.team.internal.ccvs.core.resources.RemoteFile; public class CVSFileHistory extends FileHistory { protected ICVSFile cvsFile; //used to hold all revisions (changes based on filtering) protected IFileRevision[] revisions; //used to hold all of the remote revisions protected IFileRevision[] remoteRevisions; //used to hold all of the local revisions protected IFileRevision[] localRevisions; protected boolean includeLocalRevisions; protected boolean includeRemoteRevisions; protected boolean includesExists; protected boolean refetchRevisions; private int flag; /* * Creates a new CVSFile history that will fetch remote revisions by default. */ public CVSFileHistory(ICVSFile file) { this.cvsFile = file; this.includeLocalRevisions = false; this.includeRemoteRevisions = true; this.refetchRevisions = true; this.flag = 0; } /* * * Creates a new CVSFile history that will fetch remote revisions by default. * The flag passed can be IFileHistoryProvider.SINGLE_REVISION or IFileHistoryProvider.SINGLE_LINE_OF_DESCENT */ public CVSFileHistory(ICVSFile file, int flag) { this.cvsFile = file; this.includeLocalRevisions = false; this.includeRemoteRevisions = true; this.refetchRevisions = true; this.flag = flag; } public IFileRevision[] getFileRevisions() { if (revisions == null) return new IFileRevision[0]; return revisions; } /** * Refreshes the revisions for this CVS file. It may or may not contact the server to get new revisions. * * @param monitor a progress monitor */ public void refresh(IProgressMonitor monitor) throws TeamException { if (refetchRevisions) { monitor.beginTask(NLS.bind(CVSMessages.CVSFileHistory_0, cvsFile.getRepositoryRelativePath()), 300); try { ILogEntry[] entries = cvsFile.getLogEntries(new SubProgressMonitor(monitor, 200)); if (entries.length == 0){ //Get the parent folder ICVSFolder folder = cvsFile.getParent(); if (folder.isManaged()){ String remoteFolderLocation = folder.getRemoteLocation(folder); String remoteFileName = remoteFolderLocation.concat(Session.SERVER_SEPARATOR + cvsFile.getName()); //Create remote file CVSTeamProvider pro = (CVSTeamProvider) RepositoryProvider.getProvider(cvsFile.getIResource().getProject()); - CVSWorkspaceRoot root = pro.getCVSWorkspaceRoot(); - CVSRepositoryLocation location = CVSRepositoryLocation.fromString(root.getRemoteLocation().getLocation(false)); - RemoteFile remFile = RemoteFile.create(remoteFileName, location); - entries=remFile.getLogEntries(monitor); + if (pro != null){ + CVSWorkspaceRoot root = pro.getCVSWorkspaceRoot(); + CVSRepositoryLocation location = CVSRepositoryLocation.fromString(root.getRemoteLocation().getLocation(false)); + RemoteFile remFile = RemoteFile.create(remoteFileName, location); + entries=remFile.getLogEntries(monitor); + } } } if (flag == IFileHistoryProvider.SINGLE_REVISION) { String revisionNumber = cvsFile.getSyncInfo().getRevision(); for (int i = 0; i < entries.length; i++) { if (entries[i].getRevision().equals(revisionNumber)) { remoteRevisions = new IFileRevision[] {new CVSFileRevision(entries[i])}; revisions = new IFileRevision[1]; //copy over remote revisions System.arraycopy(remoteRevisions, 0, revisions, 0, remoteRevisions.length); break; } } } else if (flag == IFileHistoryProvider.SINGLE_LINE_OF_DESCENT) { CVSTag tempTag = cvsFile.getSyncInfo().getTag(); ArrayList entriesOfInterest = new ArrayList(); for (int i = 0; i < entries.length; i++) { CVSTag[] tags = entries[i].getTags(); for (int j = 0; j < tags.length; j++) { if (tags[j].getType() == tempTag.getType()) { if (tempTag.getType() == CVSTag.BRANCH && tempTag.getName().equals(tags[j].getName())) { entriesOfInterest.add(entries[i]); break; } else { entriesOfInterest.add(entries[i]); break; } } } } //always fetch the remote revisions, just filter them out from the returned array remoteRevisions = new IFileRevision[entriesOfInterest.size()]; Iterator iter = entriesOfInterest.iterator(); int i = 0; while (iter.hasNext()) { remoteRevisions[i++] = new CVSFileRevision((ILogEntry) iter.next()); } //copy over remote revisions revisions = new IFileRevision[remoteRevisions.length]; System.arraycopy(remoteRevisions, 0, revisions, 0, remoteRevisions.length); } else { localRevisions = new IFileRevision[0]; //always fetch the local revisions, just filter them out from the returned array if not wanted IResource localResource = cvsFile.getIResource(); includesExists = false; if (localResource != null && localResource instanceof IFile) { //get the local revisions IFileState[] localHistoryState; try { localHistoryState = ((IFile) localResource).getHistory(new SubProgressMonitor(monitor, 100)); localRevisions = convertToFileRevision(localHistoryState, new SubProgressMonitor(monitor, 100)); includesExists = (localRevisions.length > 0); } catch (CoreException e) { TeamException.asTeamException(e); } } //always fetch the remote revisions, just filter them out from the returned array remoteRevisions = new IFileRevision[entries.length]; for (int i = 0; i < entries.length; i++) { remoteRevisions[i] = new CVSFileRevision(entries[i]); } revisions = new IFileRevision[0]; arrangeRevisions(); } } finally { monitor.done(); } } else { //don't refetch revisions just return revisions with local revisions as requested arrangeRevisions(); } } private void arrangeRevisions() { if (revisions != null) { if (includeLocalRevisions && includeRemoteRevisions) { //Local + Remote mode revisions = new IFileRevision[remoteRevisions.length + localRevisions.length]; //copy over remote revisions System.arraycopy(remoteRevisions, 0, revisions, 0, remoteRevisions.length); //copy over local revisions System.arraycopy(localRevisions, 0, revisions, remoteRevisions.length, localRevisions.length); } else if (includeLocalRevisions) { //Local mode only revisions = new IFileRevision[localRevisions.length]; //copy over local revisions System.arraycopy(localRevisions, 0, revisions, 0, localRevisions.length); } else if (includeRemoteRevisions) { //Remote mode and fall through for Local + Remote mode where no Locals exist revisions = new IFileRevision[remoteRevisions.length]; //copy over remote revisions System.arraycopy(remoteRevisions, 0, revisions, 0, remoteRevisions.length); } } } public IFileRevision getFileRevision(String id) { IFileRevision[] revisions = getFileRevisions(); for (int i = 0; i < revisions.length; i++) { if (revisions[i].getContentIdentifier().equals(id)) return revisions[i]; } return null; } public IFileRevision[] getContributors(IFileRevision revision) { IFileRevision[] revisions = getFileRevisions(); //the predecessor is the file with a timestamp that is the largest timestamp //from the set of all timestamps smaller than the root file's timestamp IFileRevision fileRevision = null; for (int i = 0; i < revisions.length; i++) { if (((CVSFileRevision) revisions[i]).isPredecessorOf(revision)) { //no revision has been set as of yet if (fileRevision == null) fileRevision = revisions[i]; //this revision is a predecessor - now check to see if it comes //after the current predecessor, if it does make it the current predecessor if (revisions[i].getTimestamp() > fileRevision.getTimestamp()) { fileRevision = revisions[i]; } } } if (fileRevision == null) return new IFileRevision[0]; return new IFileRevision[] {fileRevision}; } public IFileRevision[] getTargets(IFileRevision revision) { IFileRevision[] revisions = getFileRevisions(); //the predecessor is the file with a timestamp that is the largest timestamp //from the set of all timestamps smaller than the root file's timestamp ArrayList directDescendents = new ArrayList(); for (int i = 0; i < revisions.length; i++) { if (((CVSFileRevision) revisions[i]).isDescendentOf(revision)) { directDescendents.add(revisions[i]); } } return (IFileRevision[]) directDescendents.toArray(new IFileRevision[directDescendents.size()]); } private IFileRevision[] convertToFileRevision(IFileState[] localRevisions, IProgressMonitor monitor) { boolean modified = false; try { modified = cvsFile.isModified(monitor); } catch (CVSException e) { } IFile localFile = (IFile) cvsFile.getIResource(); boolean localFileExists = (localFile != null && localFile.exists()); int arrayLength = 0; if (modified && localFileExists) arrayLength++; arrayLength += localRevisions.length; IFileRevision[] fileRevisions = new IFileRevision[arrayLength]; for (int i = 0; i < localRevisions.length; i++) { IFileState localFileState = localRevisions[i]; CVSLocalFileRevision localRevision = new CVSLocalFileRevision(localFileState); fileRevisions[i] = localRevision; } if (modified && localFileExists) { CVSLocalFileRevision currentFile = new CVSLocalFileRevision(localFile); CVSFileHistoryProvider provider = new CVSFileHistoryProvider(); currentFile.setBaseRevision(provider.getWorkspaceFileRevision(localFile)); fileRevisions[localRevisions.length] = currentFile; } return fileRevisions; } public void includeLocalRevisions(boolean flag) { this.includeLocalRevisions = flag; } public boolean getIncludesExists() { return includesExists; } public void setRefetchRevisions(boolean refetch) { this.refetchRevisions = refetch; } public void includeRemoteRevisions(boolean flag) { this.includeRemoteRevisions = flag; } public void fetchLocalOnly(IProgressMonitor monitor) { try{ localRevisions = new IFileRevision[0]; //always fetch the local revisions, just filter them out from the returned array if not wanted IResource localResource = cvsFile.getIResource(); includesExists = false; if (localResource != null && localResource instanceof IFile) { //get the local revisions IFileState[] localHistoryState = ((IFile) localResource).getHistory(new SubProgressMonitor(monitor, 100)); localRevisions = convertToFileRevision(localHistoryState, new SubProgressMonitor(monitor, 100)); includesExists = (localRevisions.length > 0); } remoteRevisions = new IFileRevision[0]; revisions = new IFileRevision[0]; arrangeRevisions(); } catch (CoreException ex){ //nothing to do - calling getFileRevisions() when revisions is null will result in //revisions returning an empty array } finally { monitor.done(); } } }
true
true
public void refresh(IProgressMonitor monitor) throws TeamException { if (refetchRevisions) { monitor.beginTask(NLS.bind(CVSMessages.CVSFileHistory_0, cvsFile.getRepositoryRelativePath()), 300); try { ILogEntry[] entries = cvsFile.getLogEntries(new SubProgressMonitor(monitor, 200)); if (entries.length == 0){ //Get the parent folder ICVSFolder folder = cvsFile.getParent(); if (folder.isManaged()){ String remoteFolderLocation = folder.getRemoteLocation(folder); String remoteFileName = remoteFolderLocation.concat(Session.SERVER_SEPARATOR + cvsFile.getName()); //Create remote file CVSTeamProvider pro = (CVSTeamProvider) RepositoryProvider.getProvider(cvsFile.getIResource().getProject()); CVSWorkspaceRoot root = pro.getCVSWorkspaceRoot(); CVSRepositoryLocation location = CVSRepositoryLocation.fromString(root.getRemoteLocation().getLocation(false)); RemoteFile remFile = RemoteFile.create(remoteFileName, location); entries=remFile.getLogEntries(monitor); } } if (flag == IFileHistoryProvider.SINGLE_REVISION) { String revisionNumber = cvsFile.getSyncInfo().getRevision(); for (int i = 0; i < entries.length; i++) { if (entries[i].getRevision().equals(revisionNumber)) { remoteRevisions = new IFileRevision[] {new CVSFileRevision(entries[i])}; revisions = new IFileRevision[1]; //copy over remote revisions System.arraycopy(remoteRevisions, 0, revisions, 0, remoteRevisions.length); break; } } } else if (flag == IFileHistoryProvider.SINGLE_LINE_OF_DESCENT) { CVSTag tempTag = cvsFile.getSyncInfo().getTag(); ArrayList entriesOfInterest = new ArrayList(); for (int i = 0; i < entries.length; i++) { CVSTag[] tags = entries[i].getTags(); for (int j = 0; j < tags.length; j++) { if (tags[j].getType() == tempTag.getType()) { if (tempTag.getType() == CVSTag.BRANCH && tempTag.getName().equals(tags[j].getName())) { entriesOfInterest.add(entries[i]); break; } else { entriesOfInterest.add(entries[i]); break; } } } } //always fetch the remote revisions, just filter them out from the returned array remoteRevisions = new IFileRevision[entriesOfInterest.size()]; Iterator iter = entriesOfInterest.iterator(); int i = 0; while (iter.hasNext()) { remoteRevisions[i++] = new CVSFileRevision((ILogEntry) iter.next()); } //copy over remote revisions revisions = new IFileRevision[remoteRevisions.length]; System.arraycopy(remoteRevisions, 0, revisions, 0, remoteRevisions.length); } else { localRevisions = new IFileRevision[0]; //always fetch the local revisions, just filter them out from the returned array if not wanted IResource localResource = cvsFile.getIResource(); includesExists = false; if (localResource != null && localResource instanceof IFile) { //get the local revisions IFileState[] localHistoryState; try { localHistoryState = ((IFile) localResource).getHistory(new SubProgressMonitor(monitor, 100)); localRevisions = convertToFileRevision(localHistoryState, new SubProgressMonitor(monitor, 100)); includesExists = (localRevisions.length > 0); } catch (CoreException e) { TeamException.asTeamException(e); } } //always fetch the remote revisions, just filter them out from the returned array remoteRevisions = new IFileRevision[entries.length]; for (int i = 0; i < entries.length; i++) { remoteRevisions[i] = new CVSFileRevision(entries[i]); } revisions = new IFileRevision[0]; arrangeRevisions(); } } finally { monitor.done(); } } else { //don't refetch revisions just return revisions with local revisions as requested arrangeRevisions(); } }
public void refresh(IProgressMonitor monitor) throws TeamException { if (refetchRevisions) { monitor.beginTask(NLS.bind(CVSMessages.CVSFileHistory_0, cvsFile.getRepositoryRelativePath()), 300); try { ILogEntry[] entries = cvsFile.getLogEntries(new SubProgressMonitor(monitor, 200)); if (entries.length == 0){ //Get the parent folder ICVSFolder folder = cvsFile.getParent(); if (folder.isManaged()){ String remoteFolderLocation = folder.getRemoteLocation(folder); String remoteFileName = remoteFolderLocation.concat(Session.SERVER_SEPARATOR + cvsFile.getName()); //Create remote file CVSTeamProvider pro = (CVSTeamProvider) RepositoryProvider.getProvider(cvsFile.getIResource().getProject()); if (pro != null){ CVSWorkspaceRoot root = pro.getCVSWorkspaceRoot(); CVSRepositoryLocation location = CVSRepositoryLocation.fromString(root.getRemoteLocation().getLocation(false)); RemoteFile remFile = RemoteFile.create(remoteFileName, location); entries=remFile.getLogEntries(monitor); } } } if (flag == IFileHistoryProvider.SINGLE_REVISION) { String revisionNumber = cvsFile.getSyncInfo().getRevision(); for (int i = 0; i < entries.length; i++) { if (entries[i].getRevision().equals(revisionNumber)) { remoteRevisions = new IFileRevision[] {new CVSFileRevision(entries[i])}; revisions = new IFileRevision[1]; //copy over remote revisions System.arraycopy(remoteRevisions, 0, revisions, 0, remoteRevisions.length); break; } } } else if (flag == IFileHistoryProvider.SINGLE_LINE_OF_DESCENT) { CVSTag tempTag = cvsFile.getSyncInfo().getTag(); ArrayList entriesOfInterest = new ArrayList(); for (int i = 0; i < entries.length; i++) { CVSTag[] tags = entries[i].getTags(); for (int j = 0; j < tags.length; j++) { if (tags[j].getType() == tempTag.getType()) { if (tempTag.getType() == CVSTag.BRANCH && tempTag.getName().equals(tags[j].getName())) { entriesOfInterest.add(entries[i]); break; } else { entriesOfInterest.add(entries[i]); break; } } } } //always fetch the remote revisions, just filter them out from the returned array remoteRevisions = new IFileRevision[entriesOfInterest.size()]; Iterator iter = entriesOfInterest.iterator(); int i = 0; while (iter.hasNext()) { remoteRevisions[i++] = new CVSFileRevision((ILogEntry) iter.next()); } //copy over remote revisions revisions = new IFileRevision[remoteRevisions.length]; System.arraycopy(remoteRevisions, 0, revisions, 0, remoteRevisions.length); } else { localRevisions = new IFileRevision[0]; //always fetch the local revisions, just filter them out from the returned array if not wanted IResource localResource = cvsFile.getIResource(); includesExists = false; if (localResource != null && localResource instanceof IFile) { //get the local revisions IFileState[] localHistoryState; try { localHistoryState = ((IFile) localResource).getHistory(new SubProgressMonitor(monitor, 100)); localRevisions = convertToFileRevision(localHistoryState, new SubProgressMonitor(monitor, 100)); includesExists = (localRevisions.length > 0); } catch (CoreException e) { TeamException.asTeamException(e); } } //always fetch the remote revisions, just filter them out from the returned array remoteRevisions = new IFileRevision[entries.length]; for (int i = 0; i < entries.length; i++) { remoteRevisions[i] = new CVSFileRevision(entries[i]); } revisions = new IFileRevision[0]; arrangeRevisions(); } } finally { monitor.done(); } } else { //don't refetch revisions just return revisions with local revisions as requested arrangeRevisions(); } }
diff --git a/ComicReader/src/com/blogspot/applications4android/comicreader/core/Strip.java b/ComicReader/src/com/blogspot/applications4android/comicreader/core/Strip.java index 3c34004..301aaf3 100755 --- a/ComicReader/src/com/blogspot/applications4android/comicreader/core/Strip.java +++ b/ComicReader/src/com/blogspot/applications4android/comicreader/core/Strip.java @@ -1,408 +1,410 @@ package com.blogspot.applications4android.comicreader.core; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.apache.http.client.ClientProtocolException; import org.json.JSONException; import org.json.JSONObject; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import com.blogspot.applications4android.comicreader.exceptions.BitMapException; import com.blogspot.applications4android.comicreader.exceptions.ComicSDCardFull; /** * Data-structure for holding info on a comic-strip */ public final class Strip { /** for logging purposes only */ private static final String TAG = "Strip"; /** Limit to the amount of memory to be used by the bitmap (in B) */ public static final int BITMAP_MEM_LIMIT = 3 * 1024 * 1024; /** HTML url for this strip (used to uniquely identify this strip) */ private String mHtmlUrl; /** Strip url (used for sharing the strip) */ private String mStripUrl; /** image stored in sd-card */ private String mImgFile; /** this strip has been read before? */ private boolean mRead; /** favorite strip? */ private boolean mFav; /** uid for the previous strip */ private String mPrevUid; /** uid for the next strip */ private String mNextUid; /** strip title */ private String mTitle; /** strip text */ private String mText; /** * Default constructor * @param html html url * @param imgR image file root */ public Strip(String html, String imgR) { _init_(html, imgR, false, false, null, null, null, null); } /** * Constructor with initialization * @param html html url * @param imgR image file root * @param read strip read before? * @param fav favorite strip? * @param prev previous comic strip * @param next next comic strip * @param title strip title * @param text strip text */ public Strip(String html, String imgR, boolean read, boolean fav, String prev, String next, String title, String text) { _init_(html, imgR, read, fav, prev, next, title, text); } /** * Helper function to initialize the contents of the strip * @param obj json object * @return strip object * @throws JSONException */ public static Strip readFromJsonObject(JSONObject obj) throws JSONException { Strip s = new Strip(null, null); s.mHtmlUrl = obj.getString("mHtmlUrl"); if(obj.has("mStripUrl")) { s.mStripUrl = obj.getString("mStripUrl"); } s.mImgFile = obj.getString("mImgFile"); s.mRead = obj.getBoolean("mRead"); s.mFav = obj.getBoolean("mFav"); if(obj.has("mPrevUid")) { s.mPrevUid = obj.getString("mPrevUid"); } if(obj.has("mNextUid")) { s.mNextUid = obj.getString("mNextUid"); } if(obj.has("mTitle")) { s.mTitle = obj.getString("mTitle"); } if(obj.has("mText")) { s.mText = obj.getString("mText"); } return s; } /** * Convert the contents of this strip into json string * @param sb string-builder where to append the contents */ public void toJsonString(StringBuilder sb) { sb.append("{\"mHtmlUrl\":\"" + mHtmlUrl + "\""); if(mStripUrl != null) { sb.append(", \"mStripUrl\":\"" + mStripUrl + "\""); } sb.append(", \"mImgFile\":\"" + mImgFile + "\""); if(mRead) { sb.append(", \"mRead\":\"true\""); } else { sb.append(", \"mRead\":\"false\""); } if(mFav) { sb.append(", \"mFav\":\"true\""); } else { sb.append(", \"mFav\":\"false\""); } if(mPrevUid != null) { sb.append(", \"mPrevUid\":\"" + mPrevUid + "\""); } if(mNextUid != null) { sb.append(", \"mNextUid\":\"" + mNextUid + "\""); } if(mTitle != null) { - sb.append(", \"mTitle\":\"" + mTitle + "\""); + String temp = mTitle.replaceAll("\"", "\\\""); + sb.append(", \"mTitle\":\"" + temp + "\""); } if(mText != null) { - sb.append(", \"mText\":\"" + mText + "\""); + String temp = mText.replaceAll("\"", "\\\""); + sb.append(", \"mText\":\"" + temp + "\""); } sb.append("}"); } /** * This gets the bitmap from the file (to be used only for comics which can have large strips) * You should have called 'getImage' before calling this function! * @return bitmap object * @throws FileNotFoundException * @throws BitMapException */ public Bitmap getBitmapFromFile() throws FileNotFoundException, BitMapException { //Decode image size and fit in exactly the amount of the memory needed. BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; FlushedInputStream fis = new FlushedInputStream(new FileInputStream(mImgFile)); BitmapFactory.decodeStream(fis, null, o); int bytes = o.outWidth * o.outHeight * 3; int factor = bytes / BITMAP_MEM_LIMIT; if(factor <= 1) { factor = 1; } else if(factor <= 4) { factor = 2; } else { factor = 4; } BitmapFactory.Options o1 = new BitmapFactory.Options(); o1.inSampleSize = factor; Bitmap bm = BitmapFactory.decodeFile(mImgFile, o1); if(bm == null) { String msg = "Failed to decode the image="+mImgFile+" URL="+mHtmlUrl; BitMapException ce = new BitMapException(msg); throw ce; } return bm; } /** * Fetches the image of the strip * @param p parser which generates strip info * @return path to the image * @throws IOException * @throws URISyntaxException * @throws ClientProtocolException * @throws ComicSDCardFull */ public String getImage(ComicParser p) throws ClientProtocolException, URISyntaxException, IOException, ComicSDCardFull { downloadImage(p); setAsRead(true); return mImgFile; } /** * Downloads the image of the strip if it doesn't exist already * @param p parser which generates strip info * @return true if the image had to be downloaded, else false * @throws IOException * @throws URISyntaxException * @throws ClientProtocolException * @throws ComicSDCardFull */ public boolean downloadImage(ComicParser p) throws ClientProtocolException, URISyntaxException, IOException, ComicSDCardFull { File img = new File(mImgFile); if(img.exists()) { return false; } String surl = p.parse(mHtmlUrl, this); Log.d(TAG, "Image url="+surl); mStripUrl = surl; Downloader.dnldImage(mImgFile, new URI(surl)); return true; } /** * Creates a valid file name out of the strip's title * @return valid file name */ public String currentTitleAsValidFilename() { if(mTitle == null) { return null; } return mTitle.replaceAll("[^a-zA-Z0-9]", "_"); } /** * Mark this strip as read/un-read * @param read read/un-read */ public void setAsRead(boolean read) { mRead = read; } /** * Set this comic as favorite * @param fav favorite or not */ public void setAsFavorite(boolean fav) { mFav = fav; } /** * Set the previous comic strip * @param uid previous strip */ public void setPrevious(String uid) { mPrevUid = uid; } /** * Set the next comic strip * @param uid next strip */ public void setNext(String uid) { mNextUid = uid; } /** * Set the strip text * @param txt text */ public void setText(String txt) { mText = txt; } /** * Set the strip title * @param title title */ public void setTitle(String title) { mTitle = title; } /** * Returns the UID for this strip (nothing but the html-url) * @return uid */ public String uid() { return mHtmlUrl; } /** * Returns the strip url * @return url */ public String getStripUrl() { return mStripUrl; } /** * Returns the path to the stored image file * @return image file path */ public String getImagePath() { return mImgFile; } /** * Whether this strip has been read * @return true if it has been read */ public boolean isRead() { return mRead; } /** * Whether this strip is favorite * @return true if is favorite */ public boolean isFavorite() { return mFav; } /** * Get the previous comic strip * @return previous strip */ public String getPrevious() { return mPrevUid; } /** * Is there a previous strip for this strip * @return true if it has */ public boolean hasPrevious() { return (mPrevUid != null); } /** * Get the next comic strip * @return next strip */ public String getNext() { return mNextUid; } /** * Is there a next strip for this strip * @return true if it has */ public boolean hasNext() { return (mNextUid != null); } /** * Get the strip title * @return title */ public String getTitle() { return Downloader.decodeHtml(mTitle); } /** * Get the strip text * @return text */ public String getText() { return Downloader.decodeHtml(mText); } /** * Checks whether the strip has hover-text or not * @return true if it has */ public boolean hasText() { if(mText == null) { return false; } if(mText.equals("") || mText.equals("-NA-")) { return false; } return true; } /** * Initialize the member variables * @param html html url * @param imgR image file root * @param read strip read before? * @param fav favorite strip? * @param prev previous comic strip * @param next next comic strip * @param title strip title * @param text strip text */ private void _init_(String html, String imgR, boolean read, boolean fav, String prev, String next, String title, String text) { mHtmlUrl = html; mStripUrl = null; _setImgFile_(imgR); mRead = read; mFav = fav; mPrevUid = prev; mNextUid = next; mTitle = title; mText = text; } /** * Sets the image file path * @param imgR image root folder */ private void _setImgFile_(String imgR) { if(imgR != null) { mImgFile = imgR + "/" + Md5Hash.str2md5(mHtmlUrl) + ".img"; } } }
false
true
public void toJsonString(StringBuilder sb) { sb.append("{\"mHtmlUrl\":\"" + mHtmlUrl + "\""); if(mStripUrl != null) { sb.append(", \"mStripUrl\":\"" + mStripUrl + "\""); } sb.append(", \"mImgFile\":\"" + mImgFile + "\""); if(mRead) { sb.append(", \"mRead\":\"true\""); } else { sb.append(", \"mRead\":\"false\""); } if(mFav) { sb.append(", \"mFav\":\"true\""); } else { sb.append(", \"mFav\":\"false\""); } if(mPrevUid != null) { sb.append(", \"mPrevUid\":\"" + mPrevUid + "\""); } if(mNextUid != null) { sb.append(", \"mNextUid\":\"" + mNextUid + "\""); } if(mTitle != null) { sb.append(", \"mTitle\":\"" + mTitle + "\""); } if(mText != null) { sb.append(", \"mText\":\"" + mText + "\""); } sb.append("}"); }
public void toJsonString(StringBuilder sb) { sb.append("{\"mHtmlUrl\":\"" + mHtmlUrl + "\""); if(mStripUrl != null) { sb.append(", \"mStripUrl\":\"" + mStripUrl + "\""); } sb.append(", \"mImgFile\":\"" + mImgFile + "\""); if(mRead) { sb.append(", \"mRead\":\"true\""); } else { sb.append(", \"mRead\":\"false\""); } if(mFav) { sb.append(", \"mFav\":\"true\""); } else { sb.append(", \"mFav\":\"false\""); } if(mPrevUid != null) { sb.append(", \"mPrevUid\":\"" + mPrevUid + "\""); } if(mNextUid != null) { sb.append(", \"mNextUid\":\"" + mNextUid + "\""); } if(mTitle != null) { String temp = mTitle.replaceAll("\"", "\\\""); sb.append(", \"mTitle\":\"" + temp + "\""); } if(mText != null) { String temp = mText.replaceAll("\"", "\\\""); sb.append(", \"mText\":\"" + temp + "\""); } sb.append("}"); }
diff --git a/src/riskyspace/view/opengl/menu/GLRecruitMenu.java b/src/riskyspace/view/opengl/menu/GLRecruitMenu.java index a7549b5..b3b5127 100644 --- a/src/riskyspace/view/opengl/menu/GLRecruitMenu.java +++ b/src/riskyspace/view/opengl/menu/GLRecruitMenu.java @@ -1,261 +1,265 @@ package riskyspace.view.opengl.menu; import java.awt.Color; import java.awt.Point; import java.awt.Toolkit; import java.util.HashMap; import java.util.Map; import javax.media.opengl.GLAutoDrawable; import com.jogamp.opengl.util.awt.TextRenderer; import riskyspace.PlayerColors; import riskyspace.model.Colony; import riskyspace.model.Player; import riskyspace.model.PlayerStats; import riskyspace.model.ShipType; import riskyspace.services.Event; import riskyspace.services.EventBus; import riskyspace.view.Action; import riskyspace.view.ViewResources; import riskyspace.view.opengl.Rectangle; import riskyspace.view.opengl.impl.GLButton; import riskyspace.view.opengl.impl.GLSprite; /** * * @author Daniel Augurell * */ public class GLRecruitMenu extends GLAbstractSideMenu { private Color ownerColor = null; private int margin; private Colony colony = null; private PlayerStats stats = null; /* * Build Buttons */ private GLButton buildScoutButton = null; private GLButton buildHunterButton = null; private GLButton buildDestroyerButton = null; private GLButton buildColonizerButton = null; /* * Texture coordinates for different Players */ private Player[] players = new Player[]{ Player.RED, Player.BLUE, Player.PINK, Player.GREEN, }; private int[] y = new int[]{ 192, 128, 64, 0 }; /* * Back Button */ private GLButton backButton = null; /* * Images */ private GLSprite colonyPicture = null; private Map<Player, GLSprite> cities = new HashMap<Player, GLSprite>(); /* * TextRenderer */ private TextRenderer nameRenderer = null; private boolean initiated = false; private int textX, textY; public GLRecruitMenu(int x, int y, int menuWidth, int menuHeight) { super(x, y, menuWidth, menuHeight); margin = menuHeight/20; int imageWidth = menuWidth - 2*margin; int imageHeight = ((menuWidth - 2*margin)*3)/4; setPicture(imageWidth, imageHeight); setButtons(); } /* * Create and set location for Buttons in this menu */ private void setButtons() { int x = getX() + getMenuWidth()/2 - margin/3; int y = getY() + cities.get(Player.BLUE).getBounds().getHeight() + 3*margin; buildScoutButton = new GLButton(x - 90, y, 90, 90); buildScoutButton.setAction(new Action() { @Override public void performAction() { Event evt = new Event(Event.EventTag.QUEUE_SHIP, ShipType.SCOUT); EventBus.CLIENT.publish(evt); } }); + buildScoutButton.setDisabledSprite(new GLSprite("ship_icon_grey", 0, 64, 128, 128)); buildHunterButton = new GLButton(x + 2 * margin / 3, y, 90, 90); buildHunterButton.setAction(new Action() { @Override public void performAction() { Event evt = new Event(Event.EventTag.QUEUE_SHIP, ShipType.HUNTER); EventBus.CLIENT.publish(evt); } }); + buildHunterButton.setDisabledSprite(new GLSprite("ship_icon_grey", 64, 64, 128, 128)); buildDestroyerButton = new GLButton(x - 90, y + 90 + margin/2, 90, 90); buildDestroyerButton.setAction(new Action() { @Override public void performAction() { Event evt = new Event(Event.EventTag.QUEUE_SHIP, ShipType.DESTROYER); EventBus.CLIENT.publish(evt); } }); + buildDestroyerButton.setDisabledSprite(new GLSprite("ship_icon_grey", 64, 0, 128, 128)); buildColonizerButton = new GLButton(x + 2 * margin / 3, y + 90 + margin/2, 90, 90); buildColonizerButton.setAction(new Action() { @Override public void performAction() { Event evt = new Event(Event.EventTag.QUEUE_SHIP, ShipType.COLONIZER); EventBus.CLIENT.publish(evt); } }); + buildColonizerButton.setDisabledSprite(new GLSprite("ship_icon_grey", 0, 0, 128, 128)); backButton = new GLButton(getX() + margin, getY() + getMenuHeight() - 2*(getMenuWidth() - 2*margin)/4, getMenuWidth() - 2 * margin, (getMenuWidth() - 2 * margin) / 4); backButton.setTexture("menu/back", 128, 32); backButton.setAction(new Action(){ @Override public void performAction() { setVisible(false); } }); } private void setPicture(int imageWidth, int imageHeight){ int sHeight = Toolkit.getDefaultToolkit().getScreenSize().height; Rectangle imageRenderRect = new Rectangle(getX() + margin, sHeight - (getY() + imageHeight + margin), imageWidth, imageHeight); GLSprite sprite = new GLSprite("menu/city_red", 1280, 700); sprite.setBounds(imageRenderRect); cities.put(Player.RED, sprite); sprite = new GLSprite("menu/city_blue", 900, 486); sprite.setBounds(imageRenderRect); cities.put(Player.BLUE, sprite); sprite = new GLSprite("menu/city_yellow", 970, 594); sprite.setBounds(imageRenderRect); cities.put(Player.PINK, sprite); sprite = new GLSprite("menu/city_green", 606, 389); sprite.setBounds(imageRenderRect); cities.put(Player.GREEN, sprite); } public GLRecruitMenu(int x, int y, int menuWidth, int menuHeight, Action backAction) { this(x, y, menuWidth, menuHeight); backButton.setAction(backAction); } public void setColony(Colony colony) { this.colony = colony; setMenuName(colony.getName()); ownerColor = PlayerColors.getColor(colony.getOwner()); colonyPicture = cities.get(colony.getOwner()); checkRecruitOptions(stats); setImages(colony.getOwner()); } private void setImages(Player player) { int i = 0; for (i = 0; i < players.length; i++) { if (players[i] == player) {break;}; } buildScoutButton.setTexture( "ship_icons", 0, y[i], 64, 64); buildHunterButton.setTexture( "ship_icons", 64, y[i], 64, 64); buildColonizerButton.setTexture("ship_icons", 128, y[i], 64, 64); buildDestroyerButton.setTexture("ship_icons", 192, y[i], 64, 64); } public void checkRecruitOptions(PlayerStats stats) { this.stats = stats; if (colony != null && stats != null){ buildScoutButton.setEnabled(stats.canAfford(ShipType.SCOUT) && colony.canBuild(ShipType.SCOUT)); buildHunterButton.setEnabled(stats.canAfford(ShipType.HUNTER) && colony.canBuild(ShipType.HUNTER)); buildColonizerButton.setEnabled(stats.canAfford(ShipType.COLONIZER) && colony.canBuild(ShipType.COLONIZER)); buildDestroyerButton.setEnabled(stats.canAfford(ShipType.DESTROYER) && colony.canBuild(ShipType.DESTROYER)); } } @Override public boolean mousePressed(Point p) { /* * Only handle mouse event if enabled */ if (isVisible()) { if (buildScoutButton.mousePressed(p)) {return true;} else if (buildHunterButton.mousePressed(p)) {return true;} else if (buildDestroyerButton.mousePressed(p)) {return true;} else if (buildColonizerButton.mousePressed(p)) {return true;} else if (backButton.mousePressed(p)) {return true;} if (this.contains(p)) {return true;} else { return false; } } return false; } @Override public boolean mouseReleased(Point p) { /* * Only handle mouse event if enabled */ if (isVisible()) { if (buildScoutButton.mouseReleased(p)) {return true;} else if (buildHunterButton.mouseReleased(p)) {return true;} else if (buildDestroyerButton.mouseReleased(p)) {return true;} else if (buildColonizerButton.mouseReleased(p)) {return true;} else if (backButton.mouseReleased(p)) {return true;} if (this.contains(p)) {return true;} else { return false; } } return false; } @Override public void draw(GLAutoDrawable drawable, Rectangle objectRect, Rectangle targetArea, int zIndex) { super.draw(drawable, objectRect, targetArea, zIndex); zIndex++; colonyPicture.draw(drawable, colonyPicture.getBounds(), targetArea, zIndex); buildScoutButton.draw(drawable, null, targetArea, zIndex); buildHunterButton.draw(drawable, null, targetArea, zIndex); buildDestroyerButton.draw(drawable, null, targetArea, zIndex); buildColonizerButton.draw(drawable, null, targetArea, zIndex); backButton.draw(drawable, null, targetArea, zIndex); drawMenuName(drawable); } private void drawMenuName(GLAutoDrawable drawable) { if(!initiated){ nameRenderer = new TextRenderer(ViewResources.getFont().deriveFont((float)getMenuHeight()/20)); textX = getX() - ((int)nameRenderer.getBounds(getMenuName()).getWidth() / 2) + (getMenuWidth() / 2); textY = getMenuHeight() - ((int)nameRenderer.getBounds(getMenuName()).getHeight() / 2) - (2*margin + colonyPicture.getBounds().getHeight()); initiated = true; } nameRenderer.beginRendering(drawable.getWidth(), drawable.getHeight()); nameRenderer.setColor(ownerColor); nameRenderer.draw(getMenuName(), textX, textY); nameRenderer.setColor(1, 1, 1, 1); nameRenderer.endRendering(); } }
false
true
private void setButtons() { int x = getX() + getMenuWidth()/2 - margin/3; int y = getY() + cities.get(Player.BLUE).getBounds().getHeight() + 3*margin; buildScoutButton = new GLButton(x - 90, y, 90, 90); buildScoutButton.setAction(new Action() { @Override public void performAction() { Event evt = new Event(Event.EventTag.QUEUE_SHIP, ShipType.SCOUT); EventBus.CLIENT.publish(evt); } }); buildHunterButton = new GLButton(x + 2 * margin / 3, y, 90, 90); buildHunterButton.setAction(new Action() { @Override public void performAction() { Event evt = new Event(Event.EventTag.QUEUE_SHIP, ShipType.HUNTER); EventBus.CLIENT.publish(evt); } }); buildDestroyerButton = new GLButton(x - 90, y + 90 + margin/2, 90, 90); buildDestroyerButton.setAction(new Action() { @Override public void performAction() { Event evt = new Event(Event.EventTag.QUEUE_SHIP, ShipType.DESTROYER); EventBus.CLIENT.publish(evt); } }); buildColonizerButton = new GLButton(x + 2 * margin / 3, y + 90 + margin/2, 90, 90); buildColonizerButton.setAction(new Action() { @Override public void performAction() { Event evt = new Event(Event.EventTag.QUEUE_SHIP, ShipType.COLONIZER); EventBus.CLIENT.publish(evt); } }); backButton = new GLButton(getX() + margin, getY() + getMenuHeight() - 2*(getMenuWidth() - 2*margin)/4, getMenuWidth() - 2 * margin, (getMenuWidth() - 2 * margin) / 4); backButton.setTexture("menu/back", 128, 32); backButton.setAction(new Action(){ @Override public void performAction() { setVisible(false); } }); }
private void setButtons() { int x = getX() + getMenuWidth()/2 - margin/3; int y = getY() + cities.get(Player.BLUE).getBounds().getHeight() + 3*margin; buildScoutButton = new GLButton(x - 90, y, 90, 90); buildScoutButton.setAction(new Action() { @Override public void performAction() { Event evt = new Event(Event.EventTag.QUEUE_SHIP, ShipType.SCOUT); EventBus.CLIENT.publish(evt); } }); buildScoutButton.setDisabledSprite(new GLSprite("ship_icon_grey", 0, 64, 128, 128)); buildHunterButton = new GLButton(x + 2 * margin / 3, y, 90, 90); buildHunterButton.setAction(new Action() { @Override public void performAction() { Event evt = new Event(Event.EventTag.QUEUE_SHIP, ShipType.HUNTER); EventBus.CLIENT.publish(evt); } }); buildHunterButton.setDisabledSprite(new GLSprite("ship_icon_grey", 64, 64, 128, 128)); buildDestroyerButton = new GLButton(x - 90, y + 90 + margin/2, 90, 90); buildDestroyerButton.setAction(new Action() { @Override public void performAction() { Event evt = new Event(Event.EventTag.QUEUE_SHIP, ShipType.DESTROYER); EventBus.CLIENT.publish(evt); } }); buildDestroyerButton.setDisabledSprite(new GLSprite("ship_icon_grey", 64, 0, 128, 128)); buildColonizerButton = new GLButton(x + 2 * margin / 3, y + 90 + margin/2, 90, 90); buildColonizerButton.setAction(new Action() { @Override public void performAction() { Event evt = new Event(Event.EventTag.QUEUE_SHIP, ShipType.COLONIZER); EventBus.CLIENT.publish(evt); } }); buildColonizerButton.setDisabledSprite(new GLSprite("ship_icon_grey", 0, 0, 128, 128)); backButton = new GLButton(getX() + margin, getY() + getMenuHeight() - 2*(getMenuWidth() - 2*margin)/4, getMenuWidth() - 2 * margin, (getMenuWidth() - 2 * margin) / 4); backButton.setTexture("menu/back", 128, 32); backButton.setAction(new Action(){ @Override public void performAction() { setVisible(false); } }); }
diff --git a/src/test/java/org/apache/hadoop/hbase/util/TestCompressionTest.java b/src/test/java/org/apache/hadoop/hbase/util/TestCompressionTest.java index 3170ab38c..14bf24f01 100644 --- a/src/test/java/org/apache/hadoop/hbase/util/TestCompressionTest.java +++ b/src/test/java/org/apache/hadoop/hbase/util/TestCompressionTest.java @@ -1,59 +1,59 @@ /* * Copyright 2010 The Apache Software Foundation * * 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.hadoop.hbase.util; import org.apache.hadoop.hbase.io.hfile.Compression; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.*; public class TestCompressionTest { @Test public void testTestCompression() { // This test will fail if you run the tests with LZO compression available. try { CompressionTest.testCompression(Compression.Algorithm.LZO); fail(); // always throws } catch (IOException e) { // there should be a 'cause'. assertNotNull(e.getCause()); } // this is testing the caching of the test results. try { CompressionTest.testCompression(Compression.Algorithm.LZO); fail(); // always throws } catch (IOException e) { // there should be NO cause because it's a direct exception not wrapped assertNull(e.getCause()); } assertFalse(CompressionTest.testCompression("LZO")); assertTrue(CompressionTest.testCompression("NONE")); assertTrue(CompressionTest.testCompression("GZ")); - assertTrue(CompressionTest.testCompression("SNAPPY")); + assertFalse(CompressionTest.testCompression("SNAPPY")); } }
true
true
public void testTestCompression() { // This test will fail if you run the tests with LZO compression available. try { CompressionTest.testCompression(Compression.Algorithm.LZO); fail(); // always throws } catch (IOException e) { // there should be a 'cause'. assertNotNull(e.getCause()); } // this is testing the caching of the test results. try { CompressionTest.testCompression(Compression.Algorithm.LZO); fail(); // always throws } catch (IOException e) { // there should be NO cause because it's a direct exception not wrapped assertNull(e.getCause()); } assertFalse(CompressionTest.testCompression("LZO")); assertTrue(CompressionTest.testCompression("NONE")); assertTrue(CompressionTest.testCompression("GZ")); assertTrue(CompressionTest.testCompression("SNAPPY")); }
public void testTestCompression() { // This test will fail if you run the tests with LZO compression available. try { CompressionTest.testCompression(Compression.Algorithm.LZO); fail(); // always throws } catch (IOException e) { // there should be a 'cause'. assertNotNull(e.getCause()); } // this is testing the caching of the test results. try { CompressionTest.testCompression(Compression.Algorithm.LZO); fail(); // always throws } catch (IOException e) { // there should be NO cause because it's a direct exception not wrapped assertNull(e.getCause()); } assertFalse(CompressionTest.testCompression("LZO")); assertTrue(CompressionTest.testCompression("NONE")); assertTrue(CompressionTest.testCompression("GZ")); assertFalse(CompressionTest.testCompression("SNAPPY")); }
diff --git a/src/com/dmdirc/addons/dcc/DCCCommand.java b/src/com/dmdirc/addons/dcc/DCCCommand.java index 58f47f6a8..5a7e9351e 100644 --- a/src/com/dmdirc/addons/dcc/DCCCommand.java +++ b/src/com/dmdirc/addons/dcc/DCCCommand.java @@ -1,186 +1,186 @@ /* * 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.addons.dcc; import com.dmdirc.Main; import com.dmdirc.Server; import com.dmdirc.parser.IRCParser; import com.dmdirc.config.IdentityManager; import com.dmdirc.commandparser.CommandManager; import com.dmdirc.commandparser.commands.GlobalCommand; import com.dmdirc.ui.interfaces.InputWindow; import com.dmdirc.actions.ActionManager; import com.dmdirc.addons.dcc.actions.DCCActions; import javax.swing.JFileChooser; import javax.swing.JFrame; import java.io.File; /** * This command allows starting dcc chats/file transfers * * @author Shane "Dataforce" Mc Cormack * @version $Id: DCCCommand.java 969 2007-04-30 18:38:20Z ShaneMcC $ */ public final class DCCCommand extends GlobalCommand { /** My Plugin */ final DCCPlugin myPlugin; /** * Creates a new instance of DCCCommand. * * @param plugin The DCC Plugin that this command belongs to */ public DCCCommand(final DCCPlugin plugin) { super(); myPlugin = plugin; CommandManager.registerCommand(this); } /** * Executes this command. * * @param origin The frame in which this command was issued * @param isSilent Whether this command is silenced or not * @param args The user supplied arguments */ @Override public void execute(final InputWindow origin, final boolean isSilent, final String... args) { if (args.length > 1) { final String type = args[0]; final String target = args[1]; if (type.equalsIgnoreCase("chat")) { final Server server = origin.getContainer().getServer(); final IRCParser parser = server.getParser(); final String myNickname = parser.getMyNickname(); final DCCChat chat = new DCCChat(); if (myPlugin.listen(chat)) { final DCCChatWindow window = new DCCChatWindow(myPlugin, chat, "*Chat: "+target, myNickname, target); parser.sendCTCP(target, "DCC", "CHAT chat "+DCC.ipToLong(DCCPlugin.getListenIP(parser))+" "+chat.getPort()); ActionManager.processEvent(DCCActions.DCC_CHAT_REQUEST_SENT, null, server, target); sendLine(origin, isSilent, "DCCChatStarting", target, chat.getHost(), chat.getPort()); window.getFrame().addLine("DCCChatStarting", target, chat.getHost(), chat.getPort()); } else { sendLine(origin, isSilent, "DCCChatError", "Unable to start chat with "+target+" - unable to create listen socket"); } } else if (type.equalsIgnoreCase("send")) { sendFile(target, origin, isSilent, args); } else { sendLine(origin, isSilent, FORMAT_ERROR, "Unknown DCC Type: '"+type+"'"); } } else { sendLine(origin, isSilent, FORMAT_ERROR, "Syntax: dcc <type> <target> [params]"); } } /** * Ask for the file to send, then start the send. * * @param target Person this dcc is to. * @param origin The InputWindow this command was issued on * @param isSilent Whether this command is silenced or not * @param args Arguments passed. */ public void sendFile(final String target, final InputWindow origin, final boolean isSilent, final String... args) { // New thread to ask the user what file to send final File givenFile = new File(implodeArgs(2, args)); final Thread dccThread = new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { final JFileChooser jc = (givenFile.exists()) ? new JFileChooser(givenFile) : new JFileChooser(); int result; if (!givenFile.exists() || !givenFile.isFile() ) { jc.setDialogTitle("Send file to "+target+" - DMDirc "); - jc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); + jc.setFileSelectionMode(JFileChooser.FILES_ONLY); jc.setMultiSelectionEnabled(false); result = jc.showOpenDialog((JFrame)Main.getUI().getMainWindow()); } else { jc.setSelectedFile(givenFile); result = JFileChooser.APPROVE_OPTION; } if (result == JFileChooser.APPROVE_OPTION) { final Server server = origin.getContainer().getServer(); final IRCParser parser = server.getParser(); final String myNickname = parser.getMyNickname(); DCCSend send = new DCCSend(IdentityManager.getGlobalConfig().getOptionInt(DCCPlugin.getDomain(), "send.blocksize", 1024)); send.setTurbo(IdentityManager.getGlobalConfig().getOptionBool(DCCPlugin.getDomain(), "send.forceturbo", false)); send.setType(DCCSend.TransferType.SEND); ActionManager.processEvent(DCCActions.DCC_SEND_REQUEST_SENT, null, server, target, jc.getSelectedFile()); sendLine(origin, isSilent, FORMAT_OUTPUT, "Starting DCC Send with: "+target); send.setFileName(jc.getSelectedFile().getAbsolutePath()); send.setFileSize(jc.getSelectedFile().length()); if (IdentityManager.getGlobalConfig().getOptionBool(DCCPlugin.getDomain(), "send.reverse", false)) { new DCCSendWindow(myPlugin, send, "Send: "+target, myNickname, target); parser.sendCTCP(target, "DCC", "SEND \""+jc.getSelectedFile().getName()+"\" "+DCC.ipToLong(DCCPlugin.getListenIP(parser))+" 0 "+send.getFileSize()+" "+send.makeToken()+((send.isTurbo()) ? " T" : "")); } else { if (myPlugin.listen(send)) { new DCCSendWindow(myPlugin, send, "*Send: "+target, myNickname, target); parser.sendCTCP(target, "DCC", "SEND \""+jc.getSelectedFile().getName()+"\" "+DCC.ipToLong(DCCPlugin.getListenIP(parser))+" "+send.getPort()+" "+send.getFileSize()+((send.isTurbo()) ? " T" : "")); } else { sendLine(origin, isSilent, "DCCSendError", "Unable to start dcc send with "+target+" - unable to create listen socket"); } } } } }, "openFileThread"); // Start the thread dccThread.start(); } /** * Returns this command's name. * * @return The name of this command */ @Override public String getName() { return "dcc"; } /** * Returns whether or not this command should be shown in help messages. * * @return True iff the command should be shown, false otherwise */ @Override public boolean showInHelp() { return true; } /** * Returns a string representing the help message for this command. * * @return the help message for this command */ @Override public String getHelp() { return "dcc - Allows DCC"; } }
true
true
public void sendFile(final String target, final InputWindow origin, final boolean isSilent, final String... args) { // New thread to ask the user what file to send final File givenFile = new File(implodeArgs(2, args)); final Thread dccThread = new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { final JFileChooser jc = (givenFile.exists()) ? new JFileChooser(givenFile) : new JFileChooser(); int result; if (!givenFile.exists() || !givenFile.isFile() ) { jc.setDialogTitle("Send file to "+target+" - DMDirc "); jc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); jc.setMultiSelectionEnabled(false); result = jc.showOpenDialog((JFrame)Main.getUI().getMainWindow()); } else { jc.setSelectedFile(givenFile); result = JFileChooser.APPROVE_OPTION; } if (result == JFileChooser.APPROVE_OPTION) { final Server server = origin.getContainer().getServer(); final IRCParser parser = server.getParser(); final String myNickname = parser.getMyNickname(); DCCSend send = new DCCSend(IdentityManager.getGlobalConfig().getOptionInt(DCCPlugin.getDomain(), "send.blocksize", 1024)); send.setTurbo(IdentityManager.getGlobalConfig().getOptionBool(DCCPlugin.getDomain(), "send.forceturbo", false)); send.setType(DCCSend.TransferType.SEND); ActionManager.processEvent(DCCActions.DCC_SEND_REQUEST_SENT, null, server, target, jc.getSelectedFile()); sendLine(origin, isSilent, FORMAT_OUTPUT, "Starting DCC Send with: "+target); send.setFileName(jc.getSelectedFile().getAbsolutePath()); send.setFileSize(jc.getSelectedFile().length()); if (IdentityManager.getGlobalConfig().getOptionBool(DCCPlugin.getDomain(), "send.reverse", false)) { new DCCSendWindow(myPlugin, send, "Send: "+target, myNickname, target); parser.sendCTCP(target, "DCC", "SEND \""+jc.getSelectedFile().getName()+"\" "+DCC.ipToLong(DCCPlugin.getListenIP(parser))+" 0 "+send.getFileSize()+" "+send.makeToken()+((send.isTurbo()) ? " T" : "")); } else { if (myPlugin.listen(send)) { new DCCSendWindow(myPlugin, send, "*Send: "+target, myNickname, target); parser.sendCTCP(target, "DCC", "SEND \""+jc.getSelectedFile().getName()+"\" "+DCC.ipToLong(DCCPlugin.getListenIP(parser))+" "+send.getPort()+" "+send.getFileSize()+((send.isTurbo()) ? " T" : "")); } else { sendLine(origin, isSilent, "DCCSendError", "Unable to start dcc send with "+target+" - unable to create listen socket"); } } } } }, "openFileThread"); // Start the thread dccThread.start(); }
public void sendFile(final String target, final InputWindow origin, final boolean isSilent, final String... args) { // New thread to ask the user what file to send final File givenFile = new File(implodeArgs(2, args)); final Thread dccThread = new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { final JFileChooser jc = (givenFile.exists()) ? new JFileChooser(givenFile) : new JFileChooser(); int result; if (!givenFile.exists() || !givenFile.isFile() ) { jc.setDialogTitle("Send file to "+target+" - DMDirc "); jc.setFileSelectionMode(JFileChooser.FILES_ONLY); jc.setMultiSelectionEnabled(false); result = jc.showOpenDialog((JFrame)Main.getUI().getMainWindow()); } else { jc.setSelectedFile(givenFile); result = JFileChooser.APPROVE_OPTION; } if (result == JFileChooser.APPROVE_OPTION) { final Server server = origin.getContainer().getServer(); final IRCParser parser = server.getParser(); final String myNickname = parser.getMyNickname(); DCCSend send = new DCCSend(IdentityManager.getGlobalConfig().getOptionInt(DCCPlugin.getDomain(), "send.blocksize", 1024)); send.setTurbo(IdentityManager.getGlobalConfig().getOptionBool(DCCPlugin.getDomain(), "send.forceturbo", false)); send.setType(DCCSend.TransferType.SEND); ActionManager.processEvent(DCCActions.DCC_SEND_REQUEST_SENT, null, server, target, jc.getSelectedFile()); sendLine(origin, isSilent, FORMAT_OUTPUT, "Starting DCC Send with: "+target); send.setFileName(jc.getSelectedFile().getAbsolutePath()); send.setFileSize(jc.getSelectedFile().length()); if (IdentityManager.getGlobalConfig().getOptionBool(DCCPlugin.getDomain(), "send.reverse", false)) { new DCCSendWindow(myPlugin, send, "Send: "+target, myNickname, target); parser.sendCTCP(target, "DCC", "SEND \""+jc.getSelectedFile().getName()+"\" "+DCC.ipToLong(DCCPlugin.getListenIP(parser))+" 0 "+send.getFileSize()+" "+send.makeToken()+((send.isTurbo()) ? " T" : "")); } else { if (myPlugin.listen(send)) { new DCCSendWindow(myPlugin, send, "*Send: "+target, myNickname, target); parser.sendCTCP(target, "DCC", "SEND \""+jc.getSelectedFile().getName()+"\" "+DCC.ipToLong(DCCPlugin.getListenIP(parser))+" "+send.getPort()+" "+send.getFileSize()+((send.isTurbo()) ? " T" : "")); } else { sendLine(origin, isSilent, "DCCSendError", "Unable to start dcc send with "+target+" - unable to create listen socket"); } } } } }, "openFileThread"); // Start the thread dccThread.start(); }
diff --git a/src/eu/bryants/anthony/plinth/compiler/passes/llvm/TypeHelper.java b/src/eu/bryants/anthony/plinth/compiler/passes/llvm/TypeHelper.java index 49ce8c7..3ed3bbd 100644 --- a/src/eu/bryants/anthony/plinth/compiler/passes/llvm/TypeHelper.java +++ b/src/eu/bryants/anthony/plinth/compiler/passes/llvm/TypeHelper.java @@ -1,4171 +1,4173 @@ package eu.bryants.anthony.plinth.compiler.passes.llvm; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import nativelib.c.C; import nativelib.llvm.LLVM; import nativelib.llvm.LLVM.LLVMBasicBlockRef; import nativelib.llvm.LLVM.LLVMBuilderRef; import nativelib.llvm.LLVM.LLVMModuleRef; import nativelib.llvm.LLVM.LLVMTypeRef; import nativelib.llvm.LLVM.LLVMValueRef; import eu.bryants.anthony.plinth.ast.ClassDefinition; import eu.bryants.anthony.plinth.ast.CompoundDefinition; import eu.bryants.anthony.plinth.ast.InterfaceDefinition; import eu.bryants.anthony.plinth.ast.TypeDefinition; import eu.bryants.anthony.plinth.ast.member.ArrayLengthMember; import eu.bryants.anthony.plinth.ast.member.BuiltinMethod; import eu.bryants.anthony.plinth.ast.member.BuiltinMethod.BuiltinMethodType; import eu.bryants.anthony.plinth.ast.member.Method; import eu.bryants.anthony.plinth.ast.member.Property; import eu.bryants.anthony.plinth.ast.metadata.GenericTypeSpecialiser; import eu.bryants.anthony.plinth.ast.metadata.MemberFunctionType; import eu.bryants.anthony.plinth.ast.metadata.MemberVariable; import eu.bryants.anthony.plinth.ast.metadata.MethodReference; import eu.bryants.anthony.plinth.ast.metadata.PropertyReference; import eu.bryants.anthony.plinth.ast.misc.Parameter; import eu.bryants.anthony.plinth.ast.type.ArrayType; import eu.bryants.anthony.plinth.ast.type.FunctionType; import eu.bryants.anthony.plinth.ast.type.NamedType; import eu.bryants.anthony.plinth.ast.type.NullType; import eu.bryants.anthony.plinth.ast.type.ObjectType; import eu.bryants.anthony.plinth.ast.type.PrimitiveType; import eu.bryants.anthony.plinth.ast.type.PrimitiveType.PrimitiveTypeType; import eu.bryants.anthony.plinth.ast.type.TupleType; import eu.bryants.anthony.plinth.ast.type.Type; import eu.bryants.anthony.plinth.ast.type.TypeParameter; import eu.bryants.anthony.plinth.ast.type.VoidType; import eu.bryants.anthony.plinth.ast.type.WildcardType; import eu.bryants.anthony.plinth.compiler.passes.SpecialTypeHandler; /* * Created on 23 Sep 2012 */ /** * A class which helps a CodeGenerator convert the AST into bitcode by providing methods to convert types into their native representations, and methods to convert between these native types. * @author Anthony Bryant */ public class TypeHelper { private static final String BASE_CHANGE_FUNCTION_PREFIX = "_base_change_o"; private static final String PROXY_FUNCTION_PREFIX = "_PROXY_"; private static final String REFERENCE_PROXY_FUNCTION_PREFIX = "_METHOD_PROXY_"; private static final String PROXY_ARRAY_GETTER_FUNCTION_PREFIX = "_PROXY_ARRAY_GET_"; private static final String PROXY_ARRAY_SETTER_FUNCTION_PREFIX = "_PROXY_ARRAY_SET_"; private static final String ARRAY_GETTER_FUNCTION_PREFIX = "_ARRAY_GET_"; private static final String ARRAY_SETTER_FUNCTION_PREFIX = "_ARRAY_SET_"; private TypeDefinition typeDefinition; private CodeGenerator codeGenerator; private VirtualFunctionHandler virtualFunctionHandler; private RTTIHelper rttiHelper; private LLVMModuleRef module; private LLVMTypeRef opaqueType; private LLVMTypeRef objectType; private Map<String, LLVMTypeRef> nativeArrayTypes = new HashMap<String, LLVMTypeRef>(); private Map<TypeDefinition, LLVMTypeRef> nativeNamedTypes = new HashMap<TypeDefinition, LLVMTypeRef>(); /** * Creates a new TypeHelper to build type conversions with the specified builder. * @param typeDefinition - the TypeDefinition to generate proxy functions in the context of * @param codeGenerator - the CodeGenerator to use to generate any miscellaneous sections of code, such as null checks * @param virtualFunctionHandler - the VirtualFunctionHandler to handle building the types of virtual function tables * @param module - the LLVMModuleRef that this TypeHelper will build inside */ public TypeHelper(TypeDefinition typeDefinition, CodeGenerator codeGenerator, VirtualFunctionHandler virtualFunctionHandler, LLVMModuleRef module) { this.typeDefinition = typeDefinition; this.codeGenerator = codeGenerator; this.virtualFunctionHandler = virtualFunctionHandler; this.module = module; opaqueType = LLVM.LLVMStructCreateNamed(codeGenerator.getContext(), "opaque"); } /** * Initialises this TypeHelper, so that it has all of the references required to operate.. * @param rttiHelper - the RTTIHelper to set */ public void initialise(RTTIHelper rttiHelper) { this.rttiHelper = rttiHelper; } /** * @return an opaque pointer type */ public LLVMTypeRef getOpaquePointer() { return LLVM.LLVMPointerType(opaqueType, 0); } /** * @return the result type of a landingpad instruction */ public LLVMTypeRef getLandingPadType() { LLVMTypeRef[] subTypes = new LLVMTypeRef[] {LLVM.LLVMPointerType(LLVM.LLVMInt8Type(), 0), LLVM.LLVMInt32Type()}; return LLVM.LLVMStructType(C.toNativePointerArray(subTypes, false, true), subTypes.length, false); } /** * Finds the standard representation for the specified type, to be used when passing parameters, or storing fields, etc. * @param type - the type to find the native type of * @return the standard native representation of the specified Type */ public LLVMTypeRef findStandardType(Type type) { return findNativeType(type, false); } /** * Finds the temporary representation for the specified type, to be used when manipulating values inside a function. * @param type - the type to find the native type of * @return the temporary native representation of the specified Type */ public LLVMTypeRef findTemporaryType(Type type) { return findNativeType(type, true); } /** * Finds the native representation of the specified type. The native representation can be of two forms: standard, and temporary. * These forms are used in different places, and can be converted between using other utility functions. * This method is not public, so to find a standard representation of a type, use findStandardType(Type); or to find a temporary representation, use findTemporaryType(Type). * @param type - the type to find the native representation of * @param temporary - true if the representation should be of the temporary form, or false if it should be in the standard form * @return the native type of the specified type */ private LLVMTypeRef findNativeType(Type type, boolean temporary) { if (type instanceof PrimitiveType) { LLVMTypeRef nonNullableType; PrimitiveTypeType primitiveTypeType = ((PrimitiveType) type).getPrimitiveTypeType(); if (primitiveTypeType == PrimitiveTypeType.DOUBLE) { nonNullableType = LLVM.LLVMDoubleType(); } else if (primitiveTypeType == PrimitiveTypeType.FLOAT) { nonNullableType = LLVM.LLVMFloatType(); } else { nonNullableType = LLVM.LLVMIntType(primitiveTypeType.getBitCount()); } if (type.canBeNullable()) { // tuple the non-nullable type with a boolean, so that we can tell whether or not the value is null LLVMTypeRef[] types = new LLVMTypeRef[] {LLVM.LLVMInt1Type(), nonNullableType}; return LLVM.LLVMStructType(C.toNativePointerArray(types, false, true), types.length, false); } return nonNullableType; } if (type instanceof ArrayType) { // strip any type parameters out of the base type, as we don't want them to change the mangled name of the array // the reason for this is that there should never be any difference between the native representation of a type, and its native representation after having its type parameters stripped Type baseType = stripTypeParameters(((ArrayType) type).getBaseType()); ArrayType arrayType = new ArrayType(false, false, baseType, null); String mangledTypeName = arrayType.getMangledName(); LLVMTypeRef existingType = nativeArrayTypes.get(mangledTypeName); if (existingType != null) { return LLVM.LLVMPointerType(existingType, 0); } LLVMTypeRef llvmArrayType = LLVM.LLVMStructCreateNamed(codeGenerator.getContext(), mangledTypeName); nativeArrayTypes.put(mangledTypeName, llvmArrayType); LLVMTypeRef rttiType = rttiHelper.getGenericRTTIType(); LLVMTypeRef vftPointerType = LLVM.LLVMPointerType(virtualFunctionHandler.getObjectVFTType(), 0); LLVMTypeRef lengthType = LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()); LLVMTypeRef[] getterFunctionParamTypes = new LLVMTypeRef[] {LLVM.LLVMPointerType(llvmArrayType, 0), lengthType}; LLVMTypeRef getterFunctionType = LLVM.LLVMFunctionType(findTemporaryType(arrayType.getBaseType()), C.toNativePointerArray(getterFunctionParamTypes, false, true), getterFunctionParamTypes.length, false); LLVMTypeRef[] setterFunctionParamTypes = new LLVMTypeRef[] {LLVM.LLVMPointerType(llvmArrayType, 0), lengthType, findStandardType(arrayType.getBaseType())}; LLVMTypeRef setterFunctionType = LLVM.LLVMFunctionType(LLVM.LLVMVoidType(), C.toNativePointerArray(setterFunctionParamTypes, false, true), setterFunctionParamTypes.length, false); LLVMTypeRef[] structureTypes = new LLVMTypeRef[] {rttiType, vftPointerType, lengthType, LLVM.LLVMPointerType(getterFunctionType, 0), LLVM.LLVMPointerType(setterFunctionType, 0)}; LLVM.LLVMStructSetBody(llvmArrayType, C.toNativePointerArray(structureTypes, false, true), structureTypes.length, false); return LLVM.LLVMPointerType(llvmArrayType, 0); } if (type instanceof FunctionType) { // create a tuple of an opaque pointer and a function pointer which has an opaque pointer as its first argument FunctionType functionType = (FunctionType) type; LLVMTypeRef rttiPointerType = rttiHelper.getGenericRTTIType(); LLVMTypeRef llvmOpaquePointerType = LLVM.LLVMPointerType(opaqueType, 0); LLVMTypeRef llvmFunctionPointer = findRawFunctionPointerType(functionType); LLVMTypeRef[] subTypes = new LLVMTypeRef[] {rttiPointerType, llvmOpaquePointerType, llvmFunctionPointer}; return LLVM.LLVMStructType(C.toNativePointerArray(subTypes, false, true), subTypes.length, false); } if (type instanceof TupleType) { TupleType tupleType = (TupleType) type; Type[] subTypes = tupleType.getSubTypes(); LLVMTypeRef[] llvmSubTypes = new LLVMTypeRef[subTypes.length]; for (int i = 0; i < subTypes.length; i++) { llvmSubTypes[i] = findNativeType(subTypes[i], temporary); } LLVMTypeRef nonNullableType = LLVM.LLVMStructType(C.toNativePointerArray(llvmSubTypes, false, true), llvmSubTypes.length, false); if (tupleType.canBeNullable()) { // tuple the non-nullable type with a boolean, so that we can tell whether or not the value is null LLVMTypeRef[] types = new LLVMTypeRef[] {LLVM.LLVMInt1Type(), nonNullableType}; return LLVM.LLVMStructType(C.toNativePointerArray(types, false, true), types.length, false); } return nonNullableType; } if (type instanceof NamedType && ((NamedType) type).getResolvedTypeDefinition() != null) { NamedType namedType = (NamedType) type; TypeDefinition typeDefinition = namedType.getResolvedTypeDefinition(); // check whether the type has been cached LLVMTypeRef existingType = nativeNamedTypes.get(typeDefinition); if (existingType != null) { if (typeDefinition instanceof CompoundDefinition) { if (temporary) { // for temporary CompoundDefinition values, we use a pointer to the non-nullable type, whether or not the type is nullable return LLVM.LLVMPointerType(existingType, 0); } if (namedType.canBeNullable()) { // tuple the non-nullable type with a boolean, so that we can tell whether or not the value is null // this is not necessary for ClassDefinitions, since they are pointers which can actually be null LLVMTypeRef[] types = new LLVMTypeRef[] {LLVM.LLVMInt1Type(), existingType}; return LLVM.LLVMStructType(C.toNativePointerArray(types, false, true), types.length, false); } } return existingType; } // the type isn't cached, so create it if (typeDefinition instanceof ClassDefinition) { // cache the LLVM type before we recurse, so that once we recurse, everything will be able to use this type instead of recreating it and possibly recursing infinitely // later on, we add the fields using LLVMStructSetBody LLVMTypeRef structType = LLVM.LLVMStructCreateNamed(codeGenerator.getContext(), typeDefinition.getQualifiedName().toString()); LLVMTypeRef pointerToStruct = LLVM.LLVMPointerType(structType, 0); nativeNamedTypes.put(typeDefinition, pointerToStruct); // add the fields to the struct type (findClassSubTypes() will call findNativeType() recursively) LLVMTypeRef[] llvmSubTypes = findClassSubTypes((ClassDefinition) typeDefinition); LLVM.LLVMStructSetBody(structType, C.toNativePointerArray(llvmSubTypes, false, true), llvmSubTypes.length, false); return pointerToStruct; } else if (typeDefinition instanceof CompoundDefinition) { // cache the LLVM type before we recurse, so that once we recurse, everything will be able to use this type instead of recreating it // later on, we add the fields using LLVMStructSetBody LLVMTypeRef nonNullableStructType = LLVM.LLVMStructCreateNamed(codeGenerator.getContext(), typeDefinition.getQualifiedName().toString()); nativeNamedTypes.put(typeDefinition, nonNullableStructType); TypeParameter[] typeParameters = typeDefinition.getTypeParameters(); MemberVariable[] instanceVariables = ((CompoundDefinition) typeDefinition).getMemberVariables(); LLVMTypeRef[] llvmSubTypes = new LLVMTypeRef[typeParameters.length + instanceVariables.length]; // add the type argument RTTI pointers to the struct for (int i = 0; i < typeParameters.length; ++i) { llvmSubTypes[i] = rttiHelper.getGenericRTTIType(); } // add the fields to the struct recursively for (int i = 0; i < instanceVariables.length; i++) { llvmSubTypes[typeParameters.length + i] = findNativeType(instanceVariables[i].getType(), false); } LLVM.LLVMStructSetBody(nonNullableStructType, C.toNativePointerArray(llvmSubTypes, false, true), llvmSubTypes.length, false); if (temporary) { // for temporary values, we use a pointer to the non-nullable type, whether or not the type is nullable return LLVM.LLVMPointerType(nonNullableStructType, 0); } if (namedType.canBeNullable()) { // tuple the non-nullable type with a boolean, so that we can tell whether or not the value is null LLVMTypeRef[] types = new LLVMTypeRef[] {LLVM.LLVMInt1Type(), nonNullableStructType}; return LLVM.LLVMStructType(C.toNativePointerArray(types, false, true), types.length, false); } return nonNullableStructType; } else if (typeDefinition instanceof InterfaceDefinition) { // an interface's type is a tuple of: // 1. the interface's VFT // 2. the object being pointed to // 3. any wildcard type arguments' RTTI pointers int numWildcards = 0; Type[] typeArguments = namedType.getTypeArguments(); for (int i = 0; typeArguments != null && i < typeArguments.length; ++i) { if (typeArguments[i] instanceof WildcardType) { numWildcards++; } } LLVMTypeRef[] types = new LLVMTypeRef[2 + numWildcards]; types[0] = LLVM.LLVMPointerType(virtualFunctionHandler.getVFTType(typeDefinition), 0); types[1] = findNativeType(new ObjectType(false, false, null), false); for (int i = 0; i < numWildcards; ++i) { types[2 + i] = rttiHelper.getGenericRTTIType(); } return LLVM.LLVMStructType(C.toNativePointerArray(types, false, true), types.length, false); } } if (type instanceof ObjectType || (type instanceof NamedType && ((NamedType) type).getResolvedTypeParameter() != null) || type instanceof WildcardType) { if (objectType != null) { return LLVM.LLVMPointerType(objectType, 0); } objectType = LLVM.LLVMStructCreateNamed(codeGenerator.getContext(), "object"); LLVMTypeRef rttiType = rttiHelper.getGenericRTTIType(); LLVMTypeRef vftPointerType = LLVM.LLVMPointerType(virtualFunctionHandler.getObjectVFTType(), 0); LLVMTypeRef[] structSubTypes = new LLVMTypeRef[] {rttiType, vftPointerType}; LLVM.LLVMStructSetBody(objectType, C.toNativePointerArray(structSubTypes, false, true), structSubTypes.length, false); return LLVM.LLVMPointerType(objectType, 0); } if (type instanceof NullType) { return LLVM.LLVMStructType(C.toNativePointerArray(new LLVMTypeRef[0], false, true), 0, false); } if (type instanceof VoidType) { return LLVM.LLVMVoidType(); } throw new IllegalStateException("Unexpected Type: " + type); } /** * Finds a function pointer type in its raw form, before being tupled with its RTTI and first argument (always an opaque pointer). * This <b>IS NOT</b> a full function type, and should not be used as such. * @param functionType - the function type to find the raw LLVM form of * @return the LLVMTypeRef corresponding to the raw form of the specified function type */ // package protected and not private, because it needs to be accessible to CodeGenerator for buildNullCheck() LLVMTypeRef findRawFunctionPointerType(FunctionType functionType) { LLVMTypeRef llvmFunctionReturnType = findNativeType(functionType.getReturnType(), false); Type[] parameterTypes = functionType.getParameterTypes(); LLVMTypeRef[] llvmParameterTypes = new LLVMTypeRef[parameterTypes.length + 1]; llvmParameterTypes[0] = LLVM.LLVMPointerType(opaqueType, 0); for (int i = 0; i < parameterTypes.length; ++i) { llvmParameterTypes[i + 1] = findNativeType(parameterTypes[i], false); } LLVMTypeRef llvmFunctionType = LLVM.LLVMFunctionType(llvmFunctionReturnType, C.toNativePointerArray(llvmParameterTypes, false, true), llvmParameterTypes.length, false); return LLVM.LLVMPointerType(llvmFunctionType, 0); } /** * Finds the raw string type. * This is similar to the type of []ubyte, as an LLVM struct, but also contains the actual array of values in addition to the getter and setter functions. * This makes it incompatible with any arrays of ubyte which might be proxied generic arrays. * @return the raw LLVM type of a string constant */ public LLVMTypeRef findRawStringType() { ArrayType arrayType = new ArrayType(false, false, new PrimitiveType(false, PrimitiveTypeType.UBYTE, null), null); return LLVM.LLVMPointerType(findNonProxiedArrayStructureType(arrayType, 0), 0); } /** * Finds an object type specialised to include some specialised data of the specified type. * @param specialisationType - the type that this object should hold (to be appended to the normal object type representation) * @return an object type, with an extra field to contain the standard type representation of the specified specialisation type */ public LLVMTypeRef findSpecialisedObjectType(Type specialisationType) { LLVMTypeRef rttiType = rttiHelper.getGenericRTTIType(); LLVMTypeRef vftPointerType = LLVM.LLVMPointerType(virtualFunctionHandler.getObjectVFTType(), 0); LLVMTypeRef llvmSpecialisedType = findStandardType(specialisationType); LLVMTypeRef[] structSubTypes = new LLVMTypeRef[] {rttiType, vftPointerType, llvmSpecialisedType}; LLVMTypeRef structType = LLVM.LLVMStructType(C.toNativePointerArray(structSubTypes, false, true), structSubTypes.length, false); return structType; } /** * Finds the type of the structure inside (i.e. not a pointer to) a non-proxied array of the specified length. * @param arrayType - the type of array to find the non-proxied type of * @param length - the length of the native array * @return the LLVM type of the structure inside a non-proxied array of the specified ArrayType */ public LLVMTypeRef findNonProxiedArrayStructureType(ArrayType arrayType, int length) { LLVMTypeRef llvmArrayType = findStandardType(arrayType); LLVMTypeRef rttiType = rttiHelper.getGenericRTTIType(); LLVMTypeRef vftPointerType = LLVM.LLVMPointerType(virtualFunctionHandler.getObjectVFTType(), 0); LLVMTypeRef lengthType = findStandardType(ArrayLengthMember.ARRAY_LENGTH_TYPE); LLVMTypeRef[] getFunctionParamTypes = new LLVMTypeRef[] {llvmArrayType, lengthType}; LLVMTypeRef getFunctionType = LLVM.LLVMFunctionType(findTemporaryType(arrayType.getBaseType()), C.toNativePointerArray(getFunctionParamTypes, false, true), getFunctionParamTypes.length, false); LLVMTypeRef[] setFunctionParamTypes = new LLVMTypeRef[] {llvmArrayType, lengthType, findStandardType(arrayType.getBaseType())}; LLVMTypeRef setFunctionType = LLVM.LLVMFunctionType(LLVM.LLVMVoidType(), C.toNativePointerArray(setFunctionParamTypes, false, true), setFunctionParamTypes.length, false); LLVMTypeRef standardElementType = findStandardType(arrayType.getBaseType()); LLVMTypeRef elementsArrayType = LLVM.LLVMArrayType(standardElementType, length); LLVMTypeRef[] structureTypes = new LLVMTypeRef[] {rttiType, vftPointerType, lengthType, LLVM.LLVMPointerType(getFunctionType, 0), LLVM.LLVMPointerType(setFunctionType, 0), elementsArrayType}; LLVMTypeRef resultType = LLVM.LLVMStructType(C.toNativePointerArray(structureTypes, false, true), structureTypes.length, false); return resultType; } /** * Finds the native (LLVM) type of the specified Method * @param method - the Method to find the LLVM type of * @return the LLVMTypeRef representing the type of the specified Method */ public LLVMTypeRef findMethodType(Method method) { Parameter[] parameters = method.getParameters(); LLVMTypeRef[] types; int offset = 1; // add the 'this' type to the function - 'this' always has a temporary type representation if (method.isStatic()) { // for static methods, we add an unused opaque*, so that the static method can be easily converted to a function type types = new LLVMTypeRef[1 + parameters.length]; types[0] = getOpaquePointer(); } else if (method.getContainingTypeDefinition() instanceof ClassDefinition) { types = new LLVMTypeRef[1 + parameters.length]; types[0] = findTemporaryType(new NamedType(false, method.isImmutable(), method.isImmutable(), method.getContainingTypeDefinition())); } else if (method.getContainingTypeDefinition() instanceof CompoundDefinition) { types = new LLVMTypeRef[1 + parameters.length]; types[0] = findTemporaryType(new NamedType(false, method.isImmutable(), method.isImmutable(), method.getContainingTypeDefinition())); } else if (method.getContainingTypeDefinition() instanceof InterfaceDefinition) { TypeParameter[] typeParameters = method.getContainingTypeDefinition().getTypeParameters(); types = new LLVMTypeRef[1 + typeParameters.length + parameters.length]; types[0] = findTemporaryType(new NamedType(false, method.isImmutable(), method.isImmutable(), method.getContainingTypeDefinition())); for (int i = 0; i < typeParameters.length; ++i) { types[offset + i] = rttiHelper.getGenericRTTIType(); } offset += typeParameters.length; } else if (method instanceof BuiltinMethod) { types = new LLVMTypeRef[1 + parameters.length]; types[0] = findTemporaryType(((BuiltinMethod) method).getBaseType()); } else { throw new IllegalArgumentException("Unknown type of method: " + method); } for (int i = 0; i < parameters.length; ++i) { types[offset + i] = findStandardType(parameters[i].getType()); } LLVMTypeRef resultType = findStandardType(method.getReturnType()); return LLVM.LLVMFunctionType(resultType, C.toNativePointerArray(types, false, true), types.length, false); } /** * Finds the native (LLVM) type of the getter of the specified Property * @param property - the Property to find the LLVM type of the getter of * @return the LLVMTypeRef representing the type of the specified Property's getter method */ public LLVMTypeRef findPropertyGetterType(Property property) { TypeDefinition typeDefinition = property.getContainingTypeDefinition(); LLVMTypeRef[] types; if (property.isStatic()) { types = new LLVMTypeRef[1]; types[0] = getOpaquePointer(); } else { if (typeDefinition instanceof InterfaceDefinition) { TypeParameter[] typeParameters = typeDefinition.getTypeParameters(); types = new LLVMTypeRef[1 + typeParameters.length]; types[0] = findTemporaryType(new NamedType(false, false, false, typeDefinition)); for (int i = 0; i < typeParameters.length; ++i) { types[1 + i] = rttiHelper.getGenericRTTIType(); } } else { types = new LLVMTypeRef[1]; types[0] = findTemporaryType(new NamedType(false, false, false, typeDefinition)); } } LLVMTypeRef resultType = findStandardType(property.getType()); return LLVM.LLVMFunctionType(resultType, C.toNativePointerArray(types, false, true), types.length, false); } /** * Finds the native (LLVM) type of the setter or constructor of the specified Property * @param property - the Property to find the LLVM type of the setter/constructor of * @return the LLVMTypeRef representing the type of the specified Property's setter/constructor method */ public LLVMTypeRef findPropertySetterConstructorType(Property property) { TypeDefinition typeDefinition = property.getContainingTypeDefinition(); LLVMTypeRef[] types; int offset = 1; if (property.isStatic()) { types = new LLVMTypeRef[2]; types[0] = getOpaquePointer(); } else { if (typeDefinition instanceof InterfaceDefinition) { TypeParameter[] typeParameters = typeDefinition.getTypeParameters(); types = new LLVMTypeRef[2 + typeParameters.length]; types[0] = findTemporaryType(new NamedType(false, false, false, typeDefinition)); for (int i = 0; i < typeParameters.length; ++i) { types[offset + i] = rttiHelper.getGenericRTTIType(); } offset += typeParameters.length; } else { types = new LLVMTypeRef[2]; types[0] = findTemporaryType(new NamedType(false, false, false, typeDefinition)); } } types[offset] = findStandardType(property.getType()); LLVMTypeRef resultType = LLVM.LLVMVoidType(); return LLVM.LLVMFunctionType(resultType, C.toNativePointerArray(types, false, true), types.length, false); } /** * Finds the sub-types of the native representation of the specified ClassDefinition, including fields and virtual function table pointers. * @param classDefinition - the class definition to find the sub-types of * @return the sub-types of the specified ClassDefinition */ private LLVMTypeRef[] findClassSubTypes(ClassDefinition classDefinition) { NamedType[] implementedInterfaces = findSubClassInterfaces(classDefinition); NamedType superType = classDefinition.getSuperType(); TypeParameter[] typeParameters = classDefinition.getTypeParameters(); MemberVariable[] nonStaticVariables = classDefinition.getMemberVariables(); int offset; // offset to the class VFT LLVMTypeRef[] subTypes; if (superType == null) { // 1 RTTI pointer, 1 object-VFT (for builtin methods), 1 class VFT, some interface VFTs, some type parameter RTTI pointers, and some fields subTypes = new LLVMTypeRef[3 + implementedInterfaces.length + typeParameters.length + nonStaticVariables.length]; subTypes[0] = rttiHelper.getGenericRTTIType(); subTypes[1] = LLVM.LLVMPointerType(virtualFunctionHandler.getObjectVFTType(), 0); offset = 2; } else { ClassDefinition superClassDefinition = (ClassDefinition) superType.getResolvedTypeDefinition(); LLVMTypeRef[] superClassSubTypes = findClassSubTypes(superClassDefinition); // everything from the super-class, 1 class VFT, some interface VFTs, some type parameter RTTI pointers, and some fields // we only include interfaces which were not included in any super-classes subTypes = new LLVMTypeRef[superClassSubTypes.length + 1 + implementedInterfaces.length + typeParameters.length + nonStaticVariables.length]; System.arraycopy(superClassSubTypes, 0, subTypes, 0, superClassSubTypes.length); offset = superClassSubTypes.length; } subTypes[offset] = LLVM.LLVMPointerType(virtualFunctionHandler.getVFTType(classDefinition), 0); for (int i = 0; i < implementedInterfaces.length; ++i) { subTypes[offset + 1 + i] = LLVM.LLVMPointerType(virtualFunctionHandler.getVFTType(implementedInterfaces[i].getResolvedTypeDefinition()), 0); } offset += 1 + implementedInterfaces.length; for (int i = 0; i < typeParameters.length; ++i) { subTypes[offset + i] = rttiHelper.getGenericRTTIType(); } offset += typeParameters.length; for (int i = 0; i < nonStaticVariables.length; ++i) { subTypes[offset + i] = findNativeType(nonStaticVariables[i].getType(), false); } return subTypes; } /** * Finds the list of interface types which are implemented in the specified ClassDefinition, but in none of its super-classes, in linearisation order. * @param classDefinition - the ClassDefinition to find the list of interfaces for * @return the list of interfaces for the specified sub-class in linearisation order */ NamedType[] findSubClassInterfaces(ClassDefinition classDefinition) { List<NamedType> result = new LinkedList<NamedType>(); for (NamedType superType : classDefinition.getInheritanceLinearisation()) { if (superType.getResolvedTypeDefinition() instanceof InterfaceDefinition) { result.add(superType); } } // since the direct super-class's linearisation contains everything inherited above this class, we don't need to go through the whole hierarchy ourselves NamedType directSuperType = classDefinition.getSuperType(); if (directSuperType != null) { GenericTypeSpecialiser genericTypeSpecialiser = new GenericTypeSpecialiser(directSuperType); for (NamedType superSuperType : directSuperType.getResolvedTypeDefinition().getInheritanceLinearisation()) { Iterator<NamedType> it = result.iterator(); while (it.hasNext()) { if (it.next().isRuntimeEquivalent(genericTypeSpecialiser.getSpecialisedType(superSuperType))) { it.remove(); } } } } return result.toArray(new NamedType[result.size()]); } /** * Finds the pointer to the specified TypeParameter inside the specified value. * @param builder - the LLVMBuilderRef to build instructions with * @param baseValue - the base value to get the TypeParameter of, in a temporary type representation - this must be of a type which contains the specified TypeParameter (or a sub-type thereof) * @param typeParameter - the TypeParameter to get the pointer to - this must not be an interface's TypeParameter * @return the pointer to the specified TypeParameter's location inside the specified base value */ public LLVMValueRef getTypeParameterPointer(LLVMBuilderRef builder, LLVMValueRef baseValue, TypeParameter typeParameter) { TypeDefinition typeDefinition = typeParameter.getContainingTypeDefinition(); if (typeDefinition instanceof InterfaceDefinition) { throw new IllegalArgumentException("Cannot get a pointer to an interface's TypeParameter RTTI block: " + typeParameter); } TypeParameter[] typeParameters = typeDefinition.getTypeParameters(); int index = -1; for (int i = 0; i < typeParameters.length; ++i) { if (typeParameters[i] == typeParameter) { index = i; break; } } if (index == -1) { throw new IllegalStateException("A TypeParameter is not contained by its containingTypeDefinition: " + typeParameter); } if (typeDefinition instanceof ClassDefinition) { // skip the RTTI pointer and the object VFT from the top-level class index += 2; // skip the super-class representations NamedType superType = ((ClassDefinition) typeDefinition).getSuperType(); while (superType != null) { ClassDefinition superClassDefinition = (ClassDefinition) superType.getResolvedTypeDefinition(); // 1 class VFT, some interface VFTs, some type parameter RTTI pointers, and some fields index += 1 + findSubClassInterfaces(superClassDefinition).length + superClassDefinition.getTypeParameters().length + superClassDefinition.getMemberVariables().length; superType = superClassDefinition.getSuperType(); } // skip the virtual function tables from this class index += 1 + findSubClassInterfaces((ClassDefinition) typeDefinition).length; } // note: compound definitions work here too, because their type parameters are stored right at the start of their type representation return LLVM.LLVMBuildStructGEP(builder, baseValue, index, ""); } /** * Finds the pointer to the specified field inside the specified value. * The value should be a NamedType in a temporary type representation, and should be for the type which contains the specified field, or a subtype thereof. * @param builder - the LLVMBuilderRef to build instructions with * @param baseValue - the base value to get the field of * @param memberVariable - the MemberVariable to extract * @return a pointer to the specified field inside baseValue */ public LLVMValueRef getMemberPointer(LLVMBuilderRef builder, LLVMValueRef baseValue, MemberVariable memberVariable) { TypeDefinition typeDefinition = memberVariable.getEnclosingTypeDefinition(); int index = memberVariable.getMemberIndex(); if (typeDefinition instanceof ClassDefinition) { // skip the RTTI pointer and the object VFT from the top-level class index += 2; // skip the super-class representations NamedType superType = ((ClassDefinition) typeDefinition).getSuperType(); while (superType != null) { ClassDefinition superClassDefinition = (ClassDefinition) superType.getResolvedTypeDefinition(); // 1 class VFT, some interface VFTs, some type parameter RTTI pointers, and some fields index += 1 + findSubClassInterfaces(superClassDefinition).length + superClassDefinition.getTypeParameters().length + superClassDefinition.getMemberVariables().length; superType = superClassDefinition.getSuperType(); } // skip the virtual function tables and type parameters from this class index += 1 + findSubClassInterfaces((ClassDefinition) typeDefinition).length + typeDefinition.getTypeParameters().length; } else if (typeDefinition instanceof CompoundDefinition) { // skip this compound type's type parameters index += typeDefinition.getTypeParameters().length; } return LLVM.LLVMBuildStructGEP(builder, baseValue, index, ""); } /** * Gets the poiner to the length field of the specified array. * @param builder - the LLVMBuilderRef to build instructions with * @param array - the array to get the length field of, in a temporary type representation * @return a pointer to the length field of the specified array */ public LLVMValueRef getArrayLengthPointer(LLVMBuilderRef builder, LLVMValueRef array) { return LLVM.LLVMBuildStructGEP(builder, array, 2, ""); } /** * Finds the pointer to the getter function inside the specified array * @param builder - the LLVMBuilderRef to build instructions with * @param array - the array to get the getter function of * @return the pointer to the getter function of the specified array */ public LLVMValueRef getArrayGetterFunctionPointer(LLVMBuilderRef builder, LLVMValueRef array) { return LLVM.LLVMBuildStructGEP(builder, array, 3, ""); } /** * Finds the pointer to the setter function inside the specified array * @param builder - the LLVMBuilderRef to build instructions with * @param array - the array to get the setter function of * @return the pointer to the setter function of the specified array */ public LLVMValueRef getArraySetterFunctionPointer(LLVMBuilderRef builder, LLVMValueRef array) { return LLVM.LLVMBuildStructGEP(builder, array, 4, ""); } /** * Finds the pointer to the specified element inside the specified non-proxied array. * @param builder - the LLVMBuilderRef to build instructions with * @param array - the non-proxied array to get the element of * @param index - the index to get inside the array * @return the pointer to the element at the specified index inside the non-proxied array */ public LLVMValueRef getNonProxiedArrayElementPointer(LLVMBuilderRef builder, LLVMValueRef array, LLVMValueRef index) { LLVMValueRef[] elementIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 0, false), LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 5, false), index}; return LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(elementIndices, false, true), elementIndices.length, ""); } /** * Retrieves the value at the specified index in the specified array. * @param builder - the LLVMBuilderRef to build instructions with * @param landingPadContainer - the LandingPadContainer containing the landing pad block for exceptions to be unwound to * @param array - the array to get the element out of, in a temporary type representation * @param index - the index in the array to retrieve the element from, as an i32 * @return the array element at the specified index, in a temporary type representation */ public LLVMValueRef buildRetrieveArrayElement(LLVMBuilderRef builder, LandingPadContainer landingPadContainer, LLVMValueRef array, LLVMValueRef index) { LLVMValueRef getterFunctionPtr = LLVM.LLVMBuildStructGEP(builder, array, 3, ""); LLVMValueRef getterFunction = LLVM.LLVMBuildLoad(builder, getterFunctionPtr, ""); LLVMValueRef[] arguments = new LLVMValueRef[] {array, index}; LLVMBasicBlockRef continuationBlock = LLVM.LLVMAddBasicBlock(builder, "arrayRetrieveInvokeContinue"); LLVMValueRef result = LLVM.LLVMBuildInvoke(builder, getterFunction, C.toNativePointerArray(arguments, false, true), arguments.length, continuationBlock, landingPadContainer.getLandingPadBlock(), ""); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); return result; } /** * Stores the specified value in the specified array. * @param builder - the LLVMBuilderRef to build instructions with * @param landingPadContainer - the LandingPadContainer containing the landing pad block for exceptions to be unwound to * @param array - the array to store the element inside * @param index - the index in the array to store the element in, as an i32 * @param value - the value to store in the array, in a standard type representation */ public void buildStoreArrayElement(LLVMBuilderRef builder, LandingPadContainer landingPadContainer, LLVMValueRef array, LLVMValueRef index, LLVMValueRef value) { LLVMValueRef setterFunctionPtr = LLVM.LLVMBuildStructGEP(builder, array, 4, ""); LLVMValueRef setterFunction = LLVM.LLVMBuildLoad(builder, setterFunctionPtr, ""); LLVMValueRef[] arguments = new LLVMValueRef[] {array, index, value}; LLVMBasicBlockRef continuationBlock = LLVM.LLVMAddBasicBlock(builder, "arrayStoreInvokeContinue"); LLVM.LLVMBuildInvoke(builder, setterFunction, C.toNativePointerArray(arguments, false, true), arguments.length, continuationBlock, landingPadContainer.getLandingPadBlock(), ""); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); } /** * Builds a function which proxies a given Method and converts the argument and return types to the types of the specified MethodReference. * The generated function accepts arguments and returns results of the MethodReference's type, and expects a callee containing some proxy-function-specific data, which includes a type argument mapper. * The generated function is private to the current TypeDefinition, as it extracts data from a type argument mapper which is expected to be in the format of this TypeDefinition. * @param methodReference - the MethodReference that the proxy function is for * @return the LLVM function created */ private LLVMValueRef buildMethodReferenceProxyFunction(MethodReference methodReference) { String mangledName = REFERENCE_PROXY_FUNCTION_PREFIX + methodReference.getDisambiguator().toString() + "_" + methodReference.getReferencedMember().getMangledName(); LLVMValueRef existingFunction = LLVM.LLVMGetNamedFunction(module, mangledName); if (existingFunction != null) { return existingFunction; } Method method = methodReference.getReferencedMember(); Parameter[] proxiedParameters = method.getParameters(); Type[] parameterTypes = methodReference.getParameterTypes(); LLVMTypeRef[] llvmParameterTypes = new LLVMTypeRef[1 + parameterTypes.length]; llvmParameterTypes[0] = getOpaquePointer(); for (int i = 0; i < parameterTypes.length; ++i) { llvmParameterTypes[1 + i] = findStandardType(parameterTypes[i]); } LLVMTypeRef returnType = findStandardType(methodReference.getReturnType()); LLVMTypeRef functionType = LLVM.LLVMFunctionType(returnType, C.toNativePointerArray(llvmParameterTypes, false, true), llvmParameterTypes.length, false); LLVMValueRef function = LLVM.LLVMAddFunction(module, mangledName, functionType); LLVM.LLVMSetLinkage(function, LLVM.LLVMLinkage.LLVMPrivateLinkage); LLVM.LLVMSetVisibility(function, LLVM.LLVMVisibility.LLVMHiddenVisibility); LLVMBuilderRef builder = LLVM.LLVMCreateFunctionBuilder(function); LandingPadContainer landingPadContainer = new LandingPadContainer(builder); // find the type of the callee opaque pointer, and the things we need to extract from it LLVMTypeRef nativeCalleeType; int numRTTIBlocks = 0; if (method.isStatic()) { nativeCalleeType = getOpaquePointer(); } else { if (methodReference.getContainingType() != null) { if (method.getContainingTypeDefinition() instanceof InterfaceDefinition) { // make sure we don't accidentally use a type with wildcard type parameters embedded in it nativeCalleeType = findStandardType(new NamedType(false, false, false, method.getContainingTypeDefinition())); // interfaces need to have their type arguments' RTTI blocks passed into their functions, so we need to pass them in through the opaque pointer // here, we find out how many of them we will need to pass through Type[] typeArguments = methodReference.getContainingType().getTypeArguments(); numRTTIBlocks = typeArguments == null ? 0 : typeArguments.length; } else { nativeCalleeType = findStandardType(methodReference.getContainingType()); } } else { // the method reference does not have a containing type, so we can assume that this is a builtin method nativeCalleeType = findStandardType(((BuiltinMethod) method).getBaseType()); } } LLVMTypeRef proxiedFunctionType = LLVM.LLVMPointerType(findMethodType(method), 0); LLVMTypeRef typeArgumentMapperType = rttiHelper.getGenericTypeArgumentMapperStructureType(); LLVMTypeRef[] opaquePointerSubTypes = new LLVMTypeRef[3 + numRTTIBlocks]; opaquePointerSubTypes[0] = nativeCalleeType; opaquePointerSubTypes[1] = proxiedFunctionType; for (int i = 0; i < numRTTIBlocks; ++i) { opaquePointerSubTypes[2 + i] = rttiHelper.getGenericRTTIType(); } opaquePointerSubTypes[2 + numRTTIBlocks] = typeArgumentMapperType; LLVMTypeRef opaquePointerType = LLVM.LLVMStructType(C.toNativePointerArray(opaquePointerSubTypes, false, true), opaquePointerSubTypes.length, false); LLVMValueRef opaquePointer = LLVM.LLVMGetParam(function, 0); opaquePointer = LLVM.LLVMBuildBitCast(builder, opaquePointer, LLVM.LLVMPointerType(opaquePointerType, 0), ""); LLVMValueRef calleePointer = LLVM.LLVMBuildStructGEP(builder, opaquePointer, 0, ""); LLVMValueRef callee = LLVM.LLVMBuildLoad(builder, calleePointer, ""); LLVMValueRef proxiedFunctionPtr = LLVM.LLVMBuildStructGEP(builder, opaquePointer, 1, ""); LLVMValueRef proxiedFunction = LLVM.LLVMBuildLoad(builder, proxiedFunctionPtr, ""); LLVMValueRef typeMapper = LLVM.LLVMBuildStructGEP(builder, opaquePointer, 2 + numRTTIBlocks, ""); TypeParameterAccessor typeParameterAccessor = new TypeParameterAccessor(builder, rttiHelper, typeDefinition, typeMapper); // create the argument list to the proxy function, and put the callee and any required type parameter RTTI pointers into it LLVMValueRef[] realArguments; int offset; TypeParameterAccessor methodTypeAccessor; if (method.isStatic()) { methodTypeAccessor = new TypeParameterAccessor(builder, rttiHelper); realArguments = new LLVMValueRef[1 + proxiedParameters.length]; offset = 1; } else if (method.getContainingTypeDefinition() instanceof InterfaceDefinition) { // interfaces need type argument RTTI blocks to be passed in as parameters, so extract them from the opaque pointer where they are stored // also, we need to build methodTypeAccessor from these RTTI blocks Map<TypeParameter, LLVMValueRef> knownTypeParameters = new HashMap<TypeParameter, LLVMValueRef>(); TypeParameter[] typeParameters = method.getContainingTypeDefinition().getTypeParameters(); realArguments = new LLVMValueRef[1 + numRTTIBlocks + proxiedParameters.length]; for (int i = 0; i < numRTTIBlocks; ++i) { LLVMValueRef rttiBlockPtr = LLVM.LLVMBuildStructGEP(builder, opaquePointer, 2 + i, ""); realArguments[1 + i] = LLVM.LLVMBuildLoad(builder, rttiBlockPtr, ""); knownTypeParameters.put(typeParameters[i], realArguments[1 + i]); } methodTypeAccessor = new TypeParameterAccessor(builder, rttiHelper, method.getContainingTypeDefinition(), knownTypeParameters); offset = 1 + numRTTIBlocks; } else { if (method.getContainingTypeDefinition() != null) { methodTypeAccessor = new TypeParameterAccessor(builder, this, rttiHelper, method.getContainingTypeDefinition(), callee); } else { // assume this method is a builtin method, in which case it can reference type parameters from inside typeParameterAccessor, but not define its own methodTypeAccessor = typeParameterAccessor; } realArguments = new LLVMValueRef[1 + proxiedParameters.length]; offset = 1; } realArguments[0] = callee; // convert the arguments for (int i = 0; i < parameterTypes.length; ++i) { LLVMValueRef argument = LLVM.LLVMGetParam(function, 1 + i); Type realParameterType = proxiedParameters[i].getType(); argument = convertStandardToTemporary(builder, argument, parameterTypes[i]); // we skip run-time checks for this conversion, because the only change is type parameters being filled in by the MethodReference, // and we know at compile-time that they are more specific in the MethodReference than in the Method's actual type argument = convertTemporary(builder, landingPadContainer, argument, parameterTypes[i], realParameterType, true, typeParameterAccessor, methodTypeAccessor); argument = convertTemporaryToStandard(builder, argument, realParameterType); realArguments[offset + i] = argument; } // call the function LLVMBasicBlockRef invokeContinueBlock = LLVM.LLVMAddBasicBlock(builder, "methodInvokeContinue"); LLVMValueRef result = LLVM.LLVMBuildInvoke(builder, proxiedFunction, C.toNativePointerArray(realArguments, false, true), realArguments.length, invokeContinueBlock, landingPadContainer.getLandingPadBlock(), ""); LLVM.LLVMPositionBuilderAtEnd(builder, invokeContinueBlock); if (methodReference.getReturnType() instanceof VoidType) { LLVM.LLVMBuildRetVoid(builder); } else { // convert the result Type realResultType = method.getReturnType(); result = convertStandardToTemporary(builder, result, realResultType); // we skip run-time checks for this conversion, because the only change is type parameters being filled in by the MethodReference, // and we know at compile-time that they are more specific in the MethodReference than in the Method's actual type result = convertTemporary(builder, landingPadContainer, result, realResultType, methodReference.getReturnType(), true, methodTypeAccessor, typeParameterAccessor); result = convertTemporaryToStandard(builder, result, methodReference.getReturnType()); LLVM.LLVMBuildRet(builder, result); } LLVMBasicBlockRef landingPadBlock = landingPadContainer.getExistingLandingPadBlock(); if (landingPadBlock != null) { LLVM.LLVMPositionBuilderAtEnd(builder, landingPadBlock); LLVMValueRef landingPad = LLVM.LLVMBuildLandingPad(builder, getLandingPadType(), codeGenerator.getPersonalityFunction(), 0, ""); LLVM.LLVMSetCleanup(landingPad, true); LLVM.LLVMBuildResume(builder, landingPad); } LLVM.LLVMDisposeBuilder(builder); return function; } /** * Extracts the specified MethodReference on the specified callee into a function-typed value. * If the callee is an interface, or some conversion needs to be done between the MethodReference's type * and the underlying Method's type, then the function is proxied, and the proxy function is returned. * @param builder - the LLVMBuilderRef to build instructions with * @param landingPadContainer - the LandingPadContainer containing the landing pad block for exceptions to be unwound to * @param callee - the callee for the method, in a temporary type representation * @param calleeType - the current type of the callee * @param methodReference - the reference to the Method to extract * @param skipVirtualLookup - true to skip a virtual function table lookup and use the function directly, false to do a VFT lookup as normal * @param typeParameterAccessor - the TypeParameterAccessor to get the values of any TypeParameters from * @return the function extracted, in the temporary type representation of a FunctionType constructed from the MethodReference (not the underlying Method) */ public LLVMValueRef extractMethodFunction(LLVMBuilderRef builder, LandingPadContainer landingPadContainer, LLVMValueRef callee, Type calleeType, MethodReference methodReference, boolean skipVirtualLookup, TypeParameterAccessor typeParameterAccessor) { Method method = methodReference.getReferencedMember(); boolean needsProxying = false; if (!method.isStatic() && method.getContainingTypeDefinition() instanceof InterfaceDefinition) { // for interface methods, the callee is the standard representation of the interface (i.e. a tuple of the object and the interface VFT) // so in order to extract it to a function pointer (a tuple of RTTI, callee pointer, and function pointer), we need to store the interface // callee as a pointer, which can only be done by proxying the method needsProxying = true; } else { // if the return type or any of the parameter types need converting, we need to proxy the method Parameter[] parameters = method.getParameters(); Type[] referenceParameterTypes = methodReference.getParameterTypes(); for (int i = 0; i < parameters.length; ++i) { // we skip run-time checks for this conversion, because the only change is type parameters being filled in by the MethodReference, // and we know at compile-time that they are more specific in the MethodReference than in the Method's actual type if (checkRequiresConversion(referenceParameterTypes[i], parameters[i].getType(), false)) { needsProxying = true; break; } } // we skip run-time checks for this conversion, because the only change is type parameters being filled in by the MethodReference, // and we know at compile-time that they are more specific in the MethodReference than in the Method's actual type if (checkRequiresConversion(method.getReturnType(), methodReference.getReturnType(), false)) { needsProxying = true; } } if (!method.isStatic()) { if (methodReference.getContainingType() != null) { Type newCalleeType = methodReference.getContainingType(); callee = convertTemporary(builder, landingPadContainer, callee, calleeType, newCalleeType, false, typeParameterAccessor, typeParameterAccessor); calleeType = newCalleeType; } else { // there is no containing type definition, so assume this is a builtin method Type newCalleeType = ((BuiltinMethod) method).getBaseType(); // since this is a builtin method, it cannot contain type parameters from any context but the MethodReference's context // so we can convert it with the same TypeParameterAccessor as in the other case callee = convertTemporary(builder, landingPadContainer, callee, calleeType, newCalleeType, false, typeParameterAccessor, typeParameterAccessor); calleeType = newCalleeType; } } LLVMValueRef function; if (needsProxying || method.isStatic() || calleeType instanceof ObjectType || calleeType instanceof WildcardType || (calleeType instanceof NamedType && ((NamedType) calleeType).getResolvedTypeDefinition() instanceof ClassDefinition) || (calleeType instanceof NamedType && ((NamedType) calleeType).getResolvedTypeDefinition() instanceof InterfaceDefinition) || (calleeType instanceof NamedType && ((NamedType) calleeType).getResolvedTypeParameter() != null) || calleeType instanceof ArrayType) { function = codeGenerator.lookupMethodFunction(builder, landingPadContainer, callee, calleeType, methodReference, skipVirtualLookup, typeParameterAccessor); } else { function = getBaseChangeFunction(method); } LLVMValueRef realCallee; LLVMValueRef realFunction; if (needsProxying) { // find the type of the callee opaque pointer, and the things we need to extract from it LLVMTypeRef nativeCalleeType; int numRTTIBlocks = 0; if (method.isStatic()) { nativeCalleeType = getOpaquePointer(); } else { if (methodReference.getContainingType() != null) { if (method.getContainingTypeDefinition() instanceof InterfaceDefinition) { // make sure we don't accidentally use a type with wildcard type parameters embedded in it nativeCalleeType = findStandardType(new NamedType(false, false, false, method.getContainingTypeDefinition())); // interfaces need to have their type arguments' RTTI blocks passed into their functions, so we need to pass them in through the opaque pointer // here, we find out how many of them we will need to pass through Type[] typeArguments = methodReference.getContainingType().getTypeArguments(); numRTTIBlocks = typeArguments == null ? 0 : typeArguments.length; } else { nativeCalleeType = findStandardType(methodReference.getContainingType()); } } else { // the method reference does not have a containing type, so we can assume that this is a builtin method nativeCalleeType = findStandardType(((BuiltinMethod) method).getBaseType()); } } LLVMTypeRef proxiedFunctionType = LLVM.LLVMPointerType(findMethodType(method), 0); LLVMTypeRef typeArgumentMapperType = typeParameterAccessor.getTypeArgumentMapperType(); LLVMTypeRef[] opaquePointerSubTypes = new LLVMTypeRef[3 + numRTTIBlocks]; opaquePointerSubTypes[0] = nativeCalleeType; opaquePointerSubTypes[1] = proxiedFunctionType; for (int i = 0; i < numRTTIBlocks; ++i) { opaquePointerSubTypes[2 + i] = rttiHelper.getGenericRTTIType(); } opaquePointerSubTypes[2 + numRTTIBlocks] = typeArgumentMapperType; LLVMTypeRef opaquePointerType = LLVM.LLVMPointerType(LLVM.LLVMStructType(C.toNativePointerArray(opaquePointerSubTypes, false, true), opaquePointerSubTypes.length, false), 0); // allocate the opaque pointer as the real callee of this object LLVMValueRef pointer = codeGenerator.buildHeapAllocation(builder, opaquePointerType); if (!method.isStatic() && method.getContainingTypeDefinition() instanceof InterfaceDefinition) { // this is a non-static interface method, so store each of the type argument RTTI blocks inside the new piece of memory int wildcardIndex = 0; Type[] typeArguments = methodReference.getContainingType().getTypeArguments(); for (int i = 0; i < numRTTIBlocks; ++i) { LLVMValueRef rttiBlock; if (typeArguments[i] instanceof WildcardType) { // the first wildcard RTTI is at index 2 inside the callee interface (before it are the interface's VFT pointer and the object pointer) rttiBlock = LLVM.LLVMBuildExtractValue(builder, callee, 2 + wildcardIndex, ""); ++wildcardIndex; } else { rttiBlock = rttiHelper.buildRTTICreation(builder, typeArguments[i], typeParameterAccessor); } LLVMValueRef rttiBlockPointer = LLVM.LLVMBuildStructGEP(builder, pointer, 2 + i, ""); LLVM.LLVMBuildStore(builder, rttiBlock, rttiBlockPointer); } if (wildcardIndex > 0) { // there were wildcards in the interface's type, so we need to remove them from the native type of the callee before they can be stored in the opaque pointer block // to do this, we find the native type of the interface without any wildcard type arguments // (it doesn't matter what they actually are, so we just use the NamedType constructor which sets them to type parameter references) // then, we copy the VFT pointer and object pointer from our current interface value and put them into the one without wildcard type arguments LLVMValueRef newCallee = LLVM.LLVMGetUndef(findStandardType(new NamedType(false, false, false, method.getContainingTypeDefinition()))); LLVMValueRef vftPointer = LLVM.LLVMBuildExtractValue(builder, callee, 0, ""); newCallee = LLVM.LLVMBuildInsertValue(builder, newCallee, vftPointer, 0, ""); LLVMValueRef objectPointer = LLVM.LLVMBuildExtractValue(builder, callee, 1, ""); newCallee = LLVM.LLVMBuildInsertValue(builder, newCallee, objectPointer, 1, ""); callee = newCallee; } } // store the callee inside the new piece of memory LLVMValueRef calleePointer = LLVM.LLVMBuildStructGEP(builder, pointer, 0, ""); LLVM.LLVMBuildStore(builder, callee, calleePointer); // store the function pointer inside the new piece of memory LLVMValueRef functionPointer = LLVM.LLVMBuildStructGEP(builder, pointer, 1, ""); LLVM.LLVMBuildStore(builder, function, functionPointer); // store the type argument mapper inside the new piece of memory LLVMValueRef typeMapper = LLVM.LLVMBuildStructGEP(builder, pointer, 2 + numRTTIBlocks, ""); typeParameterAccessor.buildTypeArgumentMapper(typeMapper); // set the callee and the function to the proxied callee and function realCallee = LLVM.LLVMBuildBitCast(builder, pointer, getOpaquePointer(), ""); realFunction = buildMethodReferenceProxyFunction(methodReference); } else { if (method.isStatic()) { realCallee = LLVM.LLVMConstNull(getOpaquePointer()); } else { realCallee = convertTemporary(builder, landingPadContainer, callee, calleeType, new ObjectType(false, false, null), false, typeParameterAccessor, new TypeParameterAccessor(builder, rttiHelper)); realCallee = LLVM.LLVMBuildBitCast(builder, realCallee, getOpaquePointer(), ""); } realFunction = function; } FunctionType functionType = new FunctionType(false, method.isImmutable(), methodReference.getReturnType(), methodReference.getParameterTypes(), methodReference.getCheckedThrownTypes(), null); // make sure this function type doesn't reference any type parameters (or if it does, replace them with 'object') // otherwise, the RTTI would turn out wrong (due to typeParameterAccessor) and people would be able to cast // from object to a function of whatever the values of those type parameters are, // even though the function's native representation might not take whatever type those type parameters happen to be functionType = (FunctionType) stripTypeParameters(functionType); realFunction = LLVM.LLVMBuildBitCast(builder, realFunction, findRawFunctionPointerType(functionType), ""); LLVMValueRef result = LLVM.LLVMGetUndef(findStandardType(functionType)); result = LLVM.LLVMBuildInsertValue(builder, result, rttiHelper.buildRTTICreation(builder, functionType, typeParameterAccessor), 0, ""); result = LLVM.LLVMBuildInsertValue(builder, result, realCallee, 1, ""); result = LLVM.LLVMBuildInsertValue(builder, result, realFunction, 2, ""); return convertStandardToTemporary(builder, result, functionType); } /** * Builds the preamble to the LLVM argument list of a non-static interface method, which contains the callee and all of the interface's type argument RTTI blocks. * The resulting array is an argument list which begins with the preamble, and leaves enough space for the normal arguments to the function. * @param builder - the LLVMBuilderRef to build instructions with * @param typeParameterAccessor - the TypeParameterAccessor with which to look up any type parameters referenced by calleeType * @param callee - the callee of the interface, which should be of the type specified by calleeType * @param calleeType - the type of the callee of this interface * @param calleeAccessor - the TypeParameterAccessor to look up the values of any type parameters inside callee with * @param normalArgumentCount - the number of trailing spaces to leave in the argument list for normal arguments * @return the argument list created */ private LLVMValueRef[] buildInterfaceArgListPreamble(LLVMBuilderRef builder, LLVMValueRef callee, NamedType calleeType, TypeParameterAccessor calleeAccessor, int normalArgumentCount) { Type[] typeArguments = calleeType.getTypeArguments(); LLVMValueRef[] realArguments = new LLVMValueRef[1 + (typeArguments == null ? 0 : typeArguments.length) + normalArgumentCount]; // if we have any wildcard type arguments, their RTTI blocks need to be taken from the callee int wildcardIndex = 0; for (int i = 0; typeArguments != null && i < typeArguments.length; ++i) { if (typeArguments[i] instanceof WildcardType) { // the first wildcard RTTI is at index 2 (before it are the interface's VFT pointer and the object pointer) realArguments[1 + i] = LLVM.LLVMBuildExtractValue(builder, callee, 2 + wildcardIndex, ""); ++wildcardIndex; } else { realArguments[1 + i] = rttiHelper.buildRTTICreation(builder, typeArguments[i], calleeAccessor); } } if (wildcardIndex > 0) { // there were wildcards in the interface's type, so we need to remove them from the native type of the callee before performing the call // to do this, we find the native type of the interface without any wildcard type arguments // (it doesn't matter what they actually are, so we just use the NamedType constructor which sets them to type parameter references) // then, we copy the VFT pointer and object pointer from our current interface value and put them into the one without type arguments LLVMValueRef newCallee = LLVM.LLVMGetUndef(findStandardType(new NamedType(false, false, false, calleeType.getResolvedTypeDefinition()))); LLVMValueRef vftPointer = LLVM.LLVMBuildExtractValue(builder, callee, 0, ""); newCallee = LLVM.LLVMBuildInsertValue(builder, newCallee, vftPointer, 0, ""); LLVMValueRef objectPointer = LLVM.LLVMBuildExtractValue(builder, callee, 1, ""); newCallee = LLVM.LLVMBuildInsertValue(builder, newCallee, objectPointer, 1, ""); callee = newCallee; } realArguments[0] = callee; return realArguments; } /** * Builds code to call the specified MethodReference. * @param builder - the LLVMBuilderRef to build instructions with * @param landingPadContainer - the LandingPadContainer containing the landing pad block for exceptions to be unwound to * @param callee - the callee for the method, in a temporary type representation * @param calleeType - the current type of the callee * @param methodReference - the MethodReference to build the call to * @param arguments - the arguments, in temporary type representations of the types that the MethodReference (not the Method) expects * @param typeParameterAccessor - the TypeParameterAccessor to get the values of any TypeParameters in the MethodReference or the callee from * @return the result of the method call, in a temporary type representation of the type that the MethodReference (not the Method) returns */ public LLVMValueRef buildMethodCall(LLVMBuilderRef builder, LandingPadContainer landingPadContainer, LLVMValueRef callee, Type calleeType, MethodReference methodReference, LLVMValueRef[] arguments, TypeParameterAccessor typeParameterAccessor) { Method method = methodReference.getReferencedMember(); if (!method.isStatic()) { if (methodReference.getContainingType() != null) { Type newCalleeType = methodReference.getContainingType(); callee = convertTemporary(builder, landingPadContainer, callee, calleeType, newCalleeType, false, typeParameterAccessor, typeParameterAccessor); calleeType = newCalleeType; } else { // there is no containing type definition, so assume this is a builtin method Type newCalleeType = ((BuiltinMethod) method).getBaseType(); // since this is a builtin method, it cannot contain type parameters from any context but the MethodReference's context // so we can convert it with the same TypeParameterAccessor as in the other case callee = convertTemporary(builder, landingPadContainer, callee, calleeType, newCalleeType, false, typeParameterAccessor, typeParameterAccessor); calleeType = newCalleeType; } } LLVMValueRef function = codeGenerator.lookupMethodFunction(builder, landingPadContainer, callee, calleeType, methodReference, false, typeParameterAccessor); LLVMValueRef[] realArguments; int offset; if (!method.isStatic() && method.getContainingTypeDefinition() instanceof InterfaceDefinition) { // interfaces need type argument RTTI blocks to be passed in as parameters NamedType containingType = methodReference.getContainingType(); realArguments = buildInterfaceArgListPreamble(builder, callee, containingType, typeParameterAccessor, arguments.length); Type[] typeArguments = containingType.getTypeArguments(); offset = 1 + (typeArguments == null ? 0 : typeArguments.length); } else { realArguments = new LLVMValueRef[1 + arguments.length]; realArguments[0] = callee; offset = 1; } Type[] referenceParameterTypes = methodReference.getParameterTypes(); TypeParameterAccessor methodTypeAccessor = typeParameterAccessor; if (methodReference.getContainingType() != null) { if (method.isStatic()) { methodTypeAccessor = new TypeParameterAccessor(builder, rttiHelper); } else if (method.getContainingTypeDefinition() instanceof InterfaceDefinition) { methodTypeAccessor = new TypeParameterAccessor(builder, rttiHelper, callee, methodReference.getContainingType(), typeParameterAccessor); } else { methodTypeAccessor = new TypeParameterAccessor(builder, this, rttiHelper, method.getContainingTypeDefinition(), callee); } } Parameter[] parameters = method.getParameters(); for (int i = 0; i < arguments.length; ++i) { Type realParameterType = parameters[i].getType(); realArguments[offset + i] = convertTemporaryToStandard(builder, landingPadContainer, arguments[i], referenceParameterTypes[i], realParameterType, typeParameterAccessor, methodTypeAccessor); } LLVMBasicBlockRef invokeContinueBlock = LLVM.LLVMAddBasicBlock(builder, "methodInvokeContinue"); LLVMValueRef result = LLVM.LLVMBuildInvoke(builder, function, C.toNativePointerArray(realArguments, false, true), realArguments.length, invokeContinueBlock, landingPadContainer.getLandingPadBlock(), ""); LLVM.LLVMPositionBuilderAtEnd(builder, invokeContinueBlock); if (methodReference.getReturnType() instanceof VoidType) { return null; } Type resultType = method.getReturnType(); result = convertStandardToTemporary(builder, landingPadContainer, result, resultType, methodReference.getReturnType(), methodTypeAccessor, typeParameterAccessor); return result; } /** * Builds code to call the specified PropertyReference's getter. * @param builder - the LLVMBuilderRef to build instructions with * @param landingPadContainer - the LandingPadContainer containing the landing pad block for exceptions to be unwound to * @param callee - the callee for the property function, in a temporary type representation * @param calleeType - the current type of the callee * @param propertyReference - the PropertyReference to build the call to the getter of * @param typeParameterAccessor - the TypeParameterAccessor to get the values of any TypeParameters from * @return the result of the property getter call, in a temporary type representation of the type that the PropertyReference (not the Property) returns */ public LLVMValueRef buildPropertyGetterFunctionCall(LLVMBuilderRef builder, LandingPadContainer landingPadContainer, LLVMValueRef callee, Type calleeType, PropertyReference propertyReference, TypeParameterAccessor typeParameterAccessor) { Property property = propertyReference.getReferencedMember(); if (!property.isStatic()) { Type newCalleeType = propertyReference.getContainingType(); // newCalleeType is always non-null, because there is no such thing as a built-in property callee = convertTemporary(builder, landingPadContainer, callee, calleeType, newCalleeType, false, typeParameterAccessor, typeParameterAccessor); calleeType = newCalleeType; } LLVMValueRef function = codeGenerator.lookupPropertyFunction(builder, landingPadContainer, callee, calleeType, propertyReference, MemberFunctionType.PROPERTY_GETTER, typeParameterAccessor); LLVMValueRef[] realArguments; if (!property.isStatic() && property.getContainingTypeDefinition() instanceof InterfaceDefinition) { // interfaces need type argument RTTI blocks to be passed in as parameters NamedType containingType = propertyReference.getContainingType(); realArguments = buildInterfaceArgListPreamble(builder, callee, containingType, typeParameterAccessor, 0); } else { realArguments = new LLVMValueRef[1]; realArguments[0] = callee; } TypeParameterAccessor propertyTypeAccessor; if (property.isStatic()) { propertyTypeAccessor = new TypeParameterAccessor(builder, rttiHelper); } else if (property.getContainingTypeDefinition() instanceof InterfaceDefinition) { propertyTypeAccessor = new TypeParameterAccessor(builder, rttiHelper, callee, propertyReference.getContainingType(), typeParameterAccessor); } else { propertyTypeAccessor = new TypeParameterAccessor(builder, this, rttiHelper, property.getContainingTypeDefinition(), callee); } LLVMBasicBlockRef invokeContinueBlock = LLVM.LLVMAddBasicBlock(builder, "propertyGetterInvokeContinue"); LLVMValueRef result = LLVM.LLVMBuildInvoke(builder, function, C.toNativePointerArray(realArguments, false, true), realArguments.length, invokeContinueBlock, landingPadContainer.getLandingPadBlock(), ""); LLVM.LLVMPositionBuilderAtEnd(builder, invokeContinueBlock); Type resultType = property.getType(); result = convertStandardToTemporary(builder, landingPadContainer, result, resultType, propertyReference.getType(), propertyTypeAccessor, typeParameterAccessor); return result; } /** * Builds code to call the specified PropertyReference's setter or constructor. * @param builder - the LLVMBuilderRef to build instructions with * @param landingPadContainer - the LandingPadContainer containing the landing pad block for exceptions to be unwound to * @param callee - the callee for the property function, in a temporary type representation * @param calleeType - the current type of the callee * @param argument - the value to pass to the setter/constructor, in a temporary type representation * @param propertyReference - the PropertyReference to build the call to the setter/constructor of * @param functionType - the type of function to call, should be either PROPERTY_SETTER or PROPERTY_CONSTRUCTOR * @param typeParameterAccessor - the TypeParameterAccessor to get the values of any TypeParameters from */ public void buildPropertySetterConstructorFunctionCall(LLVMBuilderRef builder, LandingPadContainer landingPadContainer, LLVMValueRef callee, Type calleeType, LLVMValueRef argument, PropertyReference propertyReference, MemberFunctionType functionType, TypeParameterAccessor typeParameterAccessor) { Property property = propertyReference.getReferencedMember(); if (!property.isStatic()) { Type newCalleeType = propertyReference.getContainingType(); // newCalleeType is always non-null, because there is no such thing as a built-in property callee = convertTemporary(builder, landingPadContainer, callee, calleeType, newCalleeType, false, typeParameterAccessor, typeParameterAccessor); calleeType = newCalleeType; } LLVMValueRef function = codeGenerator.lookupPropertyFunction(builder, landingPadContainer, callee, calleeType, propertyReference, functionType, typeParameterAccessor); LLVMValueRef[] realArguments; int offset; if (!property.isStatic() && property.getContainingTypeDefinition() instanceof InterfaceDefinition) { // interfaces need type argument RTTI blocks to be passed in as parameters NamedType containingType = propertyReference.getContainingType(); realArguments = buildInterfaceArgListPreamble(builder, callee, containingType, typeParameterAccessor, 1); Type[] typeArguments = containingType.getTypeArguments(); offset = 1 + (typeArguments == null ? 0 : typeArguments.length); } else { realArguments = new LLVMValueRef[2]; realArguments[0] = callee; offset = 1; } TypeParameterAccessor propertyTypeAccessor; if (property.isStatic()) { propertyTypeAccessor = new TypeParameterAccessor(builder, rttiHelper); } else if (property.getContainingTypeDefinition() instanceof InterfaceDefinition) { propertyTypeAccessor = new TypeParameterAccessor(builder, rttiHelper, callee, propertyReference.getContainingType(), typeParameterAccessor); } else { propertyTypeAccessor = new TypeParameterAccessor(builder, this, rttiHelper, property.getContainingTypeDefinition(), callee); } // convert the argument from the PropertyReference's expected type to the Property's expected type Type argumentType = property.getType(); realArguments[offset] = convertTemporaryToStandard(builder, landingPadContainer, argument, propertyReference.getType(), argumentType, typeParameterAccessor, propertyTypeAccessor); LLVMBasicBlockRef invokeContinueBlock = LLVM.LLVMAddBasicBlock(builder, "property" + (functionType == MemberFunctionType.PROPERTY_CONSTRUCTOR ? "Constructor" : "Setter") + "InvokeContinue"); LLVM.LLVMBuildInvoke(builder, function, C.toNativePointerArray(realArguments, false, true), realArguments.length, invokeContinueBlock, landingPadContainer.getLandingPadBlock(), ""); LLVM.LLVMPositionBuilderAtEnd(builder, invokeContinueBlock); } /** * Gets a function that takes a callee of type 'object' and converts it to the base type of the specified method before calling that method. * @param method - the method to find the base change method for, cannot be an interface method * @return the base change method for the specified method */ public LLVMValueRef getBaseChangeFunction(Method method) { if (method.isStatic()) { throw new IllegalArgumentException("Cannot change the base of a static method"); } if (method.getContainingTypeDefinition() instanceof InterfaceDefinition) { throw new IllegalArgumentException("Cannot change the base of an interface method"); } String mangledName = BASE_CHANGE_FUNCTION_PREFIX + method.getMangledName(); LLVMValueRef existingFunction = LLVM.LLVMGetNamedFunction(module, mangledName); if (existingFunction != null) { return existingFunction; } Parameter[] parameters = method.getParameters(); LLVMTypeRef[] types = new LLVMTypeRef[1 + parameters.length]; ObjectType objectType = new ObjectType(false, false, null); types[0] = findTemporaryType(objectType); for (int i = 0; i < parameters.length; ++i) { types[i + 1] = findStandardType(parameters[i].getType()); } LLVMTypeRef resultType = findStandardType(method.getReturnType()); LLVMTypeRef objectFunctionType = LLVM.LLVMFunctionType(resultType, C.toNativePointerArray(types, false, true), types.length, false); LLVMValueRef objectFunction = LLVM.LLVMAddFunction(module, mangledName, objectFunctionType); LLVM.LLVMSetLinkage(objectFunction, LLVM.LLVMLinkage.LLVMLinkOnceODRLinkage); LLVM.LLVMSetVisibility(objectFunction, LLVM.LLVMVisibility.LLVMHiddenVisibility); LLVMBuilderRef builder = LLVM.LLVMCreateFunctionBuilder(objectFunction); LandingPadContainer landingPadContainer = new LandingPadContainer(builder); Type baseType; if (method.getContainingTypeDefinition() != null) { baseType = new NamedType(false, false, false, method.getContainingTypeDefinition()); } else if (method instanceof BuiltinMethod) { baseType = ((BuiltinMethod) method).getBaseType(); } else { throw new IllegalArgumentException("Method has no base type: " + method); } TypeParameterAccessor nullAccessor = new TypeParameterAccessor(builder, rttiHelper); LLVMValueRef callee = LLVM.LLVMGetParam(objectFunction, 0); // disable checks for this conversion, since (a) we know the the object contains exactly the type we are expecting, and (b) we don't have the TypeParameterAccessor to do the instanceof check with LLVMValueRef convertedBaseValue = convertTemporary(builder, landingPadContainer, callee, objectType, baseType, true, nullAccessor, nullAccessor); MethodReference methodReference = new MethodReference(method, GenericTypeSpecialiser.IDENTITY_SPECIALISER); LLVMValueRef methodFunction = codeGenerator.lookupMethodFunction(builder, landingPadContainer, convertedBaseValue, baseType, methodReference, false, null); LLVMValueRef[] arguments = new LLVMValueRef[1 + parameters.length]; arguments[0] = convertedBaseValue; for (int i = 0; i < parameters.length; ++i) { arguments[i + 1] = LLVM.LLVMGetParam(objectFunction, i + 1); } LLVMBasicBlockRef methodInvokeContinueBlock = LLVM.LLVMAddBasicBlock(builder, "methodInvokeContinue"); LLVMValueRef result = LLVM.LLVMBuildInvoke(builder, methodFunction, C.toNativePointerArray(arguments, false, true), arguments.length, methodInvokeContinueBlock, landingPadContainer.getLandingPadBlock(), ""); LLVM.LLVMPositionBuilderAtEnd(builder, methodInvokeContinueBlock); if (method.getReturnType() instanceof VoidType) { LLVM.LLVMBuildRetVoid(builder); } else { LLVM.LLVMBuildRet(builder, result); } LLVMBasicBlockRef landingPadBlock = landingPadContainer.getExistingLandingPadBlock(); if (landingPadBlock != null) { LLVM.LLVMPositionBuilderAtEnd(builder, landingPadBlock); LLVMValueRef landingPad = LLVM.LLVMBuildLandingPad(builder, getLandingPadType(), codeGenerator.getPersonalityFunction(), 0, ""); LLVM.LLVMSetCleanup(landingPad, true); LLVM.LLVMBuildResume(builder, landingPad); } LLVM.LLVMDisposeBuilder(builder); return objectFunction; } /** * Initialises the specified value as a compound definition of the specified type. * This method performs any initialisation which must happen before the constructor is called, such as zeroing fields which have default values, and setting the type parameters. * @param compoundType - the compound type to initialise the value as * @param compoundValue - the value to initialise, which is a temporary type representation of the specified CompoundDefinition */ void initialiseCompoundType(LLVMBuilderRef builder, NamedType compoundType, LLVMValueRef compoundValue, TypeParameterAccessor typeParameterAccessor) { CompoundDefinition compoundDefinition = (CompoundDefinition) compoundType.getResolvedTypeDefinition(); TypeParameter[] typeParameters = compoundDefinition.getTypeParameters(); Type[] typeArguments = compoundType.getTypeArguments(); if (typeArguments == null ? typeParameters.length > 0 : (typeArguments.length != typeParameters.length)) { throw new IllegalArgumentException("Cannot initialise a compound type without the required type arguments"); } // initialise the type parameters (this must be done during allocation, not in the constructor) for (int i = 0; typeArguments != null && i < typeArguments.length; ++i) { LLVMValueRef pointer = getTypeParameterPointer(builder, compoundValue, typeParameters[i]); LLVMValueRef rtti = rttiHelper.buildRTTICreation(builder, typeArguments[i], typeParameterAccessor); LLVM.LLVMBuildStore(builder, rtti, pointer); } // initialise all of the fields which have default values to zero/null for (MemberVariable variable : compoundDefinition.getMemberVariables()) { if (variable.getType().hasDefaultValue()) { LLVMValueRef pointer = getMemberPointer(builder, compoundValue, variable); LLVM.LLVMBuildStore(builder, LLVM.LLVMConstNull(findStandardType(variable.getType())), pointer); } } } /** * Builds a conversion from one function type to another, through a proxy function. * @param builder - the LLVMBuilderRef to build the conversion with * @param value - the function to convert, in a temporary type representation * @param fromType - the function type to convert from * @param toType - the function type to convert to * @param fromAccessor - the TypeParameterAccessor containing the values of all TypeParameters that may exist in fromType * @param toAccessor - the TypeParameterAccessor containing the values of all TypeParameters that may exist in toType * @return the proxied function, in a temporary type representation */ private LLVMValueRef buildFunctionProxyConversion(LLVMBuilderRef builder, LLVMValueRef value, FunctionType fromType, FunctionType toType, TypeParameterAccessor fromAccessor, TypeParameterAccessor toAccessor) { // make sure this function type's RTTI doesn't reference any type parameters // otherwise, the RTTI would turn out wrong (due to typeParameterAccessor) and people would be able to cast // from object to a function of whatever the values of those type parameters are, // even though the function's native representation might not take whatever type those type parameters happen to be LLVMValueRef rtti = rttiHelper.buildRTTICreation(builder, stripTypeParameters(toType), toAccessor); TypeDefinition fromMapperTypeDefinition = fromAccessor.getTypeDefinition(); TypeDefinition toMapperTypeDefinition = toAccessor.getTypeDefinition(); LLVMValueRef proxyFunction = getProxyFunction(fromType, toType, fromMapperTypeDefinition, toMapperTypeDefinition); LLVMTypeRef fromNativeType = findStandardType(fromType); LLVMTypeRef fromTypeMapperType = rttiHelper.getTypeArgumentMapperType(fromMapperTypeDefinition == null ? 0 : fromMapperTypeDefinition.getTypeParameters().length); LLVMTypeRef toTypeMapperType = rttiHelper.getTypeArgumentMapperType(toMapperTypeDefinition == null ? 0 : toMapperTypeDefinition.getTypeParameters().length); LLVMTypeRef[] opaquePointerSubTypes = new LLVMTypeRef[] {fromNativeType, fromTypeMapperType, toTypeMapperType}; LLVMTypeRef allocationType = LLVM.LLVMStructType(C.toNativePointerArray(opaquePointerSubTypes, false, true), opaquePointerSubTypes.length, false); LLVMTypeRef allocationPtrType = LLVM.LLVMPointerType(allocationType, 0); LLVMValueRef pointer = codeGenerator.buildHeapAllocation(builder, allocationPtrType); LLVMValueRef functionValuePtr = LLVM.LLVMBuildStructGEP(builder, pointer, 0, ""); LLVMValueRef functionValue = convertTemporaryToStandard(builder, value, fromType); LLVM.LLVMBuildStore(builder, functionValue, functionValuePtr); LLVMValueRef fromTypeMapperPtr = LLVM.LLVMBuildStructGEP(builder, pointer, 1, ""); fromAccessor.buildTypeArgumentMapper(fromTypeMapperPtr); LLVMValueRef toTypeMapperPtr = LLVM.LLVMBuildStructGEP(builder, pointer, 2, ""); toAccessor.buildTypeArgumentMapper(toTypeMapperPtr); LLVMValueRef callee = LLVM.LLVMBuildBitCast(builder, pointer, getOpaquePointer(), ""); LLVMValueRef result = LLVM.LLVMGetUndef(findTemporaryType(toType)); result = LLVM.LLVMBuildInsertValue(builder, result, rtti, 0, ""); result = LLVM.LLVMBuildInsertValue(builder, result, callee, 1, ""); result = LLVM.LLVMBuildInsertValue(builder, result, proxyFunction, 2, ""); return result; } /** * Builds a proxy function that allows one function type to be converted into another. * @param fromType - the type of function that the proxy function will call down into * @param toType - the type of function that the proxy function will be * @param fromMapperTypeDefinition - the TypeDefinition that the type mapper for the from type is based on * @param toMapperTypeDefinition - the TypeDefinition that the type mapper for the to type is based on * @return the proxy function created */ private LLVMValueRef getProxyFunction(FunctionType fromType, FunctionType toType, TypeDefinition fromMapperTypeDefinition, TypeDefinition toMapperTypeDefinition) { // mangled name and type mappers: // because the ABI of this function depends on which type mappers are used for it, regardless of whether or not they are used, we must include the size of each of the type mappers in the mangled name // otherwise we could try to generate a similar proxy function later on, and find one with the same mangled name that has a slightly different ABI, which would cause things to break int fromMapperNumTypeParams = fromMapperTypeDefinition == null ? 0 : fromMapperTypeDefinition.getTypeParameters().length; int toMapperNumTypeParams = toMapperTypeDefinition == null ? 0 : toMapperTypeDefinition.getTypeParameters().length; String mangledName = PROXY_FUNCTION_PREFIX + typeDefinition.getQualifiedName().getMangledName() + "_" + fromType.getMangledName() + "_" + toType.getMangledName() + "_" + fromMapperNumTypeParams + "_" + toMapperNumTypeParams; LLVMValueRef existingFunction = LLVM.LLVMGetNamedFunction(module, mangledName); if (existingFunction != null) { return existingFunction; } Type[] fromParamTypes = fromType.getParameterTypes(); Type[] toParamTypes = toType.getParameterTypes(); if (fromParamTypes.length > toParamTypes.length) { throw new IllegalArgumentException("Cannot convert from " + fromType + " to " + toType + " - not enough parameter types"); } if ((fromType.getReturnType() instanceof VoidType) && !(toType.getReturnType() instanceof VoidType)) { throw new IllegalArgumentException("Cannot convert from " + fromType + " to " + toType + " - return types conflict"); } LLVMTypeRef[] parameterTypes = new LLVMTypeRef[1 + toParamTypes.length]; parameterTypes[0] = getOpaquePointer(); for (int i = 0; i < toParamTypes.length; ++i) { parameterTypes[1 + i] = findStandardType(toParamTypes[i]); } LLVMTypeRef returnType = findStandardType(toType.getReturnType()); LLVMTypeRef proxyFunctionType = LLVM.LLVMFunctionType(returnType, C.toNativePointerArray(parameterTypes, false, true), parameterTypes.length, false); LLVMValueRef proxyFunction = LLVM.LLVMAddFunction(module, mangledName, proxyFunctionType); LLVM.LLVMSetLinkage(proxyFunction, LLVM.LLVMLinkage.LLVMPrivateLinkage); LLVM.LLVMSetVisibility(proxyFunction, LLVM.LLVMVisibility.LLVMHiddenVisibility); LLVMBuilderRef builder = LLVM.LLVMCreateFunctionBuilder(proxyFunction); LandingPadContainer landingPadContainer = new LandingPadContainer(builder); LLVMTypeRef fromNativeType = findStandardType(fromType); LLVMTypeRef fromTypeMapperType = rttiHelper.getTypeArgumentMapperType(fromMapperNumTypeParams); LLVMTypeRef toTypeMapperType = rttiHelper.getTypeArgumentMapperType(toMapperNumTypeParams); LLVMTypeRef[] subTypes = new LLVMTypeRef[] {fromNativeType, fromTypeMapperType, toTypeMapperType}; LLVMTypeRef opaqueValueType = LLVM.LLVMStructType(C.toNativePointerArray(subTypes, false, true), subTypes.length, false); LLVMTypeRef opaquePointerType = LLVM.LLVMPointerType(opaqueValueType, 0); LLVMValueRef opaquePointer = LLVM.LLVMGetParam(proxyFunction, 0); LLVMValueRef calleeValue = LLVM.LLVMBuildBitCast(builder, opaquePointer, opaquePointerType, ""); LLVMValueRef baseFunctionStructurePtr = LLVM.LLVMBuildStructGEP(builder, calleeValue, 0, ""); LLVMValueRef fromTypeMapper = LLVM.LLVMBuildStructGEP(builder, calleeValue, 1, ""); LLVMValueRef toTypeMapper = LLVM.LLVMBuildStructGEP(builder, calleeValue, 2, ""); TypeParameterAccessor fromAccessor = new TypeParameterAccessor(builder, rttiHelper, fromMapperTypeDefinition, fromTypeMapper); TypeParameterAccessor toAccessor = new TypeParameterAccessor(builder, rttiHelper, toMapperTypeDefinition, toTypeMapper); LLVMValueRef[] baseFunctionParameters = new LLVMValueRef[1 + fromParamTypes.length]; for (int i = 0; i < fromParamTypes.length; ++i) { LLVMValueRef parameter = LLVM.LLVMGetParam(proxyFunction, 1 + i); if (toParamTypes[i].isRuntimeEquivalent(fromParamTypes[i])) { baseFunctionParameters[i + 1] = parameter; } else { LLVMValueRef converted = convertStandardToTemporary(builder, landingPadContainer, parameter, toParamTypes[i], fromParamTypes[i], toAccessor, fromAccessor); converted = convertTemporaryToStandard(builder, converted, fromParamTypes[i]); baseFunctionParameters[i + 1] = converted; } } LLVMValueRef baseFunctionCalleePtr = LLVM.LLVMBuildStructGEP(builder, baseFunctionStructurePtr, 1, ""); LLVMValueRef baseFunctionCallee = LLVM.LLVMBuildLoad(builder, baseFunctionCalleePtr, ""); baseFunctionParameters[0] = baseFunctionCallee; LLVMValueRef baseFunctionPtr = LLVM.LLVMBuildStructGEP(builder, baseFunctionStructurePtr, 2, ""); LLVMValueRef baseFunction = LLVM.LLVMBuildLoad(builder, baseFunctionPtr, ""); LLVMBasicBlockRef invokeContinueBlock = LLVM.LLVMAddBasicBlock(builder, "invokeContinue"); LLVMValueRef result = LLVM.LLVMBuildInvoke(builder, baseFunction, C.toNativePointerArray(baseFunctionParameters, false, true), baseFunctionParameters.length, invokeContinueBlock, landingPadContainer.getLandingPadBlock(), ""); LLVM.LLVMPositionBuilderAtEnd(builder, invokeContinueBlock); if (toType.getReturnType() instanceof VoidType) { LLVM.LLVMBuildRetVoid(builder); } else { LLVMValueRef convertedResult = convertStandardToTemporary(builder, landingPadContainer, result, fromType.getReturnType(), toType.getReturnType(), fromAccessor, toAccessor); convertedResult = convertTemporaryToStandard(builder, convertedResult, toType.getReturnType()); LLVM.LLVMBuildRet(builder, convertedResult); } LLVMBasicBlockRef landingPadBlock = landingPadContainer.getExistingLandingPadBlock(); if (landingPadBlock != null) { LLVM.LLVMPositionBuilderAtEnd(builder, landingPadBlock); LLVMValueRef landingPad = LLVM.LLVMBuildLandingPad(builder, getLandingPadType(), codeGenerator.getPersonalityFunction(), 0, ""); LLVM.LLVMSetCleanup(landingPad, true); LLVM.LLVMBuildResume(builder, landingPad); } LLVM.LLVMDisposeBuilder(builder); return proxyFunction; } /** * Builds a conversion from one array type to another, through a proxy array. * @param builder - the LLVMBuilderRef to build the conversion with * @param value - the array to convert, in a temporary type representation * @param fromType - the array type to convert from * @param toType - the array type to convert to - any type parameters inside this type are considered to just be objects (i.e. they are stripped out before use) * @param fromAccessor - the TypeParameterAccessor containing the values of all TypeParameters that may exist in fromType * @param toAccessor - the TypeParameterAccessor containing the values of all TypeParameters that may exist in toType * @return the proxied array, in a temporary type representation */ private LLVMValueRef buildProxyArrayConversion(LLVMBuilderRef builder, LLVMValueRef value, ArrayType fromType, ArrayType toType, TypeParameterAccessor fromAccessor, TypeParameterAccessor toAccessor) { // we need to create the array as if any type parameters inside it are actually objects, so strip them toType = (ArrayType) stripTypeParameters(toType); // find the type of the proxy array LLVMTypeRef llvmArrayType = findStandardType(toType); LLVMTypeRef rttiType = rttiHelper.getGenericRTTIType(); LLVMTypeRef vftPointerType = LLVM.LLVMPointerType(virtualFunctionHandler.getObjectVFTType(), 0); LLVMTypeRef lengthType = LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()); LLVMTypeRef[] getFunctionParamTypes = new LLVMTypeRef[] {llvmArrayType, lengthType}; LLVMTypeRef getFunctionType = LLVM.LLVMFunctionType(findTemporaryType(toType.getBaseType()), C.toNativePointerArray(getFunctionParamTypes, false, true), getFunctionParamTypes.length, false); LLVMTypeRef[] setFunctionParamTypes = new LLVMTypeRef[] {llvmArrayType, lengthType, findStandardType(toType.getBaseType())}; LLVMTypeRef setFunctionType = LLVM.LLVMFunctionType(LLVM.LLVMVoidType(), C.toNativePointerArray(setFunctionParamTypes, false, true), setFunctionParamTypes.length, false); LLVMTypeRef baseArrayType = findStandardType(fromType); TypeDefinition fromMapperTypeDefinition = fromAccessor.getTypeDefinition(); TypeDefinition toMapperTypeDefinition = toAccessor.getTypeDefinition(); LLVMTypeRef fromTypeMapperType = rttiHelper.getTypeArgumentMapperType(fromMapperTypeDefinition == null ? 0 : fromMapperTypeDefinition.getTypeParameters().length); LLVMTypeRef toTypeMapperType = rttiHelper.getTypeArgumentMapperType(toMapperTypeDefinition == null ? 0 : toMapperTypeDefinition.getTypeParameters().length); LLVMTypeRef[] subTypes = new LLVMTypeRef[] {rttiType, vftPointerType, lengthType, LLVM.LLVMPointerType(getFunctionType, 0), LLVM.LLVMPointerType(setFunctionType, 0), baseArrayType, fromTypeMapperType, toTypeMapperType}; LLVMTypeRef proxyArrayType = LLVM.LLVMStructType(C.toNativePointerArray(subTypes, false, true), subTypes.length, false); LLVMTypeRef proxyArrayPointerType = LLVM.LLVMPointerType(proxyArrayType, 0); // allocate memory for the proxy array LLVMValueRef pointer = codeGenerator.buildHeapAllocation(builder, proxyArrayPointerType); // store the RTTI LLVMValueRef rtti = rttiHelper.buildRTTICreation(builder, toType, toAccessor); LLVMValueRef rttiPtr = LLVM.LLVMBuildStructGEP(builder, pointer, 0, ""); LLVM.LLVMBuildStore(builder, rtti, rttiPtr); // store the VFT LLVMValueRef vft = virtualFunctionHandler.getBaseChangeObjectVFT(toType); LLVMValueRef vftPtr = LLVM.LLVMBuildStructGEP(builder, pointer, 1, ""); LLVM.LLVMBuildStore(builder, vft, vftPtr); // extract the length from the underlying array, and store it here LLVMValueRef baseLengthPtr = getArrayLengthPointer(builder, value); LLVMValueRef length = LLVM.LLVMBuildLoad(builder, baseLengthPtr, ""); LLVMValueRef lengthPtr = LLVM.LLVMBuildStructGEP(builder, pointer, 2, ""); LLVM.LLVMBuildStore(builder, length, lengthPtr); // store the getter and setter functions LLVMValueRef getterFunction = getProxyArrayGetterFunction(fromType, toType, fromMapperTypeDefinition, toMapperTypeDefinition); LLVMValueRef getterFunctionPtr = LLVM.LLVMBuildStructGEP(builder, pointer, 3, ""); LLVM.LLVMBuildStore(builder, getterFunction, getterFunctionPtr); LLVMValueRef setterFunction = getProxyArraySetterFunction(fromType, toType, fromMapperTypeDefinition, toMapperTypeDefinition); LLVMValueRef setterFunctionPtr = LLVM.LLVMBuildStructGEP(builder, pointer, 4, ""); LLVM.LLVMBuildStore(builder, setterFunction, setterFunctionPtr); // store the base array LLVMValueRef baseArrayPtr = LLVM.LLVMBuildStructGEP(builder, pointer, 5, ""); LLVM.LLVMBuildStore(builder, value, baseArrayPtr); // store the type mappers LLVMValueRef fromTypeMapper = LLVM.LLVMBuildStructGEP(builder, pointer, 6, ""); fromAccessor.buildTypeArgumentMapper(fromTypeMapper); LLVMValueRef toTypeMapper = LLVM.LLVMBuildStructGEP(builder, pointer, 7, ""); toAccessor.buildTypeArgumentMapper(toTypeMapper); // bitcast the result to the normal array type and return it return LLVM.LLVMBuildBitCast(builder, pointer, findTemporaryType(toType), ""); } /** * Builds a getter function for a proxy array, which along with a setter function allows one array type to be converted into another. * @param fromType - the type of array that this function will call the getter of * @param toType - the type of array that this function will be for * @param fromMapperTypeDefinition - the TypeDefinition that the type mapper for the from type is based on * @param toMapperTypeDefinition - the TypeDefinition that the type mapper for the to type is based on * @return the proxy getter function created */ private LLVMValueRef getProxyArrayGetterFunction(ArrayType fromType, ArrayType toType, TypeDefinition fromMapperTypeDefinition, TypeDefinition toMapperTypeDefinition) { // mangled name and type mappers: // because the ABI of this function depends on which type mappers are used for it, regardless of whether or not they are used, we must include the size of each of the type mappers in the mangled name // otherwise we could try to generate a similar proxy function later on, and find one with the same mangled name that has a slightly different ABI, which would cause things to break int fromMapperNumTypeParams = fromMapperTypeDefinition == null ? 0 : fromMapperTypeDefinition.getTypeParameters().length; int toMapperNumTypeParams = toMapperTypeDefinition == null ? 0 : toMapperTypeDefinition.getTypeParameters().length; String mangledName = PROXY_ARRAY_GETTER_FUNCTION_PREFIX + typeDefinition.getQualifiedName().getMangledName() + "_" + fromType.getMangledName() + "_" + toType.getMangledName() + "_" + fromMapperNumTypeParams + "_" + toMapperNumTypeParams; LLVMValueRef existingFunction = LLVM.LLVMGetNamedFunction(module, mangledName); if (existingFunction != null) { return existingFunction; } LLVMTypeRef toArrayNativeType = findTemporaryType(toType); LLVMTypeRef indexType = LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()); LLVMTypeRef[] getterFunctionParamTypes = new LLVMTypeRef[] {toArrayNativeType, indexType}; LLVMTypeRef getterFunctionType = LLVM.LLVMFunctionType(findTemporaryType(toType.getBaseType()), C.toNativePointerArray(getterFunctionParamTypes, false, true), getterFunctionParamTypes.length, false); LLVMValueRef proxyFunction = LLVM.LLVMAddFunction(module, mangledName, getterFunctionType); LLVM.LLVMSetLinkage(proxyFunction, LLVM.LLVMLinkage.LLVMPrivateLinkage); LLVM.LLVMSetVisibility(proxyFunction, LLVM.LLVMVisibility.LLVMHiddenVisibility); LLVMBuilderRef builder = LLVM.LLVMCreateFunctionBuilder(proxyFunction); LandingPadContainer landingPadContainer = new LandingPadContainer(builder); LLVMValueRef array = LLVM.LLVMGetParam(proxyFunction, 0); LLVMValueRef index = LLVM.LLVMGetParam(proxyFunction, 1); // find the real type of the proxy array LLVMTypeRef llvmArrayType = findStandardType(toType); LLVMTypeRef rttiType = rttiHelper.getGenericRTTIType(); LLVMTypeRef vftPointerType = LLVM.LLVMPointerType(virtualFunctionHandler.getObjectVFTType(), 0); LLVMTypeRef lengthType = LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()); LLVMTypeRef[] getFunctionParamTypes = new LLVMTypeRef[] {llvmArrayType, lengthType}; LLVMTypeRef getFunctionType = LLVM.LLVMFunctionType(findTemporaryType(toType.getBaseType()), C.toNativePointerArray(getFunctionParamTypes, false, true), getFunctionParamTypes.length, false); LLVMTypeRef[] setFunctionParamTypes = new LLVMTypeRef[] {llvmArrayType, lengthType, findStandardType(toType.getBaseType())}; LLVMTypeRef setFunctionType = LLVM.LLVMFunctionType(LLVM.LLVMVoidType(), C.toNativePointerArray(setFunctionParamTypes, false, true), setFunctionParamTypes.length, false); LLVMTypeRef baseArrayType = findStandardType(fromType); LLVMTypeRef fromTypeMapperType = rttiHelper.getTypeArgumentMapperType(fromMapperNumTypeParams); LLVMTypeRef toTypeMapperType = rttiHelper.getTypeArgumentMapperType(toMapperNumTypeParams); LLVMTypeRef[] realArraySubTypes = new LLVMTypeRef[] {rttiType, vftPointerType, lengthType, LLVM.LLVMPointerType(getFunctionType, 0), LLVM.LLVMPointerType(setFunctionType, 0), baseArrayType, fromTypeMapperType, toTypeMapperType}; LLVMTypeRef realArrayType = LLVM.LLVMPointerType(LLVM.LLVMStructType(C.toNativePointerArray(realArraySubTypes, false, true), realArraySubTypes.length, false), 0); array = LLVM.LLVMBuildBitCast(builder, array, realArrayType, ""); // extract the required values from the specialised proxy array LLVMValueRef baseArrayPtr = LLVM.LLVMBuildStructGEP(builder, array, 5, ""); LLVMValueRef baseArray = LLVM.LLVMBuildLoad(builder, baseArrayPtr, ""); LLVMValueRef fromTypeMapper = LLVM.LLVMBuildStructGEP(builder, array, 6, ""); LLVMValueRef toTypeMapper = LLVM.LLVMBuildStructGEP(builder, array, 7, ""); TypeParameterAccessor fromAccessor = new TypeParameterAccessor(builder, rttiHelper, fromMapperTypeDefinition, fromTypeMapper); TypeParameterAccessor toAccessor = new TypeParameterAccessor(builder, rttiHelper, toMapperTypeDefinition, toTypeMapper); // call the base array's getter LLVMValueRef retrievedElement = buildRetrieveArrayElement(builder, landingPadContainer, baseArray, index); // convert the element to the base type of toType LLVMValueRef convertedElement = convertTemporary(builder, landingPadContainer, retrievedElement, fromType.getBaseType(), toType.getBaseType(), false, fromAccessor, toAccessor); // return the converted value LLVM.LLVMBuildRet(builder, convertedElement); LLVMBasicBlockRef landingPadBlock = landingPadContainer.getExistingLandingPadBlock(); if (landingPadBlock != null) { LLVM.LLVMPositionBuilderAtEnd(builder, landingPadBlock); LLVMValueRef landingPad = LLVM.LLVMBuildLandingPad(builder, getLandingPadType(), codeGenerator.getPersonalityFunction(), 0, ""); LLVM.LLVMSetCleanup(landingPad, true); LLVM.LLVMBuildResume(builder, landingPad); } LLVM.LLVMDisposeBuilder(builder); return proxyFunction; } /** * Builds a setter function for a proxy array, which along with a getter function allows one array type to be converted into another. * @param fromType - the type of array that this function will call the setter of * @param toType - the type of array that this function will be for * @param fromMapperTypeDefinition - the TypeDefinition that the type mapper for the from type is based on * @param toMapperTypeDefinition - the TypeDefinition that the type mapper for the to type is based on * @return the proxy setter function created */ private LLVMValueRef getProxyArraySetterFunction(ArrayType fromType, ArrayType toType, TypeDefinition fromMapperTypeDefinition, TypeDefinition toMapperTypeDefinition) { // mangled name and type mappers: // because the ABI of this function depends on which type mappers are used for it, regardless of whether or not they are used, we must include the size of each of the type mappers in the mangled name // otherwise we could try to generate a similar proxy function later on, and find one with the same mangled name that has a slightly different ABI, which would cause things to break int fromMapperNumTypeParams = fromMapperTypeDefinition == null ? 0 : fromMapperTypeDefinition.getTypeParameters().length; int toMapperNumTypeParams = toMapperTypeDefinition == null ? 0 : toMapperTypeDefinition.getTypeParameters().length; String mangledName = PROXY_ARRAY_SETTER_FUNCTION_PREFIX + typeDefinition.getQualifiedName().getMangledName() + "_" + fromType.getMangledName() + "_" + toType.getMangledName() + "_" + fromMapperNumTypeParams + "_" + toMapperNumTypeParams; LLVMValueRef existingFunction = LLVM.LLVMGetNamedFunction(module, mangledName); if (existingFunction != null) { return existingFunction; } LLVMTypeRef toArrayNativeType = findTemporaryType(toType); LLVMTypeRef indexType = LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()); LLVMTypeRef[] setterFunctionParamTypes = new LLVMTypeRef[] {toArrayNativeType, indexType, findStandardType(toType.getBaseType())}; LLVMTypeRef setterFunctionType = LLVM.LLVMFunctionType(LLVM.LLVMVoidType(), C.toNativePointerArray(setterFunctionParamTypes, false, true), setterFunctionParamTypes.length, false); LLVMValueRef proxyFunction = LLVM.LLVMAddFunction(module, mangledName, setterFunctionType); LLVM.LLVMSetLinkage(proxyFunction, LLVM.LLVMLinkage.LLVMPrivateLinkage); LLVM.LLVMSetVisibility(proxyFunction, LLVM.LLVMVisibility.LLVMHiddenVisibility); LLVMBuilderRef builder = LLVM.LLVMCreateFunctionBuilder(proxyFunction); LandingPadContainer landingPadContainer = new LandingPadContainer(builder); LLVMValueRef array = LLVM.LLVMGetParam(proxyFunction, 0); LLVMValueRef index = LLVM.LLVMGetParam(proxyFunction, 1); LLVMValueRef value = LLVM.LLVMGetParam(proxyFunction, 2); // find the real type of the proxy array LLVMTypeRef llvmArrayType = findStandardType(toType); LLVMTypeRef rttiType = rttiHelper.getGenericRTTIType(); LLVMTypeRef vftPointerType = LLVM.LLVMPointerType(virtualFunctionHandler.getObjectVFTType(), 0); LLVMTypeRef lengthType = LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()); LLVMTypeRef[] getFunctionParamTypes = new LLVMTypeRef[] {llvmArrayType, lengthType}; LLVMTypeRef getFunctionType = LLVM.LLVMFunctionType(findTemporaryType(toType.getBaseType()), C.toNativePointerArray(getFunctionParamTypes, false, true), getFunctionParamTypes.length, false); LLVMTypeRef[] setFunctionParamTypes = new LLVMTypeRef[] {llvmArrayType, lengthType, findStandardType(toType.getBaseType())}; LLVMTypeRef setFunctionType = LLVM.LLVMFunctionType(LLVM.LLVMVoidType(), C.toNativePointerArray(setFunctionParamTypes, false, true), setFunctionParamTypes.length, false); LLVMTypeRef baseArrayType = findStandardType(fromType); LLVMTypeRef fromTypeMapperType = rttiHelper.getTypeArgumentMapperType(fromMapperNumTypeParams); LLVMTypeRef toTypeMapperType = rttiHelper.getTypeArgumentMapperType(toMapperNumTypeParams); LLVMTypeRef[] realArraySubTypes = new LLVMTypeRef[] {rttiType, vftPointerType, lengthType, LLVM.LLVMPointerType(getFunctionType, 0), LLVM.LLVMPointerType(setFunctionType, 0), baseArrayType, fromTypeMapperType, toTypeMapperType}; LLVMTypeRef realArrayType = LLVM.LLVMPointerType(LLVM.LLVMStructType(C.toNativePointerArray(realArraySubTypes, false, true), realArraySubTypes.length, false), 0); array = LLVM.LLVMBuildBitCast(builder, array, realArrayType, ""); // extract the required values from the specialised proxy array LLVMValueRef baseArrayPtr = LLVM.LLVMBuildStructGEP(builder, array, 5, ""); LLVMValueRef baseArray = LLVM.LLVMBuildLoad(builder, baseArrayPtr, ""); LLVMValueRef fromTypeMapper = LLVM.LLVMBuildStructGEP(builder, array, 6, ""); LLVMValueRef toTypeMapper = LLVM.LLVMBuildStructGEP(builder, array, 7, ""); TypeParameterAccessor fromAccessor = new TypeParameterAccessor(builder, rttiHelper, fromMapperTypeDefinition, fromTypeMapper); TypeParameterAccessor toAccessor = new TypeParameterAccessor(builder, rttiHelper, toMapperTypeDefinition, toTypeMapper); // convert the value to the base array's type LLVMValueRef convertedValue = convertStandardToTemporary(builder, landingPadContainer, value, toType.getBaseType(), fromType.getBaseType(), toAccessor, fromAccessor); convertedValue = convertTemporaryToStandard(builder, convertedValue, fromType.getBaseType()); // call the base array's setter buildStoreArrayElement(builder, landingPadContainer, baseArray, index, convertedValue); LLVM.LLVMBuildRetVoid(builder); LLVMBasicBlockRef landingPadBlock = landingPadContainer.getExistingLandingPadBlock(); if (landingPadBlock != null) { LLVM.LLVMPositionBuilderAtEnd(builder, landingPadBlock); LLVMValueRef landingPad = LLVM.LLVMBuildLandingPad(builder, getLandingPadType(), codeGenerator.getPersonalityFunction(), 0, ""); LLVM.LLVMSetCleanup(landingPad, true); LLVM.LLVMBuildResume(builder, landingPad); } LLVM.LLVMDisposeBuilder(builder); return proxyFunction; } /** * Gets the non-proxied array getter function for the specified ArrayType. * @param arrayType - the type of array to get the getter function for * @return the getter function for the specified array type */ public LLVMValueRef getArrayGetterFunction(ArrayType arrayType) { String mangledName = ARRAY_GETTER_FUNCTION_PREFIX + arrayType.getMangledName(); LLVMValueRef existingFunction = LLVM.LLVMGetNamedFunction(module, mangledName); if (existingFunction != null) { return existingFunction; } LLVMTypeRef llvmArrayType = findTemporaryType(arrayType); LLVMTypeRef indexType = LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()); LLVMTypeRef[] getterFunctionParamTypes = new LLVMTypeRef[] {llvmArrayType, indexType}; LLVMTypeRef getterFunctionType = LLVM.LLVMFunctionType(findTemporaryType(arrayType.getBaseType()), C.toNativePointerArray(getterFunctionParamTypes, false, true), getterFunctionParamTypes.length, false); LLVMValueRef function = LLVM.LLVMAddFunction(module, mangledName, getterFunctionType); LLVM.LLVMSetLinkage(function, LLVM.LLVMLinkage.LLVMLinkOnceODRLinkage); LLVM.LLVMSetVisibility(function, LLVM.LLVMVisibility.LLVMHiddenVisibility); LLVMBuilderRef builder = LLVM.LLVMCreateFunctionBuilder(function); LandingPadContainer landingPadContainer = new LandingPadContainer(builder); LLVMValueRef array = LLVM.LLVMGetParam(function, 0); LLVMValueRef index = LLVM.LLVMGetParam(function, 1); LLVMTypeRef realArrayType = LLVM.LLVMPointerType(findNonProxiedArrayStructureType(arrayType, 0), 0); array = LLVM.LLVMBuildBitCast(builder, array, realArrayType, ""); // check that the array index is in range LLVMValueRef lengthPointer = LLVM.LLVMBuildStructGEP(builder, array, 2, ""); LLVMValueRef length = LLVM.LLVMBuildLoad(builder, lengthPointer, ""); LLVMValueRef isInRange = LLVM.LLVMBuildICmp(builder, LLVM.LLVMIntPredicate.LLVMIntULT, index, length, ""); LLVMBasicBlockRef notInRangeBlock = LLVM.LLVMAddBasicBlock(builder, "notInRange"); LLVMBasicBlockRef inRangeBlock = LLVM.LLVMAddBasicBlock(builder, "inRange"); LLVM.LLVMBuildCondBr(builder, isInRange, inRangeBlock, notInRangeBlock); LLVM.LLVMPositionBuilderAtEnd(builder, inRangeBlock); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 0, false), LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 5, false), index}; LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(indices, false, true), indices.length, ""); LLVMValueRef element = convertStandardPointerToTemporary(builder, elementPointer, arrayType.getBaseType()); LLVM.LLVMBuildRet(builder, element); LLVM.LLVMPositionBuilderAtEnd(builder, notInRangeBlock); buildThrowIndexError(builder, landingPadContainer, index, length); LLVMBasicBlockRef landingPadBlock = landingPadContainer.getExistingLandingPadBlock(); if (landingPadBlock != null) { LLVM.LLVMPositionBuilderAtEnd(builder, landingPadBlock); LLVMValueRef landingPad = LLVM.LLVMBuildLandingPad(builder, getLandingPadType(), codeGenerator.getPersonalityFunction(), 0, ""); LLVM.LLVMSetCleanup(landingPad, true); LLVM.LLVMBuildResume(builder, landingPad); } LLVM.LLVMDisposeBuilder(builder); return function; } /** * Gets the non-proxied array setter function for the specified ArrayType. * @param arrayType - the type of array to get the setter function for * @return the setter function for the specified array type */ public LLVMValueRef getArraySetterFunction(ArrayType arrayType) { String mangledName = ARRAY_SETTER_FUNCTION_PREFIX + arrayType.getMangledName(); LLVMValueRef existingFunction = LLVM.LLVMGetNamedFunction(module, mangledName); if (existingFunction != null) { return existingFunction; } LLVMTypeRef llvmArrayType = findTemporaryType(arrayType); LLVMTypeRef indexType = LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()); LLVMTypeRef[] setterFunctionParamTypes = new LLVMTypeRef[] {llvmArrayType, indexType, findStandardType(arrayType.getBaseType())}; LLVMTypeRef setterFunctionType = LLVM.LLVMFunctionType(LLVM.LLVMVoidType(), C.toNativePointerArray(setterFunctionParamTypes, false, true), setterFunctionParamTypes.length, false); LLVMValueRef function = LLVM.LLVMAddFunction(module, mangledName, setterFunctionType); LLVM.LLVMSetLinkage(function, LLVM.LLVMLinkage.LLVMLinkOnceODRLinkage); LLVM.LLVMSetVisibility(function, LLVM.LLVMVisibility.LLVMHiddenVisibility); LLVMBuilderRef builder = LLVM.LLVMCreateFunctionBuilder(function); LandingPadContainer landingPadContainer = new LandingPadContainer(builder); LLVMValueRef array = LLVM.LLVMGetParam(function, 0); LLVMValueRef index = LLVM.LLVMGetParam(function, 1); LLVMValueRef value = LLVM.LLVMGetParam(function, 2); LLVMTypeRef realArrayType = LLVM.LLVMPointerType(findNonProxiedArrayStructureType(arrayType, 0), 0); array = LLVM.LLVMBuildBitCast(builder, array, realArrayType, ""); // check that the array index is in range LLVMValueRef lengthPointer = LLVM.LLVMBuildStructGEP(builder, array, 2, ""); LLVMValueRef length = LLVM.LLVMBuildLoad(builder, lengthPointer, ""); LLVMValueRef isInRange = LLVM.LLVMBuildICmp(builder, LLVM.LLVMIntPredicate.LLVMIntULT, index, length, ""); LLVMBasicBlockRef notInRangeBlock = LLVM.LLVMAddBasicBlock(builder, "notInRange"); LLVMBasicBlockRef inRangeBlock = LLVM.LLVMAddBasicBlock(builder, "inRange"); LLVM.LLVMBuildCondBr(builder, isInRange, inRangeBlock, notInRangeBlock); LLVM.LLVMPositionBuilderAtEnd(builder, inRangeBlock); LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 0, false), LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 5, false), index}; LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(indices, false, true), indices.length, ""); LLVM.LLVMBuildStore(builder, value, elementPointer); LLVM.LLVMBuildRetVoid(builder); LLVM.LLVMPositionBuilderAtEnd(builder, notInRangeBlock); buildThrowIndexError(builder, landingPadContainer, index, length); LLVMBasicBlockRef landingPadBlock = landingPadContainer.getExistingLandingPadBlock(); if (landingPadBlock != null) { LLVM.LLVMPositionBuilderAtEnd(builder, landingPadBlock); LLVMValueRef landingPad = LLVM.LLVMBuildLandingPad(builder, getLandingPadType(), codeGenerator.getPersonalityFunction(), 0, ""); LLVM.LLVMSetCleanup(landingPad, true); LLVM.LLVMBuildResume(builder, landingPad); } LLVM.LLVMDisposeBuilder(builder); return function; } /** * Builds code to throw an index error, with the specified index and size. * @param builder - the LLVMBuilderRef to build instructions with * @param landingPadContainer - the LandingPadContainer containing the landing pad block for exceptions to be unwound to * @param index - the index that was out of bounds * @param size - the size that the index should have been less than */ public void buildThrowIndexError(LLVMBuilderRef builder, LandingPadContainer landingPadContainer, LLVMValueRef index, LLVMValueRef size) { // call the allocator ClassDefinition indexErrorTypeDefinition = (ClassDefinition) SpecialTypeHandler.INDEX_ERROR_TYPE.getResolvedTypeDefinition(); LLVMValueRef[] allocatorArgs = new LLVMValueRef[0]; LLVMValueRef allocator = codeGenerator.getAllocatorFunction(indexErrorTypeDefinition); LLVMBasicBlockRef allocatorInvokeContinueBlock = LLVM.LLVMAddBasicBlock(builder, "indexErrorAllocatorContinue"); LLVMValueRef allocatedIndexError = LLVM.LLVMBuildInvoke(builder, allocator, C.toNativePointerArray(allocatorArgs, false, true), allocatorArgs.length, allocatorInvokeContinueBlock, landingPadContainer.getLandingPadBlock(), ""); LLVM.LLVMPositionBuilderAtEnd(builder, allocatorInvokeContinueBlock); // call the constructor LLVMValueRef constructorFunction = codeGenerator.getConstructorFunction(SpecialTypeHandler.indexErrorIndexSizeConstructor); LLVMValueRef[] constructorArgs = new LLVMValueRef[] {allocatedIndexError, index, size}; LLVMBasicBlockRef constructorInvokeContinueBlock = LLVM.LLVMAddBasicBlock(builder, "indexErrorConstructorContinue"); LLVM.LLVMBuildInvoke(builder, constructorFunction, C.toNativePointerArray(constructorArgs, false, true), constructorArgs.length, constructorInvokeContinueBlock, landingPadContainer.getLandingPadBlock(), ""); LLVM.LLVMPositionBuilderAtEnd(builder, constructorInvokeContinueBlock); LLVMValueRef indexError = convertTemporaryToStandard(builder, allocatedIndexError, SpecialTypeHandler.INDEX_ERROR_TYPE); LLVMValueRef unwindException = codeGenerator.buildCreateException(builder, indexError); codeGenerator.buildThrow(builder, landingPadContainer, unwindException); } /** * Builds code to throw a cast error, with the specified from type, to type, and reason. * Note: this method finishes the current LLVM basic block. * @param builder - the LLVMBuilderRef to build instructions with * @param landingPadContainer - the LandingPadContainer containing the landing pad block for exceptions to be unwound to * @param fromType - the fromType string to call the CastError constructor with * @param toType - the toType string to call the CastError constructor with * @param reason - the reason string to call the CastError constructor with (can be null) */ public void buildThrowCastError(LLVMBuilderRef builder, LandingPadContainer landingPadContainer, String fromType, String toType, String reason) { buildThrowCastError(builder, landingPadContainer, codeGenerator.buildStringCreation(builder, landingPadContainer, fromType), toType, reason); } /** * Builds code to throw a cast error, with the specified from type, to type, and reason. * Note: this method finishes the current LLVM basic block. * @param builder - the LLVMBuilderRef to build instructions with * @param landingPadContainer - the LandingPadContainer containing the landing pad block for exceptions to be unwound to * @param llvmFromType - the fromType string to call the CastError constructor with, in a temporary type representation * @param toType - the toType string to call the CastError constructor with * @param reason - the reason string to call the CastError constructor with (can be null) */ public void buildThrowCastError(LLVMBuilderRef builder, LandingPadContainer landingPadContainer, LLVMValueRef llvmFromType, String toType, String reason) { ClassDefinition castErrorTypeDefinition = (ClassDefinition) SpecialTypeHandler.CAST_ERROR_TYPE.getResolvedTypeDefinition(); LLVMValueRef[] allocatorArgs = new LLVMValueRef[0]; LLVMValueRef allocator = codeGenerator.getAllocatorFunction(castErrorTypeDefinition); LLVMBasicBlockRef allocatorInvokeContinueBlock = LLVM.LLVMAddBasicBlock(builder, "castErrorAllocatorContinue"); LLVMValueRef allocatedCastError = LLVM.LLVMBuildInvoke(builder, allocator, C.toNativePointerArray(allocatorArgs, false, true), allocatorArgs.length, allocatorInvokeContinueBlock, landingPadContainer.getLandingPadBlock(), ""); LLVM.LLVMPositionBuilderAtEnd(builder, allocatorInvokeContinueBlock); llvmFromType = convertTemporaryToStandard(builder, llvmFromType, SpecialTypeHandler.STRING_TYPE); LLVMValueRef llvmToType = codeGenerator.buildStringCreation(builder, landingPadContainer, toType); llvmToType = convertTemporaryToStandard(builder, llvmToType, SpecialTypeHandler.STRING_TYPE); LLVMValueRef llvmReason; Type nullableStringType = Type.findTypeWithNullability(SpecialTypeHandler.STRING_TYPE, true); if (reason == null) { llvmReason = LLVM.LLVMConstNull(findStandardType(nullableStringType)); } else { llvmReason = codeGenerator.buildStringCreation(builder, landingPadContainer, reason); llvmReason = convertTemporaryToStandard(builder, landingPadContainer, llvmReason, SpecialTypeHandler.STRING_TYPE, nullableStringType, null, null); } LLVMValueRef constructorFunction = codeGenerator.getConstructorFunction(SpecialTypeHandler.castErrorTypesReasonConstructor); LLVMValueRef[] constructorArguments = new LLVMValueRef[] {allocatedCastError, llvmFromType, llvmToType, llvmReason}; LLVMBasicBlockRef constructorInvokeContinueBlock = LLVM.LLVMAddBasicBlock(builder, "castErrorConstructorContinue"); LLVM.LLVMBuildInvoke(builder, constructorFunction, C.toNativePointerArray(constructorArguments, false, true), constructorArguments.length, constructorInvokeContinueBlock, landingPadContainer.getLandingPadBlock(), ""); LLVM.LLVMPositionBuilderAtEnd(builder, constructorInvokeContinueBlock); LLVMValueRef castError = convertTemporaryToStandard(builder, allocatedCastError, SpecialTypeHandler.CAST_ERROR_TYPE); LLVMValueRef unwindException = codeGenerator.buildCreateException(builder, castError); codeGenerator.buildThrow(builder, landingPadContainer, unwindException); } /** * Builds a null check which will throw a CastError on failure. * @param builder - the LLVMBuilderRef to build instructions with * @param landingPadContainer - the LandingPadContainer containing the landing pad block for exceptions to be unwound to * @param value - the value to perform the null check on, in a temporary type representation * @param from - the Type of value * @param to - the Type that the value is being converted to * @param toAccessor - the TypeParameterAccessor to look up 'to' in, if it turns out to be a type parameter */ private void buildCastNullCheck(LLVMBuilderRef builder, LandingPadContainer landingPadContainer, LLVMValueRef value, Type from, Type to, TypeParameterAccessor toAccessor) { LLVMBasicBlockRef continueBlock = LLVM.LLVMAddBasicBlock(builder, "castNullCheckContinue"); LLVMBasicBlockRef nullBlock = LLVM.LLVMAddBasicBlock(builder, "castNullFailure"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); String reasonString = null; boolean isTupleUnboxing = from instanceof TupleType && ((TupleType) from).getSubTypes().length == 1 && ((TupleType) from).getSubTypes()[0].isRuntimeEquivalent(to); if (to instanceof NamedType && ((NamedType) to).getResolvedTypeParameter() != null && !isTupleUnboxing) { TypeParameter typeParameter = ((NamedType) to).getResolvedTypeParameter(); LLVMValueRef rtti = toAccessor.findTypeParameterRTTI(typeParameter); LLVMValueRef typeIsNullable = rttiHelper.buildTypeIsNullableCheck(builder, rtti); LLVMValueRef success = LLVM.LLVMBuildOr(builder, isNotNull, typeIsNullable, ""); LLVM.LLVMBuildCondBr(builder, success, continueBlock, nullBlock); reasonString = "the type parameter " + to + " turned out not to be nullable"; } else { LLVM.LLVMBuildCondBr(builder, isNotNull, continueBlock, nullBlock); } LLVM.LLVMPositionBuilderAtEnd(builder, nullBlock); buildThrowCastError(builder, landingPadContainer, "null", to.toString(), reasonString); LLVM.LLVMPositionBuilderAtEnd(builder, continueBlock); } /** * Checks whether a conversion is required to convert from 'from' to 'to'. * This is designed to be used when deciding e.g. whether or not to proxy a function or an array during a conversion. * In some circumstances it will return that no conversion is required when in fact some bitcasting of contained pointers must be done for the LLVM types to line up correctly. * Crucially, it will never return false if a value needs to be re-packed into a different LLVM type, or if we would need to perform some run-time checks on the value. * In case of an unexpected conversion which should be invalid, this method will always return true, so that the caller will try to perform a conversion and convertTemporary() will discover the error. * @param from - the type that we are converting from * @param to - the type that we are converting to * @param performChecks - true if this check should assume that run-time checks need to be performed, false if it should assume that they aren't necessary * @return false if we can be sure that no conversion (over and above a bitcast) is required from 'from' to 'to', true otherwise */ private boolean checkRequiresConversion(Type from, Type to, boolean performChecks) { if (from.isRuntimeEquivalent(to)) { return false; } if (from instanceof PrimitiveType && to instanceof PrimitiveType) { // they are not equivalent, so there needs to be a conversion return true; } if (from instanceof ArrayType && to instanceof ArrayType) { ArrayType fromArray = (ArrayType) from; ArrayType toArray = (ArrayType) to; if (performChecks && fromArray.canBeNullable() && !toArray.isNullable()) { return true; } return checkRequiresConversion(fromArray.getBaseType(), toArray.getBaseType(), performChecks) || checkRequiresConversion(toArray.getBaseType(), fromArray.getBaseType(), performChecks); } if (from instanceof FunctionType && to instanceof FunctionType) { FunctionType fromFunction = (FunctionType) from; FunctionType toFunction = (FunctionType) to; if (performChecks && ((fromFunction.canBeNullable() && !toFunction.isNullable()) || (!fromFunction.isImmutable() && toFunction.isImmutable()))) { return true; } if (checkRequiresConversion(fromFunction.getReturnType(), toFunction.getReturnType(), performChecks)) { return true; } Type[] fromParams = fromFunction.getParameterTypes(); Type[] toParams = toFunction.getParameterTypes(); if (fromParams.length != toParams.length) { return true; } for (int i = 0; i < fromParams.length; ++i) { if (checkRequiresConversion(toParams[i], fromParams[i], performChecks)) { return true; } } return false; } // note: we let single-element-tuple extraction and insertion fall through to the catch-all, as they always require conversion if (from instanceof TupleType && to instanceof TupleType) { TupleType fromTuple = (TupleType) from; TupleType toTuple = (TupleType) to; Type[] fromSubTypes = fromTuple.getSubTypes(); Type[] toSubTypes = toTuple.getSubTypes(); if (from.canBeNullable() != to.isNullable() || fromSubTypes.length != toSubTypes.length) { return true; } for (int i = 0; i < fromSubTypes.length; ++i) { if (checkRequiresConversion(fromSubTypes[i], toSubTypes[i], performChecks)) { return true; } } // the elements inside the tuples do not require conversion return false; } if (to instanceof WildcardType) { if (!performChecks && from.canBeNullable() && !to.canBeNullable()) { return true; } if (from instanceof ObjectType || from instanceof ArrayType || from instanceof WildcardType || (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof ClassDefinition) || (from instanceof NamedType && ((NamedType) from).getResolvedTypeParameter() != null)) { // a run-time check only needs to be generated if the 'to' type's super-types can't assign 'from' if (performChecks) { Type fromNoModifiers = Type.findTypeWithoutModifiers(from); for (Type t : Type.findAllSuperTypes(to)) { if (!t.canAssign(fromNoModifiers)) { return true; } } } return false; } return true; } if (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof ClassDefinition) { if (!performChecks && from.canBeNullable() && !to.isNullable() && !(to instanceof WildcardType && to.canBeNullable())) { return true; } // in some circumstances, we might be able to get away without casting a class, since it has the same native representation as various other types if (to instanceof ObjectType || from.isRuntimeEquivalent(to) || (!performChecks && to instanceof NamedType && ((NamedType) to).getResolvedTypeParameter() != null) || (!performChecks && to instanceof NamedType && ((NamedType) to).getResolvedTypeDefinition() instanceof ClassDefinition)) { return false; } if (to instanceof WildcardType) { return performChecks && !((WildcardType) to).encompasses(from); } if (!(to instanceof NamedType)) { return true; } NamedType fromNamed = (NamedType) from; GenericTypeSpecialiser specialiser = new GenericTypeSpecialiser(fromNamed); NamedType toNamed = (NamedType) to; if (toNamed.getResolvedTypeDefinition() != null) { Type[] toTypeArguments = toNamed.getTypeArguments(); for (NamedType t : fromNamed.getResolvedTypeDefinition().getInheritanceLinearisation()) { NamedType superType = (NamedType) specialiser.getSpecialisedType(t); if (!(superType.getResolvedTypeDefinition() instanceof ClassDefinition) || toNamed.getResolvedTypeDefinition() != superType.getResolvedTypeDefinition()) { continue; } Type[] superTypeArguments = superType.getTypeArguments(); if ((toTypeArguments == null) != (superTypeArguments == null) || (toTypeArguments != null && toTypeArguments.length != superTypeArguments.length)) { continue; } boolean argumentsMatch = true; for (int i = 0; toTypeArguments != null && i < toTypeArguments.length; ++i) { if (toTypeArguments[i] instanceof WildcardType) { // the type argument of 'to' is a wildcard, so allow the conversion as long as it encompasses the current type argument if (!((WildcardType) toTypeArguments[i]).encompasses(superTypeArguments[i])) { argumentsMatch = false; break; } } else if (toTypeArguments[i].isRuntimeEquivalent(superTypeArguments[i])) { // all non-wildcard type arguments must be equivalent argumentsMatch = false; break; } } if (argumentsMatch) { // 'to' is above 'from' in the type hierarchy, so the only conversion we need is a bitcast return false; } } return true; } } if (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof InterfaceDefinition) { if (to instanceof NamedType && ((NamedType) to).getResolvedTypeDefinition() instanceof InterfaceDefinition) { if (performChecks && from.canBeNullable() && !to.isNullable()) { return true; } // if these two interfaces are completely identical, then we don't need to do any conversion // however, if either the interface or any of the type arguments differ, we will need to lookup the VFT again NamedType fromNamed = (NamedType) from; NamedType toNamed = (NamedType) to; if (fromNamed.getResolvedTypeDefinition() != toNamed.getResolvedTypeDefinition() || fromNamed.getTypeArguments().length != toNamed.getTypeArguments().length) { return true; } Type[] fromArguments = fromNamed.getTypeArguments(); Type[] toArguments = toNamed.getTypeArguments(); for (int i = 0; i < fromArguments.length; ++i) { if (fromArguments[i] instanceof WildcardType && toArguments[i] instanceof WildcardType) { // both of the arguments are wildcards, so if the 'to' argument encompasses the 'from' argument, then this argument doesn't make us require a conversion // NOTE: we require that both of them are wildcards in order to relax the equivalence check, because if one is a wildcard but one isn't then the interface's type representation will change if (!((WildcardType) toArguments[i]).encompasses(fromArguments[i])) { return true; } } else if (!fromArguments[i].isRuntimeEquivalent(toArguments[i])) { return true; } } // the 'from' and 'to' types are identical, except for perhaps their nullability, which we have already checked for return false; } return true; } if (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof CompoundDefinition) { if (to instanceof NamedType && ((NamedType) to).getResolvedTypeDefinition() instanceof CompoundDefinition) { if (performChecks && from.canBeNullable() && !to.isNullable()) { return true; } // if these two compound types are completely identical, then we don't need to do any checks // however, if either the compound type or any of the type arguments differ, we will need to do some checks if (performChecks) { NamedType fromNamed = (NamedType) from; NamedType toNamed = (NamedType) to; if (fromNamed.getResolvedTypeDefinition() != toNamed.getResolvedTypeDefinition() || fromNamed.getTypeArguments().length != toNamed.getTypeArguments().length) { return true; } Type[] fromArguments = fromNamed.getTypeArguments(); Type[] toArguments = toNamed.getTypeArguments(); for (int i = 0; i < fromArguments.length; ++i) { if (toArguments[i] instanceof WildcardType) { // the type argument of 'to' is a wildcard, so allow the conversion as long as it encompasses the current type argument if (!((WildcardType) toArguments[i]).encompasses(fromArguments[i])) { return true; } } else if (!fromArguments[i].isRuntimeEquivalent(toArguments[i])) { return true; } } } // the 'from' and 'to' types are identical, except for perhaps their nullability, which we have already checked for return false; } return true; } if (from instanceof NamedType && ((NamedType) from).getResolvedTypeParameter() != null) { if (performChecks && from.canBeNullable() && !to.isNullable() && !(to instanceof WildcardType && to.canBeNullable())) { return true; } TypeParameter typeParameter = ((NamedType) from).getResolvedTypeParameter(); if (to instanceof ObjectType || (!performChecks && to instanceof NamedType && ((NamedType) to).getResolvedTypeParameter() != null) || (to instanceof NamedType && ((NamedType) to).getResolvedTypeParameter() == typeParameter)) { return false; } if ((to instanceof NamedType && ((NamedType) to).getResolvedTypeDefinition() instanceof ClassDefinition) || to instanceof ArrayType) { for (Type superType : typeParameter.getSuperTypes()) { if (((superType instanceof NamedType && ((NamedType) superType).getResolvedTypeDefinition() instanceof ClassDefinition) || superType instanceof ArrayType) && !checkRequiresConversion(superType, to, performChecks)) { return false; } } } return true; } if (!performChecks && (from instanceof ObjectType || from instanceof WildcardType)) { // if we are coming from the object type or a wildcard type and not performing checks, we can go to any type which is represented like an object, by bitcasting return !(to instanceof ArrayType || (to instanceof NamedType && ((NamedType) to).getResolvedTypeDefinition() instanceof ClassDefinition) || (to instanceof NamedType && ((NamedType) to).getResolvedTypeParameter() != null) || to instanceof ObjectType || to instanceof WildcardType); } // if we aren't doing any run-time checks, treat type parameters as objects if (to instanceof ObjectType || (!performChecks && to instanceof NamedType && ((NamedType) to).getResolvedTypeParameter() != null)) { if (performChecks && from.canBeNullable() && !to.isNullable()) { return true; } // if we are converting from something which is not represented like a pointer to an object, then we require a conversion return !(from instanceof ArrayType || (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof ClassDefinition) || (from instanceof NamedType && ((NamedType) from).getResolvedTypeParameter() != null) || from instanceof ObjectType || from instanceof WildcardType); } if (performChecks && to instanceof NamedType && ((NamedType) to).getResolvedTypeParameter() != null) { if (from instanceof NamedType && ((NamedType) from).getResolvedTypeParameter() == ((NamedType) to).getResolvedTypeParameter()) { // these types represent the same type parameter, so we only need to do any run-time checks if their nullabilities can't always be implicitly converted return from.isNullable() && !to.isNullable(); } // if we are converting from something other than exactly the same type parameter, we will have to do RTTI checks return true; } // note: we let all other conversions from objects fall through to the catch-all, as they always require RTTI checks return true; } /** * Strips any type parameters and wildcard types which are not part of a type argument to a NamedType from the specified type. * The stripped type parameters are replaced by the object type. * Types are meant to be treated as immutable, so a new stripped type is returned rather than modifying the existing one. * @param type - the Type to find the stripped version of * @return the type, with any type parameters and wildcard types which could affect the native type replaced by objects */ public Type stripTypeParameters(Type type) { if (type instanceof ArrayType) { ArrayType arrayType = (ArrayType) type; Type baseType = stripTypeParameters(arrayType.getBaseType()); if (baseType == arrayType.getBaseType()) { // it wasn't modified, so return the existing array return arrayType; } return new ArrayType(arrayType.canBeNullable(), arrayType.isExplicitlyImmutable(), arrayType.isContextuallyImmutable(), baseType, null); } if (type instanceof FunctionType) { FunctionType functionType = (FunctionType) type; Type returnType = stripTypeParameters(functionType.getReturnType()); boolean changed = returnType != functionType.getReturnType(); Type[] oldParamTypes = functionType.getParameterTypes(); Type[] paramTypes = new Type[oldParamTypes.length]; for (int i = 0; i < paramTypes.length; ++i) { paramTypes[i] = stripTypeParameters(oldParamTypes[i]); changed |= paramTypes[i] != oldParamTypes[i]; } if (changed) { return new FunctionType(functionType.canBeNullable(), functionType.isImmutable(), returnType, paramTypes, functionType.getThrownTypes(), null); } return functionType; } if (type instanceof NamedType) { NamedType namedType = (NamedType) type; if (namedType.getResolvedTypeParameter() != null) { return new ObjectType(namedType.canBeNullable(), namedType.canBeExplicitlyImmutable(), namedType.isContextuallyImmutable(), null); } // all non-type-parameter NamedTypes don't need anything to be replaced, as their native types do not depend on their type arguments return namedType; } if (type instanceof TupleType) { TupleType tupleType = (TupleType) type; boolean changed = false; Type[] oldSubTypes = tupleType.getSubTypes(); Type[] subTypes = new Type[oldSubTypes.length]; for (int i = 0; i < oldSubTypes.length; ++i) { subTypes[i] = stripTypeParameters(oldSubTypes[i]); changed |= subTypes[i] != oldSubTypes[i]; } if (changed) { return new TupleType(tupleType.canBeNullable(), subTypes, null); } return tupleType; } if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; return new ObjectType(wildcardType.canBeNullable(), wildcardType.canBeExplicitlyImmutable(), null); } if (type instanceof NullType || type instanceof ObjectType || type instanceof PrimitiveType || type instanceof VoidType) { return type; } throw new IllegalArgumentException("Unknown sort of type: " + type); } /** * Converts the specified value from the specified 'from' type to the specified 'to' type, as a temporary. * This method assumes that the incoming value has a temporary native type, and produces a result with a temporary native type. * @param builder - the LLVMBuilderRef to build instructions with * @param landingPadContainer - the LandingPadContainer containing the landing pad block for exceptions to be unwound to * @param value - the value to convert * @param from - the Type to convert from * @param to - the Type to convert to * @param skipRuntimeChecks - true if run-time checks should be checked during this conversion - only use this if you can be SURE that the value is definitely of the correct type already * @param fromAccessor - the TypeParameterAccessor to get the values of any type parameters inside 'from' from * @param toAccessor - the TypeParameterAccessor to get the values of any type parameters inside 'to' from * @return the converted value */ public LLVMValueRef convertTemporary(LLVMBuilderRef builder, LandingPadContainer landingPadContainer, LLVMValueRef value, Type from, Type to, boolean skipRuntimeChecks, TypeParameterAccessor fromAccessor, TypeParameterAccessor toAccessor) { // Note concerning Type Parameters: // Sometimes, we will be at a boundary between two objects, such as a method call, converting from a type in one object's context to a type in another object's context. // For type parameters, you might expect this to cause a problem when the two type parameters are equivalent at compile time but are looked up in different TypeParameterAccessors at run time. // However, whenever we convert something at a type boundary, we always do a direct conversion from the real type (e.g. of a parameter) to the specialised type, where the only // difference is that the parameter has been specialised to the outer context. Because of this, we can know that if we have two equivalent TypeParameters, they must have // equivalent values in their respective mappers. if (from.isRuntimeEquivalent(to)) { return value; } if (from instanceof PrimitiveType && to instanceof PrimitiveType) { if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } return convertPrimitiveType(builder, value, (PrimitiveType) from, (PrimitiveType) to); } if (from instanceof ArrayType && to instanceof ArrayType) { // array casts are illegal unless the base types are the same, so they must have the same basic type if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } // immutability will be checked by the type checker, but it doesn't have any effect on the native type, so we do not need to do anything special here ArrayType fromArray = (ArrayType) from; // the run-time type of an array never includes any references to type parameters, so they need to be stripped here ArrayType toArray = (ArrayType) stripTypeParameters(to); boolean needsProxying = checkRequiresConversion(fromArray.getBaseType(), toArray.getBaseType(), true) || checkRequiresConversion(toArray.getBaseType(), fromArray.getBaseType(), true); if (needsProxying) { return buildProxyArrayConversion(builder, value, fromArray, toArray, fromAccessor, toAccessor); } return LLVM.LLVMBuildBitCast(builder, value, findTemporaryType(toArray), ""); } if (from instanceof FunctionType && to instanceof FunctionType) { // function casts are illegal unless the parameter and return types are the same, so they must have the same basic type if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } FunctionType fromFunction = (FunctionType) from; FunctionType toFunction = (FunctionType) to; // a cast from a non-immutable function to an immutable function type is impossible // so perform a run-time check that this constraint is not violated if (!skipRuntimeChecks && !fromFunction.isImmutable() && toFunction.isImmutable()) { // this is only allowed if the run-time type of value shows that it is immutable LLVMBasicBlockRef functionImmutabilityCheckContinueBlock = LLVM.LLVMAddBasicBlock(builder, "functionImmutabilityCheckContinue"); // if the value is nullable, allow null values to pass through (we've already checked the nullability) if (from.canBeNullable()) { LLVMBasicBlockRef functionImmutabilityCheckBlock = LLVM.LLVMAddBasicBlock(builder, "functionImmutabilityCheck"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); LLVM.LLVMBuildCondBr(builder, isNotNull, functionImmutabilityCheckBlock, functionImmutabilityCheckContinueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, functionImmutabilityCheckBlock); } LLVMValueRef runtimeTypeMatches = rttiHelper.buildInstanceOfCheck(builder, landingPadContainer, value, Type.findTypeWithNullability(from, false), to, fromAccessor, toAccessor); LLVMBasicBlockRef immutabilityCastFailure = LLVM.LLVMAddBasicBlock(builder, "functionImmutabilityCheckFailure"); LLVM.LLVMBuildCondBr(builder, runtimeTypeMatches, functionImmutabilityCheckContinueBlock, immutabilityCastFailure); LLVM.LLVMPositionBuilderAtEnd(builder, immutabilityCastFailure); buildThrowCastError(builder, landingPadContainer, from.toString(), to.toString(), "non-immutable functions cannot be cast to immutable"); LLVM.LLVMPositionBuilderAtEnd(builder, functionImmutabilityCheckContinueBlock); } // strip any type parameters from the 'to' type, so that the RTTI doesn't contain anything which could confuse things // if we tried to convert to object and back to another type, RTTI containing type parameters would cause breakages in the cast instanceof checks toFunction = (FunctionType) stripTypeParameters(toFunction); boolean needsProxying = checkRequiresConversion(toFunction.getReturnType(), fromFunction.getReturnType(), true); Type[] fromParamTypes = fromFunction.getParameterTypes(); Type[] toParamTypes = toFunction.getParameterTypes(); needsProxying |= fromParamTypes.length != toParamTypes.length; for (int i = 0; !needsProxying & i < fromParamTypes.length; ++i) { needsProxying |= checkRequiresConversion(fromParamTypes[i], toParamTypes[i], true); } if (needsProxying) { return buildFunctionProxyConversion(builder, value, fromFunction, toFunction, fromAccessor, toAccessor); } if (!fromFunction.isRuntimeEquivalent(toFunction)) { // repack the function, after bitcasting the function pointer LLVMValueRef rtti = LLVM.LLVMBuildExtractValue(builder, value, 0, ""); LLVMValueRef callee = LLVM.LLVMBuildExtractValue(builder, value, 1, ""); LLVMValueRef function = LLVM.LLVMBuildExtractValue(builder, value, 2, ""); function = LLVM.LLVMBuildBitCast(builder, function, findRawFunctionPointerType(toFunction), ""); LLVMValueRef result = LLVM.LLVMGetUndef(findTemporaryType(toFunction)); result = LLVM.LLVMBuildInsertValue(builder, result, rtti, 0, ""); result = LLVM.LLVMBuildInsertValue(builder, result, callee, 1, ""); result = LLVM.LLVMBuildInsertValue(builder, result, function, 2, ""); return result; } return value; } if (from instanceof NamedType && to instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof ClassDefinition && ((NamedType) to).getResolvedTypeDefinition() instanceof ClassDefinition) { if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } // check whether 'to' is a super-class of 'from' NamedType fromNamed = (NamedType) from; NamedType toNamed = (NamedType) to; GenericTypeSpecialiser genericTypeSpecialiser = new GenericTypeSpecialiser(fromNamed); boolean isInherited = false; for (NamedType t : fromNamed.getResolvedTypeDefinition().getInheritanceLinearisation()) { NamedType superType = (NamedType) genericTypeSpecialiser.getSpecialisedType(t); if (!(superType.getResolvedTypeDefinition() instanceof ClassDefinition) || superType.getResolvedTypeDefinition() != toNamed.getResolvedTypeDefinition()) { continue; } Type[] fromArguments = superType.getTypeArguments(); Type[] toArguments = toNamed.getTypeArguments(); if ((fromArguments == null) != (toArguments == null) || (fromArguments != null && fromArguments.length != toArguments.length)) { continue; } boolean argumentsMatch = true; for (int i = 0; fromArguments != null && i < fromArguments.length; ++i) { if (toArguments[i] instanceof WildcardType) { // the type argument of 'to' is a wildcard, so the super-type matches as long as it encompasses the current type argument if (!((WildcardType) toArguments[i]).encompasses(fromArguments[i])) { argumentsMatch = false; break; } } else if (!toArguments[i].isRuntimeEquivalent(fromArguments[i])) { argumentsMatch = false; break; } } if (argumentsMatch) { isInherited = true; break; } } if (!isInherited && !skipRuntimeChecks) { LLVMBasicBlockRef instanceOfContinueBlock = LLVM.LLVMAddBasicBlock(builder, "castInstanceOfCheckContinue"); if (from.canBeNullable()) { // if the value is null, then skip the check LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); LLVMBasicBlockRef instanceOfCheckBlock = LLVM.LLVMAddBasicBlock(builder, "castInstanceOfCheck"); LLVM.LLVMBuildCondBr(builder, isNotNull, instanceOfCheckBlock, instanceOfContinueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfCheckBlock); } LLVMValueRef runtimeTypeMatches = rttiHelper.buildInstanceOfCheck(builder, landingPadContainer, value, Type.findTypeWithNullability(from, false), to, fromAccessor, toAccessor); LLVMBasicBlockRef castFailureBlock = LLVM.LLVMAddBasicBlock(builder, "castFailure"); LLVM.LLVMBuildCondBr(builder, runtimeTypeMatches, instanceOfContinueBlock, castFailureBlock); LLVM.LLVMPositionBuilderAtEnd(builder, castFailureBlock); LLVMValueRef rttiPointer = rttiHelper.getRTTIPointer(builder, value); LLVMValueRef rtti = LLVM.LLVMBuildLoad(builder, rttiPointer, ""); LLVMValueRef classNameUbyteArray = rttiHelper.lookupNamedTypeName(builder, rtti); LLVMValueRef classNameString = codeGenerator.buildStringCreation(builder, landingPadContainer, classNameUbyteArray); buildThrowCastError(builder, landingPadContainer, classNameString, to.toString(), null); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfContinueBlock); } // both from and to are class types, and we have made sure that we can convert between them // so bitcast value to the new type return LLVM.LLVMBuildBitCast(builder, value, findTemporaryType(to), ""); } if (from instanceof NamedType && to instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof CompoundDefinition && ((NamedType) to).getResolvedTypeDefinition() instanceof CompoundDefinition) { // compound type casts are illegal unless the type definitions are the same, so they must have the same type definition if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } if (!skipRuntimeChecks && !from.isRuntimeEquivalent(to)) { LLVMBasicBlockRef instanceOfContinueBlock = LLVM.LLVMAddBasicBlock(builder, "castInstanceOfCheckContinue"); if (from.canBeNullable()) { // if the value is null, then skip the check LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); LLVMBasicBlockRef instanceOfCheckBlock = LLVM.LLVMAddBasicBlock(builder, "castInstanceOfCheck"); LLVM.LLVMBuildCondBr(builder, isNotNull, instanceOfCheckBlock, instanceOfContinueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfCheckBlock); } LLVMValueRef runtimeTypeMatches = rttiHelper.buildInstanceOfCheck(builder, landingPadContainer, value, Type.findTypeWithNullability(from, false), to, fromAccessor, toAccessor); LLVMBasicBlockRef castFailureBlock = LLVM.LLVMAddBasicBlock(builder, "castFailure"); LLVM.LLVMBuildCondBr(builder, runtimeTypeMatches, instanceOfContinueBlock, castFailureBlock); LLVM.LLVMPositionBuilderAtEnd(builder, castFailureBlock); buildThrowCastError(builder, landingPadContainer, from.toString(), to.toString(), null); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfContinueBlock); // both from and to are compound types, and we have made sure that we can convert between them // so bitcast value to the new type value = LLVM.LLVMBuildBitCast(builder, value, findTemporaryType(to), ""); } return value; } if (from instanceof NamedType && to instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof InterfaceDefinition && ((NamedType) to).getResolvedTypeDefinition() instanceof ClassDefinition) { ObjectType objectType = new ObjectType(from.canBeNullable(), false, null); // there are no type parameters inside objectType, so use a null TypeParameterAccessor TypeParameterAccessor nullAccessor = new TypeParameterAccessor(builder, rttiHelper); LLVMValueRef objectValue = convertTemporary(builder, landingPadContainer, value, from, objectType, skipRuntimeChecks, fromAccessor, nullAccessor); return convertTemporary(builder, landingPadContainer, objectValue, objectType, to, skipRuntimeChecks, nullAccessor, toAccessor); } if (from instanceof NamedType && to instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof ClassDefinition && ((NamedType) to).getResolvedTypeDefinition() instanceof InterfaceDefinition) { ClassDefinition classDefinition = (ClassDefinition) ((NamedType) from).getResolvedTypeDefinition(); GenericTypeSpecialiser genericTypeSpecialiser = new GenericTypeSpecialiser((NamedType) from); NamedType toNamed = (NamedType) to; NamedType foundType = null; + NamedType specialisedFoundType = null; for (NamedType t : classDefinition.getInheritanceLinearisation()) { NamedType superType = (NamedType) genericTypeSpecialiser.getSpecialisedType(t); // check whether superType matches toNamed // we cannot just remove modifiers and check for equivalence, because toNamed might have wildcard type arguments which match superType's type arguments if (toNamed.getResolvedTypeDefinition() != superType.getResolvedTypeDefinition()) { continue; } Type[] toTypeArguments = toNamed.getTypeArguments(); Type[] superTypeArguments = superType.getTypeArguments(); if (((toTypeArguments == null) != (superTypeArguments == null)) || (toTypeArguments != null && toTypeArguments.length != superTypeArguments.length)) { continue; } boolean argumentsMatch = true; for (int i = 0; argumentsMatch && toTypeArguments != null && i < toTypeArguments.length; ++i) { if (toTypeArguments[i] instanceof WildcardType) { argumentsMatch = ((WildcardType) toTypeArguments[i]).encompasses(superTypeArguments[i]); } else { argumentsMatch = toTypeArguments[i].isRuntimeEquivalent(superTypeArguments[i]); } } if (argumentsMatch) { // Note: we want the unspecialised version of the super-type here, so that it can be specialised at run-time to have the same type arguments as the run-time type of the class we are converting from // one point to consider is, if 'from' has wildcard type arguments, we want to set the interface's type argument RTTI pointers to their real values, not a '?' foundType = t; + specialisedFoundType = superType; break; } } if (foundType != null) { if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef continueBlock = null; // make sure we don't do a second null check if this is a cast from nullable to not-nullable if (from.canBeNullable() && to.isNullable()) { startBlock = LLVM.LLVMGetInsertBlock(builder); continueBlock = LLVM.LLVMAddBasicBlock(builder, "toInterfaceContinuation"); LLVMBasicBlockRef convertBlock = LLVM.LLVMAddBasicBlock(builder, "toInterfaceConversion"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); LLVM.LLVMBuildCondBr(builder, isNotNull, convertBlock, continueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, convertBlock); } LLVMTypeRef resultNativeType = findStandardType(to); // we know exactly where the VFT is at compile time, so we don't need to search for it at run time, just look it up TypeParameterAccessor foundAccessor = new TypeParameterAccessor(builder, this, rttiHelper, classDefinition, value); - LLVMValueRef vft = virtualFunctionHandler.getVirtualFunctionTable(builder, landingPadContainer, value, (NamedType) from, foundType, fromAccessor, foundAccessor); + LLVMValueRef vft = virtualFunctionHandler.getVirtualFunctionTable(builder, landingPadContainer, value, (NamedType) from, specialisedFoundType, fromAccessor, foundAccessor); LLVMValueRef objectPointer = convertTemporary(builder, landingPadContainer, value, from, new ObjectType(from.canBeNullable(), false, null), skipRuntimeChecks, fromAccessor, new TypeParameterAccessor(builder, rttiHelper)); LLVMValueRef interfaceValue = LLVM.LLVMGetUndef(resultNativeType); interfaceValue = LLVM.LLVMBuildInsertValue(builder, interfaceValue, vft, 0, ""); interfaceValue = LLVM.LLVMBuildInsertValue(builder, interfaceValue, objectPointer, 1, ""); // fill in the interface's wildcard type argument RTTI values Type[] toTypeArguments = toNamed.getTypeArguments(); Type[] foundTypeArguments = foundType.getTypeArguments(); int wildcardIndex = 0; TypeParameterAccessor wildcardTypeParameterAccessor = new TypeParameterAccessor(builder, this, rttiHelper, classDefinition, value); for (int i = 0; toTypeArguments != null && i < toTypeArguments.length; ++i) { if (toTypeArguments[i] instanceof WildcardType) { LLVMValueRef rtti = rttiHelper.buildRTTICreation(builder, foundTypeArguments[i], wildcardTypeParameterAccessor); interfaceValue = LLVM.LLVMBuildInsertValue(builder, interfaceValue, rtti, 2 + wildcardIndex, ""); ++wildcardIndex; } } if (from.canBeNullable() && to.isNullable()) { LLVMBasicBlockRef endConvertBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continueBlock); LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, resultNativeType, ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {LLVM.LLVMConstNull(resultNativeType), interfaceValue}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, endConvertBlock}; LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length); return phiNode; } return interfaceValue; } } if (to instanceof NamedType && ((NamedType) to).getResolvedTypeDefinition() instanceof InterfaceDefinition) { LLVMValueRef objectValue = null; Type objectType = null; if (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof ClassDefinition) { objectType = new ObjectType(from.canBeNullable(), ((NamedType) from).isContextuallyImmutable(), null); objectValue = convertTemporary(builder, landingPadContainer, value, from, objectType, skipRuntimeChecks, fromAccessor, new TypeParameterAccessor(builder, rttiHelper)); } else if (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof InterfaceDefinition) { objectType = new ObjectType(from.canBeNullable(), ((NamedType) from).isContextuallyImmutable(), null); objectValue = convertTemporary(builder, landingPadContainer, value, from, objectType, skipRuntimeChecks, fromAccessor, new TypeParameterAccessor(builder, rttiHelper)); } else if (from instanceof ObjectType || from instanceof WildcardType) { objectType = from; objectValue = value; } if (objectValue != null) { if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef continueBlock = null; // make sure we don't do a second null check if this is a cast from nullable to not-nullable if (objectType.canBeNullable() && to.isNullable()) { startBlock = LLVM.LLVMGetInsertBlock(builder); continueBlock = LLVM.LLVMAddBasicBlock(builder, "toInterfaceContinuation"); LLVMBasicBlockRef convertBlock = LLVM.LLVMAddBasicBlock(builder, "toInterfaceConversion"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, objectValue, objectType); LLVM.LLVMBuildCondBr(builder, isNotNull, convertBlock, continueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, convertBlock); } LLVMTypeRef resultNativeType = findStandardType(to); NamedType toNamed = (NamedType) to; LLVMValueRef objectRTTIPtr = rttiHelper.getRTTIPointer(builder, objectValue); LLVMValueRef objectRTTI = LLVM.LLVMBuildLoad(builder, objectRTTIPtr, ""); LLVMValueRef typeLookupResult = rttiHelper.lookupInstanceSuperType(builder, objectRTTI, toNamed, toAccessor); LLVMValueRef vftPointer = LLVM.LLVMBuildExtractValue(builder, typeLookupResult, 1, ""); LLVMTypeRef vftPointerType = LLVM.LLVMPointerType(virtualFunctionHandler.getVFTType(toNamed.getResolvedTypeDefinition()), 0); vftPointer = LLVM.LLVMBuildBitCast(builder, vftPointer, vftPointerType, ""); LLVMValueRef vftPointerIsNotNull = LLVM.LLVMBuildIsNotNull(builder, vftPointer, ""); LLVMBasicBlockRef castSuccessBlock = LLVM.LLVMAddBasicBlock(builder, "toInterfaceCastSuccess"); LLVMBasicBlockRef castFailureBlock = LLVM.LLVMAddBasicBlock(builder, "toInterfaceCastFailure"); LLVM.LLVMBuildCondBr(builder, vftPointerIsNotNull, castSuccessBlock, castFailureBlock); LLVM.LLVMPositionBuilderAtEnd(builder, castFailureBlock); if ((from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof ClassDefinition) || (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof InterfaceDefinition)) { // if we're coming from a class or an interface, then we know that we can look up the real class name LLVMValueRef classNameUbyteArray = rttiHelper.lookupNamedTypeName(builder, objectRTTI); LLVMValueRef classNameString = codeGenerator.buildStringCreation(builder, landingPadContainer, classNameUbyteArray); buildThrowCastError(builder, landingPadContainer, classNameString, to.toString(), null); } else { buildThrowCastError(builder, landingPadContainer, from.toString(), to.toString(), "this object does not implement " + to); } LLVM.LLVMPositionBuilderAtEnd(builder, castSuccessBlock); LLVMValueRef interfaceValue = LLVM.LLVMGetUndef(resultNativeType); interfaceValue = LLVM.LLVMBuildInsertValue(builder, interfaceValue, vftPointer, 0, ""); interfaceValue = LLVM.LLVMBuildInsertValue(builder, interfaceValue, objectValue, 1, ""); Type[] toTypeArguments = toNamed.getTypeArguments(); TypeParameterAccessor interfaceTypeParameterAccessor = null; int wildcardIndex = 0; for (int i = 0; toTypeArguments != null && i < toTypeArguments.length; ++i) { if (toTypeArguments[i] instanceof WildcardType) { if (interfaceTypeParameterAccessor == null) { LLVMValueRef interfaceRTTIValue = LLVM.LLVMBuildExtractValue(builder, typeLookupResult, 0, ""); interfaceRTTIValue = LLVM.LLVMBuildBitCast(builder, interfaceRTTIValue, LLVM.LLVMPointerType(rttiHelper.getRTTIStructType(toNamed), 0), ""); interfaceTypeParameterAccessor = new TypeParameterAccessor(builder, rttiHelper, toNamed.getResolvedTypeDefinition(), rttiHelper.getNamedTypeArgumentMapper(builder, interfaceRTTIValue)); } // extract the type argument's RTTI from the interface RTTI value, by looking up the value of the type parameter at index i LLVMValueRef unspecialisedRTTI = interfaceTypeParameterAccessor.findTypeParameterRTTI(toNamed.getResolvedTypeDefinition().getTypeParameters()[i]); // specialise the extracted type argument to the same level as its concrete type // here we assume that if the interface's unspecialised RTTI in the type search list references a type parameter, then the concrete type of that object is a named type which defines that parameter LLVMValueRef objectNamedRTTI = LLVM.LLVMBuildBitCast(builder, objectRTTI, rttiHelper.getGenericNamedRTTIType(), ""); LLVMValueRef specialisedRTTI = rttiHelper.buildRTTISpecialisation(builder, unspecialisedRTTI, rttiHelper.getNamedTypeArgumentMapper(builder, objectNamedRTTI)); // store the new RTTI block inside the interface's value interfaceValue = LLVM.LLVMBuildInsertValue(builder, interfaceValue, specialisedRTTI, 2 + wildcardIndex, ""); ++wildcardIndex; } } if (objectType.canBeNullable() && to.isNullable()) { LLVMBasicBlockRef endConvertBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continueBlock); LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, resultNativeType, ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {LLVM.LLVMConstNull(resultNativeType), interfaceValue}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, endConvertBlock}; LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length); return phiNode; } return interfaceValue; } } if (from instanceof TupleType) { // check for a single-element-tuple extraction TupleType fromTuple = (TupleType) from; if (fromTuple.getSubTypes().length == 1 && fromTuple.getSubTypes()[0].isRuntimeEquivalent(to)) { if (from.canBeNullable()) { if (!skipRuntimeChecks) { // if from is nullable and value is null, then we need to throw a CastError here buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } // extract the value of the tuple from the nullable structure value = LLVM.LLVMBuildExtractValue(builder, value, 1, ""); } return LLVM.LLVMBuildExtractValue(builder, value, 0, ""); } } if (to instanceof TupleType) { // check for a single-element-tuple insertion TupleType toTuple = (TupleType) to; if (toTuple.getSubTypes().length == 1 && toTuple.getSubTypes()[0].isRuntimeEquivalent(from)) { LLVMValueRef tupledValue = LLVM.LLVMGetUndef(findTemporaryType(new TupleType(false, toTuple.getSubTypes(), null))); tupledValue = LLVM.LLVMBuildInsertValue(builder, tupledValue, value, 0, ""); if (to.isNullable()) { LLVMValueRef result = LLVM.LLVMGetUndef(findTemporaryType(to)); result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, ""); return LLVM.LLVMBuildInsertValue(builder, result, tupledValue, 1, ""); } return tupledValue; } } if (from instanceof TupleType && to instanceof TupleType) { if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } TupleType fromTuple = (TupleType) from; TupleType toTuple = (TupleType) to; Type[] fromSubTypes = fromTuple.getSubTypes(); Type[] toSubTypes = toTuple.getSubTypes(); if (fromSubTypes.length != toSubTypes.length) { throw new IllegalArgumentException("Cannot convert from a " + from + " to a " + to); } boolean subTypesEquivalent = true; for (int i = 0; i < fromSubTypes.length; ++i) { if (!fromSubTypes[i].isRuntimeEquivalent(toSubTypes[i])) { subTypesEquivalent = false; break; } } if (subTypesEquivalent) { // just convert the nullability if (from.canBeNullable() && !to.isNullable()) { // extract the value of the tuple from the nullable structure // (we have already done the associated null check above) return LLVM.LLVMBuildExtractValue(builder, value, 1, ""); } if (!from.canBeNullable() && to.isNullable()) { LLVMValueRef result = LLVM.LLVMGetUndef(findTemporaryType(to)); // set the flag to one to indicate that this value is not null result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, ""); return LLVM.LLVMBuildInsertValue(builder, result, value, 1, ""); } throw new IllegalArgumentException("Unable to convert from a " + from + " to a " + to + " - their sub types and nullability are equivalent, but the types themselves are not"); } LLVMValueRef isNotNullValue = null; LLVMValueRef tupleValue = value; if (from.canBeNullable()) { isNotNullValue = LLVM.LLVMBuildExtractValue(builder, value, 0, ""); tupleValue = LLVM.LLVMBuildExtractValue(builder, value, 1, ""); } LLVMValueRef currentValue = LLVM.LLVMGetUndef(findTemporaryType(toTuple)); for (int i = 0; i < fromSubTypes.length; i++) { LLVMValueRef current = LLVM.LLVMBuildExtractValue(builder, tupleValue, i, ""); LLVMValueRef converted = convertTemporary(builder, landingPadContainer, current, fromSubTypes[i], toSubTypes[i], skipRuntimeChecks, fromAccessor, toAccessor); currentValue = LLVM.LLVMBuildInsertValue(builder, currentValue, converted, i, ""); } if (to.isNullable()) { LLVMValueRef result = LLVM.LLVMGetUndef(findTemporaryType(to)); if (from.canBeNullable()) { result = LLVM.LLVMBuildInsertValue(builder, result, isNotNullValue, 0, ""); } else { // set the flag to one to indicate that this value is not null result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, ""); } return LLVM.LLVMBuildInsertValue(builder, result, currentValue, 1, ""); } // return the value directly, since the to type is not nullable return currentValue; } if ((from instanceof ObjectType || (from instanceof NamedType && ((NamedType) from).getResolvedTypeParameter() != null) || from instanceof WildcardType) && to instanceof ObjectType) { // object casts are always legal if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } // immutability will be checked by the type checker, and doesn't have any effect on the native type, so we do not need to do anything special here return value; } if (to instanceof ObjectType || (to instanceof NamedType && ((NamedType) to).getResolvedTypeParameter() != null) || to instanceof WildcardType) { // anything can convert to object if (from instanceof NullType) { if (!to.canBeNullable()) { throw new IllegalArgumentException("Cannot convert from NullType to a not-null object/type parameter/wildcard type"); } if (!skipRuntimeChecks && !to.isNullable() && !(to instanceof WildcardType && to.canBeNullable())) { // make sure to is actually nullable (if it is a TypeParameter, we can't check this at compile time) buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } return LLVM.LLVMConstNull(findTemporaryType(to)); } if (from instanceof ArrayType || (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof ClassDefinition) || (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof InterfaceDefinition) || (from instanceof NamedType && ((NamedType) from).getResolvedTypeParameter() != null) || from instanceof ObjectType || from instanceof WildcardType) { if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable() && !(to instanceof WildcardType && to.canBeNullable())) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } if (!skipRuntimeChecks && ((to instanceof NamedType && ((NamedType) to).getResolvedTypeParameter() != null) || to instanceof WildcardType)) { // build an instanceof check for the 'to' type LLVMBasicBlockRef continuationBlock = LLVM.LLVMAddBasicBlock(builder, "toTypeParamContinuation"); LLVMValueRef notNullValue = value; Type notNullFromType = Type.findTypeWithNullability(from, false); if (from.canBeNullable()) { // only do the instanceof check it if it is not null - if it is null then the conversion should succeed (if 'to' was nullable then we would already have failed) // if 'to' is not nullable, then we have already done the null check, so don't repeat it if (to.isNullable() || (to instanceof WildcardType && to.canBeNullable())) { LLVMBasicBlockRef notNullBlock = LLVM.LLVMAddBasicBlock(builder, "toTypeParamConversionNotNull"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); LLVM.LLVMBuildCondBr(builder, isNotNull, notNullBlock, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, notNullBlock); } // skip run-time checking on this nullable -> not-null conversion, as we have already done them notNullValue = convertTemporary(builder, landingPadContainer, value, from, notNullFromType, true, fromAccessor, fromAccessor); } LLVMValueRef isInstance = rttiHelper.buildInstanceOfCheck(builder, landingPadContainer, notNullValue, notNullFromType, to, fromAccessor, toAccessor); LLVMBasicBlockRef instanceOfFailureBlock = LLVM.LLVMAddBasicBlock(builder, "castToTypeParamInstanceOfFailure"); LLVM.LLVMBuildCondBr(builder, isInstance, continuationBlock, instanceOfFailureBlock); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfFailureBlock); buildThrowCastError(builder, landingPadContainer, from.toString(), to.toString(), null); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); } if (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof InterfaceDefinition) { // extract the object part of the interface's type return LLVM.LLVMBuildExtractValue(builder, value, 1, ""); } // object, class, type parameter, wildcard, and array types can be safely bitcast to object types return LLVM.LLVMBuildBitCast(builder, value, findTemporaryType(to), ""); } Type notNullFromType = Type.findTypeWithNullability(from, false); LLVMValueRef notNullValue = value; LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef notNullBlock; LLVMBasicBlockRef continuationBlock = null; if (from.canBeNullable()) { if (to.isNullable() || (to instanceof WildcardType && to.canBeNullable())) { continuationBlock = LLVM.LLVMAddBasicBlock(builder, "toObjectConversionContinuation"); notNullBlock = LLVM.LLVMAddBasicBlock(builder, "toObjectConversionNotNull"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); startBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildCondBr(builder, isNotNull, notNullBlock, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, notNullBlock); } else if (!skipRuntimeChecks) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } // skip run-time checking on this nullable -> not-null conversion, as we have already done them notNullValue = convertTemporary(builder, landingPadContainer, value, from, notNullFromType, true, fromAccessor, fromAccessor); } if (!skipRuntimeChecks && ((to instanceof NamedType && ((NamedType) to).getResolvedTypeParameter() != null) || to instanceof WildcardType)) { // do an instanceof check to make sure we are allowed to convert to this type parameter/wildcard LLVMValueRef isInstanceOfToType = rttiHelper.buildInstanceOfCheck(builder, landingPadContainer, notNullValue, notNullFromType, to, fromAccessor, toAccessor); LLVMBasicBlockRef instanceOfSuccessBlock = LLVM.LLVMAddBasicBlock(builder, "castObjectInstanceOfSuccess"); LLVMBasicBlockRef instanceOfFailureBlock = LLVM.LLVMAddBasicBlock(builder, "castObjectInstanceOfFailure"); LLVM.LLVMBuildCondBr(builder, isInstanceOfToType, instanceOfSuccessBlock, instanceOfFailureBlock); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfFailureBlock); buildThrowCastError(builder, landingPadContainer, from.toString(), to.toString(), null); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfSuccessBlock); } LLVMTypeRef nativeType = LLVM.LLVMPointerType(findSpecialisedObjectType(notNullFromType), 0); // allocate memory for the object LLVMValueRef pointer = codeGenerator.buildHeapAllocation(builder, nativeType); // store the object's run-time type information LLVMValueRef rtti; if (notNullFromType instanceof FunctionType) { // for function types, take the RTTI out of the value, don't generate it from the static type rtti = LLVM.LLVMBuildExtractValue(builder, notNullValue, 0, ""); } else { // make sure this type's RTTI doesn't reference any type parameters // otherwise, the RTTI would turn out wrong (due to the TypeParameterAccessor) and people would be able to cast // things in ways that would crash at runtime: e.g. (uint, T) to object to (uint, string) if T was string // to fix this, we set the RTTI to (uint, object), which is the only type that this should actually be castable to once it is an object rtti = rttiHelper.buildRTTICreation(builder, stripTypeParameters(notNullFromType), fromAccessor); } LLVMValueRef rttiPointer = rttiHelper.getRTTIPointer(builder, pointer); LLVM.LLVMBuildStore(builder, rtti, rttiPointer); // build the base change VFT, and store it as the object's VFT LLVMValueRef baseChangeVFT = virtualFunctionHandler.getBaseChangeObjectVFT(notNullFromType); LLVMValueRef vftElementPointer = virtualFunctionHandler.getFirstVirtualFunctionTablePointer(builder, pointer); LLVM.LLVMBuildStore(builder, baseChangeVFT, vftElementPointer); // store the value inside the object LLVMValueRef elementPointer = LLVM.LLVMBuildStructGEP(builder, pointer, 2, ""); notNullValue = convertTemporaryToStandard(builder, notNullValue, notNullFromType); LLVM.LLVMBuildStore(builder, notNullValue, elementPointer); // cast away the part of the type that contains the value LLVMValueRef notNullResult = LLVM.LLVMBuildBitCast(builder, pointer, findTemporaryType(to), ""); if (from.canBeNullable() && (to.isNullable() || (to instanceof WildcardType && to.canBeNullable()))) { LLVMBasicBlockRef endNotNullBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); LLVMValueRef resultPhi = LLVM.LLVMBuildPhi(builder, findTemporaryType(to), ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {LLVM.LLVMConstNull(findTemporaryType(to)), notNullResult}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, endNotNullBlock}; LLVM.LLVMAddIncoming(resultPhi, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length); return resultPhi; } return notNullResult; } if (from instanceof ObjectType || (from instanceof NamedType && ((NamedType) from).getResolvedTypeParameter() != null) || from instanceof WildcardType) { LLVMValueRef notNullValue = value; LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef notNullBlock = null; LLVMBasicBlockRef continuationBlock = null; if (from.canBeNullable()) { if (to.isNullable() || (to instanceof WildcardType && to.canBeNullable())) { continuationBlock = LLVM.LLVMAddBasicBlock(builder, "fromObjectConversionContinuation"); notNullBlock = LLVM.LLVMAddBasicBlock(builder, "fromObjectConversionNotNull"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); startBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildCondBr(builder, isNotNull, notNullBlock, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, notNullBlock); } else if (!skipRuntimeChecks) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } // skip run-time checking on this nullable -> not-null conversion, as we have already done them notNullValue = convertTemporary(builder, landingPadContainer, value, from, Type.findTypeWithNullability(from, false), true, fromAccessor, fromAccessor); } if (!skipRuntimeChecks) { LLVMValueRef isInstanceOfToType = rttiHelper.buildInstanceOfCheck(builder, landingPadContainer, notNullValue, Type.findTypeWithNullability(from, false), to, fromAccessor, toAccessor); LLVMBasicBlockRef instanceOfSuccessBlock = LLVM.LLVMAddBasicBlock(builder, "castObjectInstanceOfSuccess"); LLVMBasicBlockRef instanceOfFailureBlock = LLVM.LLVMAddBasicBlock(builder, "castObjectInstanceOfFailure"); LLVM.LLVMBuildCondBr(builder, isInstanceOfToType, instanceOfSuccessBlock, instanceOfFailureBlock); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfFailureBlock); buildThrowCastError(builder, landingPadContainer, from.toString(), to.toString(), null); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfSuccessBlock); } LLVMValueRef notNullResult; if ((to instanceof NamedType && ((NamedType) to).getResolvedTypeDefinition() instanceof ClassDefinition) || to instanceof ArrayType) { notNullResult = LLVM.LLVMBuildBitCast(builder, notNullValue, findTemporaryType(to), ""); } else { Type notNullToType = Type.findTypeWithNullability(to, false); LLVMTypeRef nativeType = LLVM.LLVMPointerType(findSpecialisedObjectType(notNullToType), 0); LLVMValueRef castedValue = LLVM.LLVMBuildBitCast(builder, notNullValue, nativeType, ""); LLVMValueRef elementPointer = LLVM.LLVMBuildStructGEP(builder, castedValue, 2, ""); notNullResult = convertStandardPointerToTemporary(builder, elementPointer, notNullToType); notNullResult = convertTemporary(builder, landingPadContainer, notNullResult, notNullToType, to, skipRuntimeChecks, toAccessor, toAccessor); } if (from.canBeNullable() && (to.isNullable() || (to instanceof WildcardType && to.canBeNullable()))) { LLVMBasicBlockRef endNotNullBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); LLVMValueRef resultPhi = LLVM.LLVMBuildPhi(builder, findTemporaryType(to), ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {LLVM.LLVMConstNull(findTemporaryType(to)), notNullResult}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, endNotNullBlock}; LLVM.LLVMAddIncoming(resultPhi, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length); return resultPhi; } return notNullResult; } throw new IllegalArgumentException("Unknown type conversion, from '" + from + "' to '" + to + "'"); } /** * Converts the specified value from the specified 'from' PrimitiveType to the specified 'to' PrimitiveType. * @param value - the value to convert * @param from - the PrimitiveType to convert from * @param to - the PrimitiveType to convert to * @return the converted value */ private LLVMValueRef convertPrimitiveType(LLVMBuilderRef builder, LLVMValueRef value, PrimitiveType from, PrimitiveType to) { PrimitiveTypeType fromType = from.getPrimitiveTypeType(); PrimitiveTypeType toType = to.getPrimitiveTypeType(); if (fromType == toType && from.canBeNullable() == to.canBeNullable()) { return value; } LLVMValueRef primitiveValue = value; if (from.canBeNullable()) { primitiveValue = LLVM.LLVMBuildExtractValue(builder, value, 1, ""); } // perform the conversion LLVMTypeRef toNativeType = findTemporaryType(new PrimitiveType(false, toType, null)); if (fromType == toType) { // do not alter primitiveValue, we only need to change the nullability } else if (fromType.isFloating() && toType.isFloating()) { primitiveValue = LLVM.LLVMBuildFPCast(builder, primitiveValue, toNativeType, ""); } else if (fromType.isFloating() && !toType.isFloating()) { if (toType.isSigned()) { primitiveValue = LLVM.LLVMBuildFPToSI(builder, primitiveValue, toNativeType, ""); } else { primitiveValue = LLVM.LLVMBuildFPToUI(builder, primitiveValue, toNativeType, ""); } } else if (!fromType.isFloating() && toType.isFloating()) { if (fromType.isSigned()) { primitiveValue = LLVM.LLVMBuildSIToFP(builder, primitiveValue, toNativeType, ""); } else { primitiveValue = LLVM.LLVMBuildUIToFP(builder, primitiveValue, toNativeType, ""); } } // both integer types, so perform a sign-extend, zero-extend, or truncation else if (fromType.getBitCount() > toType.getBitCount()) { primitiveValue = LLVM.LLVMBuildTrunc(builder, primitiveValue, toNativeType, ""); } else if (fromType.getBitCount() == toType.getBitCount() && fromType.isSigned() != toType.isSigned()) { primitiveValue = LLVM.LLVMBuildBitCast(builder, primitiveValue, toNativeType, ""); } // the value needs extending, so decide whether to do a sign-extend or a zero-extend based on whether the from type is signed else if (fromType.isSigned()) { primitiveValue = LLVM.LLVMBuildSExt(builder, primitiveValue, toNativeType, ""); } else { primitiveValue = LLVM.LLVMBuildZExt(builder, primitiveValue, toNativeType, ""); } // pack up the result before returning it if (to.canBeNullable()) { LLVMValueRef result = LLVM.LLVMGetUndef(findTemporaryType(to)); if (from.canBeNullable()) { LLVMValueRef isNotNullValue = LLVM.LLVMBuildExtractValue(builder, value, 0, ""); result = LLVM.LLVMBuildInsertValue(builder, result, isNotNullValue, 0, ""); } else { // set the flag to one to indicate that this value is not null result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, ""); } return LLVM.LLVMBuildInsertValue(builder, result, primitiveValue, 1, ""); } // return the primitive value directly, since the to type is not nullable return primitiveValue; } /** * Builds a conversion of the specified value from the specified type into the string type, by calling toString() or using the constant "null" string as necessary. * @param builder - the builder to build the conversion with * @param landingPadContainer - the LandingPadContainer containing the landing pad block for exceptions to be unwound to * @param value - the value to convert to a string, in a temporary type representation * @param type - the type of the value to convert, which can be any type except VoidType (including NullType and any nullable types) * @param typeAccessor - the TypeParameterAccessor to get the values of any TypeParameters inside 'type' from * @return an LLVMValueRef containing the string representation of value, in a standard type representation */ public LLVMValueRef convertToString(LLVMBuilderRef builder, LandingPadContainer landingPadContainer, LLVMValueRef value, Type type, TypeParameterAccessor typeAccessor) { if (type.isRuntimeEquivalent(SpecialTypeHandler.STRING_TYPE)) { return convertTemporaryToStandard(builder, value, SpecialTypeHandler.STRING_TYPE); } if (type instanceof NullType) { LLVMValueRef stringValue = codeGenerator.buildStringCreation(builder, landingPadContainer, "null"); return convertTemporaryToStandard(builder, stringValue, SpecialTypeHandler.STRING_TYPE); } LLVMValueRef notNullValue = value; Type notNullType = type; LLVMBasicBlockRef alternativeBlock = null; LLVMBasicBlockRef continuationBlock = null; if (type.canBeNullable()) { continuationBlock = LLVM.LLVMAddBasicBlock(builder, "stringConversionContinuation"); alternativeBlock = LLVM.LLVMAddBasicBlock(builder, "stringConversionNull"); LLVMBasicBlockRef conversionBlock = LLVM.LLVMAddBasicBlock(builder, "stringConversion"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, type); LLVM.LLVMBuildCondBr(builder, isNotNull, conversionBlock, alternativeBlock); LLVM.LLVMPositionBuilderAtEnd(builder, conversionBlock); notNullType = Type.findTypeWithNullability(type, false); notNullValue = convertTemporary(builder, landingPadContainer, value, type, notNullType, false, typeAccessor, typeAccessor); } MethodReference methodReference = notNullType.getMethod(new MethodReference(new BuiltinMethod(notNullType, BuiltinMethodType.TO_STRING), GenericTypeSpecialiser.IDENTITY_SPECIALISER).getDisambiguator()); if (methodReference == null) { throw new IllegalStateException("Type " + type + " does not have a 'toString()' method!"); } LLVMValueRef[] arguments = new LLVMValueRef[] {}; LLVMValueRef stringValue = buildMethodCall(builder, landingPadContainer, notNullValue, notNullType, methodReference, arguments, typeAccessor); if (type.canBeNullable()) { LLVMBasicBlockRef endConversionBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, alternativeBlock); LLVMValueRef alternativeStringValue = codeGenerator.buildStringCreation(builder, landingPadContainer, "null"); LLVMBasicBlockRef endAlternativeBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); LLVMValueRef phi = LLVM.LLVMBuildPhi(builder, findTemporaryType(SpecialTypeHandler.STRING_TYPE), ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {stringValue, alternativeStringValue}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {endConversionBlock, endAlternativeBlock}; LLVM.LLVMAddIncoming(phi, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length); return convertTemporaryToStandard(builder, phi, SpecialTypeHandler.STRING_TYPE); } return convertTemporaryToStandard(builder, stringValue, SpecialTypeHandler.STRING_TYPE); } /** * Converts the specified value of the specified type from a temporary type representation to a standard type representation, after converting it from 'fromType' to 'toType'. * @param builder - the LLVMBuilderRef to build instructions with * @param landingPadContainer - the LandingPadContainer containing the landing pad block for exceptions to be unwound to * @param value - the value to convert * @param fromType - the type to convert from * @param toType - the type to convert to * @param fromAccessor - the TypeParameterAccessor to get the values of any TypeParameters inside 'from' from * @param toAccessor - the TypeParameterAccessor to get the values of any TypeParameters inside 'to' from * @return the converted value */ public LLVMValueRef convertTemporaryToStandard(LLVMBuilderRef builder, LandingPadContainer landingPadContainer, LLVMValueRef value, Type fromType, Type toType, TypeParameterAccessor fromAccessor, TypeParameterAccessor toAccessor) { LLVMValueRef temporary = convertTemporary(builder, landingPadContainer, value, fromType, toType, false, fromAccessor, toAccessor); return convertTemporaryToStandard(builder, temporary, toType); } /** * Converts the specified value of the specified type from a temporary type representation to a standard type representation. * @param builder - the LLVMBuilderRef to build instructions with * @param value - the value to convert * @param type - the type to convert * @return the converted value */ public LLVMValueRef convertTemporaryToStandard(LLVMBuilderRef builder, LLVMValueRef value, Type type) { if (type instanceof ArrayType) { // the temporary and standard types are the same for ArrayTypes return value; } if (type instanceof FunctionType) { // the temporary and standard types are the same for FunctionTypes return value; } if (type instanceof NamedType) { if (((NamedType) type).getResolvedTypeParameter() != null) { // the temporary and standard types are the same for type parameters return value; } TypeDefinition typeDefinition = ((NamedType) type).getResolvedTypeDefinition(); if (typeDefinition instanceof ClassDefinition) { // the temporary and standard types are the same for class types return value; } else if (typeDefinition instanceof InterfaceDefinition) { // the temporary and standard types are the same for interface types return value; } else if (typeDefinition instanceof CompoundDefinition) { if (type.canBeNullable()) { LLVMTypeRef standardType = findStandardType(type); // we are converting from a pointer to a non-nullable compound into a possibly-null compound LLVMValueRef isNotNullValue = LLVM.LLVMBuildIsNotNull(builder, value, ""); // we need to branch on isNotNullValue, to decide whether to load from the pointer LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder); LLVMBasicBlockRef convertedBlock = LLVM.LLVMAddBasicBlock(builder, "compoundConverted"); LLVMBasicBlockRef loadBlock = LLVM.LLVMAddBasicBlock(builder, "compoundConversion"); LLVM.LLVMBuildCondBr(builder, isNotNullValue, loadBlock, convertedBlock); LLVM.LLVMPositionBuilderAtEnd(builder, loadBlock); LLVMValueRef loaded = LLVM.LLVMBuildLoad(builder, value, ""); LLVMValueRef notNullResult = LLVM.LLVMBuildInsertValue(builder, LLVM.LLVMGetUndef(standardType), LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, ""); notNullResult = LLVM.LLVMBuildInsertValue(builder, notNullResult, loaded, 1, ""); LLVM.LLVMBuildBr(builder, convertedBlock); LLVM.LLVMPositionBuilderAtEnd(builder, convertedBlock); LLVMValueRef phi = LLVM.LLVMBuildPhi(builder, standardType, ""); LLVMValueRef nullResult = LLVM.LLVMConstNull(standardType); LLVMValueRef[] values = new LLVMValueRef[] {nullResult, notNullResult}; LLVMBasicBlockRef[] blocks = new LLVMBasicBlockRef[] {currentBlock, loadBlock}; LLVM.LLVMAddIncoming(phi, C.toNativePointerArray(values, false, true), C.toNativePointerArray(blocks, false, true), values.length); return phi; } // type is not nullable, so we can just load it directly return LLVM.LLVMBuildLoad(builder, value, ""); } } if (type instanceof NullType) { // the temporary and standard types are the same for NullTypes return value; } if (type instanceof ObjectType) { // the temporary and standard types are the same for ObjectTypes return value; } if (type instanceof PrimitiveType) { // the temporary and standard types are the same for PrimitiveTypes return value; } if (type instanceof TupleType) { boolean containsCompound = false; Queue<TupleType> typeQueue = new LinkedList<TupleType>(); typeQueue.add((TupleType) type); while (!typeQueue.isEmpty()) { TupleType currentType = typeQueue.poll(); for (Type subType : currentType.getSubTypes()) { if (subType instanceof TupleType) { typeQueue.add((TupleType) subType); } if (subType instanceof NamedType && ((NamedType) subType).getResolvedTypeDefinition() instanceof CompoundDefinition) { containsCompound = true; break; } } } if (!containsCompound) { // if this tuple does not contain any compound types (after an arbitrary degree of nesting), // then it does not need converting, as the standard and temporary representations are the same return value; } LLVMValueRef notNullValue = value; if (type.canBeNullable()) { notNullValue = LLVM.LLVMBuildExtractValue(builder, value, 1, ""); } LLVMValueRef resultNotNull = LLVM.LLVMGetUndef(findStandardType(Type.findTypeWithNullability(type, false))); Type[] subTypes = ((TupleType) type).getSubTypes(); for (int i = 0; i < subTypes.length; ++i) { LLVMValueRef extractedValue = LLVM.LLVMBuildExtractValue(builder, notNullValue, i, ""); LLVMValueRef convertedValue = convertTemporaryToStandard(builder, extractedValue, subTypes[i]); resultNotNull = LLVM.LLVMBuildInsertValue(builder, resultNotNull, convertedValue, i, ""); } if (type.canBeNullable()) { LLVMValueRef isNotNullValue = LLVM.LLVMBuildExtractValue(builder, value, 0, ""); LLVMValueRef result = LLVM.LLVMGetUndef(findStandardType(type)); result = LLVM.LLVMBuildInsertValue(builder, result, isNotNullValue, 0, ""); result = LLVM.LLVMBuildInsertValue(builder, result, resultNotNull, 1, ""); return result; } return resultNotNull; } if (type instanceof VoidType) { throw new IllegalArgumentException("VoidType has no standard representation"); } if (type instanceof WildcardType) { // the temporary and standard types are the same for WildcardTypes return value; } throw new IllegalArgumentException("Unknown type: " + type); } /** * Converts the specified value of the specified type from a standard type representation to a temporary type representation, before converting it from 'fromType' to 'toType'. * @param builder - the LLVMBuilderRef to build instructions with * @param landingPadContainer - the LandingPadContainer containing the landing pad block for exceptions to be unwound to * @param value - the value to convert * @param fromType - the type to convert from * @param toType - the type to convert to * @param fromAccessor - the TypeParameterAccessor to get the values of any TypeParameters inside 'from' from * @param toAccessor - the TypeParameterAccessor to get the values of any TypeParameters inside 'to' from * @return the converted value */ public LLVMValueRef convertStandardToTemporary(LLVMBuilderRef builder, LandingPadContainer landingPadContainer, LLVMValueRef value, Type fromType, Type toType, TypeParameterAccessor fromAccessor, TypeParameterAccessor toAccessor) { LLVMValueRef temporary = convertStandardToTemporary(builder, value, fromType); return convertTemporary(builder, landingPadContainer, temporary, fromType, toType, false, fromAccessor, toAccessor); } /** * Converts the specified value of the specified type from a standard type representation to a temporary type representation. * @param builder - the LLVMBuilderRef to build instructions with * @param value - the value to convert * @param type - the type to convert * @return the converted value */ public LLVMValueRef convertStandardToTemporary(LLVMBuilderRef builder, LLVMValueRef value, Type type) { if (type instanceof ArrayType) { // the temporary and standard types are the same for ArrayTypes return value; } if (type instanceof FunctionType) { // the temporary and standard types are the same for FunctionTypes return value; } if (type instanceof NamedType) { if (((NamedType) type).getResolvedTypeParameter() != null) { // the temporary and standard types are the same for type parameters return value; } TypeDefinition typeDefinition = ((NamedType) type).getResolvedTypeDefinition(); if (typeDefinition instanceof ClassDefinition) { // the temporary and standard types are the same for class types return value; } else if (typeDefinition instanceof InterfaceDefinition) { // the temporary and standard types are the same for interface types return value; } else if (typeDefinition instanceof CompoundDefinition) { LLVMValueRef notNullValue = value; if (type.canBeNullable()) { notNullValue = LLVM.LLVMBuildExtractValue(builder, value, 1, ""); } // find the type to alloca, which is the standard representation of a non-nullable version of this type // when we alloca this type, it becomes equivalent to the temporary type representation of this compound type (with any nullability) LLVMTypeRef allocaBaseType = findStandardType(Type.findTypeWithNullability(type, false)); LLVMValueRef alloca = LLVM.LLVMBuildAllocaInEntryBlock(builder, allocaBaseType, ""); LLVM.LLVMBuildStore(builder, notNullValue, alloca); if (type.canBeNullable()) { LLVMValueRef isNotNullValue = LLVM.LLVMBuildExtractValue(builder, value, 0, ""); return LLVM.LLVMBuildSelect(builder, isNotNullValue, alloca, LLVM.LLVMConstNull(findTemporaryType(type)), ""); } return alloca; } } if (type instanceof NullType) { // the temporary and standard types are the same for NullTypes return value; } if (type instanceof ObjectType) { // the temporary and standard types are the same for ObjectTypes return value; } if (type instanceof PrimitiveType) { // the temporary and standard types are the same for PrimitiveTypes return value; } if (type instanceof TupleType) { boolean containsCompound = false; Queue<TupleType> typeQueue = new LinkedList<TupleType>(); typeQueue.add((TupleType) type); while (!typeQueue.isEmpty()) { TupleType currentType = typeQueue.poll(); for (Type subType : currentType.getSubTypes()) { if (subType instanceof TupleType) { typeQueue.add((TupleType) subType); } if (subType instanceof NamedType && ((NamedType) subType).getResolvedTypeDefinition() instanceof CompoundDefinition) { containsCompound = true; break; } } } if (!containsCompound) { // if this tuple does not contain any compound types (after an arbitrary degree of nesting), // then it does not need converting, as the standard and temporary representations are the same return value; } LLVMValueRef notNullValue = value; if (type.canBeNullable()) { notNullValue = LLVM.LLVMBuildExtractValue(builder, value, 1, ""); } LLVMValueRef resultNotNull = LLVM.LLVMGetUndef(findTemporaryType(Type.findTypeWithNullability(type, false))); Type[] subTypes = ((TupleType) type).getSubTypes(); for (int i = 0; i < subTypes.length; ++i) { LLVMValueRef extractedValue = LLVM.LLVMBuildExtractValue(builder, notNullValue, i, ""); LLVMValueRef convertedValue = convertStandardToTemporary(builder, extractedValue, subTypes[i]); resultNotNull = LLVM.LLVMBuildInsertValue(builder, resultNotNull, convertedValue, i, ""); } if (type.canBeNullable()) { LLVMValueRef isNotNullValue = LLVM.LLVMBuildExtractValue(builder, value, 0, ""); LLVMValueRef result = LLVM.LLVMGetUndef(findTemporaryType(type)); result = LLVM.LLVMBuildInsertValue(builder, result, isNotNullValue, 0, ""); result = LLVM.LLVMBuildInsertValue(builder, result, resultNotNull, 1, ""); return result; } return resultNotNull; } if (type instanceof VoidType) { throw new IllegalArgumentException("VoidType has no temporary representation"); } if (type instanceof WildcardType) { // the temporary and standard types are the same for WildcardTypes return value; } throw new IllegalArgumentException("Unknown type: " + type); } /** * Converts the specified pointer to a value of the specified type from a pointer to a standard type representation to a temporary type representation, before converting it from 'fromType' to 'toType'. * @param builder - the LLVMBuilderRef to build instructions with * @param landingPadContainer - the LandingPadContainer containing the landing pad block for exceptions to be unwound to * @param pointer - the pointer to the value to convert * @param fromType - the type to convert from * @param toType - the type to convert to * @param fromAccessor - the TypeParameterAccessor to get the values of any TypeParameters inside 'from' from * @param toAccessor - the TypeParameterAccessor to get the values of any TypeParameters inside 'to' from * @return the converted value */ public LLVMValueRef convertStandardPointerToTemporary(LLVMBuilderRef builder, LandingPadContainer landingPadContainer, LLVMValueRef pointer, Type fromType, Type toType, TypeParameterAccessor fromAccessor, TypeParameterAccessor toAccessor) { LLVMValueRef temporary = convertStandardPointerToTemporary(builder, pointer, fromType); return convertTemporary(builder, landingPadContainer, temporary, fromType, toType, false, fromAccessor, toAccessor); } /** * Converts the specified pointer to a value of the specified type from a pointer to a standard type representation to a temporary type representation. * @param builder - the LLVMBuilderRef to build instructions with * @param value - the pointer to the value to convert * @param type - the type to convert * @return the converted value */ public LLVMValueRef convertStandardPointerToTemporary(LLVMBuilderRef builder, LLVMValueRef value, Type type) { if (type instanceof ArrayType) { // the temporary and standard types are the same for ArrayTypes return LLVM.LLVMBuildLoad(builder, value, ""); } if (type instanceof FunctionType) { // the temporary and standard types are the same for FunctionTypes return LLVM.LLVMBuildLoad(builder, value, ""); } if (type instanceof NamedType) { if (((NamedType) type).getResolvedTypeParameter() != null) { // the temporary and standard types are the same for type parameters return LLVM.LLVMBuildLoad(builder, value, ""); } TypeDefinition typeDefinition = ((NamedType) type).getResolvedTypeDefinition(); if (typeDefinition instanceof ClassDefinition) { // the temporary and standard types are the same for class types return LLVM.LLVMBuildLoad(builder, value, ""); } else if (typeDefinition instanceof InterfaceDefinition) { // the temporary and standard types are the same for interface types return LLVM.LLVMBuildLoad(builder, value, ""); } else if (typeDefinition instanceof CompoundDefinition) { if (type.canBeNullable()) { LLVMValueRef[] nullabilityIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false)}; LLVMValueRef isNotNullPointer = LLVM.LLVMBuildGEP(builder, value, C.toNativePointerArray(nullabilityIndices, false, true), nullabilityIndices.length, ""); LLVMValueRef isNotNullValue = LLVM.LLVMBuildLoad(builder, isNotNullPointer, ""); LLVMValueRef[] valueIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false)}; LLVMValueRef notNullValue = LLVM.LLVMBuildGEP(builder, value, C.toNativePointerArray(valueIndices, false, true), valueIndices.length, ""); return LLVM.LLVMBuildSelect(builder, isNotNullValue, notNullValue, LLVM.LLVMConstNull(findTemporaryType(type)), ""); } // the pointer to the standard non-nullable representation is the same as the temporary representation return value; } } if (type instanceof NullType) { // the temporary and standard types are the same for NullTypes return LLVM.LLVMBuildLoad(builder, value, ""); } if (type instanceof ObjectType) { // the temporary and standard types are the same for ObjectTypes return LLVM.LLVMBuildLoad(builder, value, ""); } if (type instanceof PrimitiveType) { // the temporary and standard types are the same for PrimitiveTypes return LLVM.LLVMBuildLoad(builder, value, ""); } if (type instanceof TupleType) { boolean containsCompound = false; Queue<TupleType> typeQueue = new LinkedList<TupleType>(); typeQueue.add((TupleType) type); while (!typeQueue.isEmpty()) { TupleType currentType = typeQueue.poll(); for (Type subType : currentType.getSubTypes()) { if (subType instanceof TupleType) { typeQueue.add((TupleType) subType); } if (subType instanceof NamedType && ((NamedType) subType).getResolvedTypeDefinition() instanceof CompoundDefinition) { containsCompound = true; break; } } } if (!containsCompound) { // if this tuple does not contain any compound types (after an arbitrary degree of nesting), // then it does not need converting, as the standard and temporary representations are the same return LLVM.LLVMBuildLoad(builder, value, ""); } LLVMValueRef isNotNullValue = null; LLVMValueRef notNullPointer = value; if (type.canBeNullable()) { LLVMValueRef[] nullabilityIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false)}; LLVMValueRef isNotNullPointer = LLVM.LLVMBuildGEP(builder, value, C.toNativePointerArray(nullabilityIndices, false, true), nullabilityIndices.length, ""); isNotNullValue = LLVM.LLVMBuildLoad(builder, isNotNullPointer, ""); LLVMValueRef[] valueIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false)}; notNullPointer = LLVM.LLVMBuildGEP(builder, value, C.toNativePointerArray(valueIndices, false, true), valueIndices.length, ""); } LLVMValueRef resultNotNull = LLVM.LLVMGetUndef(findTemporaryType(Type.findTypeWithNullability(type, false))); Type[] subTypes = ((TupleType) type).getSubTypes(); for (int i = 0; i < subTypes.length; ++i) { LLVMValueRef[] valueIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), i, false)}; LLVMValueRef valuePointer = LLVM.LLVMBuildGEP(builder, notNullPointer, C.toNativePointerArray(valueIndices, false, true), valueIndices.length, ""); LLVMValueRef convertedValue = convertStandardPointerToTemporary(builder, valuePointer, subTypes[i]); resultNotNull = LLVM.LLVMBuildInsertValue(builder, resultNotNull, convertedValue, i, ""); } if (type.canBeNullable()) { LLVMValueRef result = LLVM.LLVMGetUndef(findTemporaryType(type)); result = LLVM.LLVMBuildInsertValue(builder, result, isNotNullValue, 0, ""); result = LLVM.LLVMBuildInsertValue(builder, result, resultNotNull, 1, ""); return result; } return resultNotNull; } if (type instanceof VoidType) { throw new IllegalArgumentException("VoidType has no standard representation"); } if (type instanceof WildcardType) { // the temporary and standard types are the same for WildcardTypes return LLVM.LLVMBuildLoad(builder, value, ""); } throw new IllegalArgumentException("Unknown type: " + type); } }
false
true
public LLVMValueRef convertTemporary(LLVMBuilderRef builder, LandingPadContainer landingPadContainer, LLVMValueRef value, Type from, Type to, boolean skipRuntimeChecks, TypeParameterAccessor fromAccessor, TypeParameterAccessor toAccessor) { // Note concerning Type Parameters: // Sometimes, we will be at a boundary between two objects, such as a method call, converting from a type in one object's context to a type in another object's context. // For type parameters, you might expect this to cause a problem when the two type parameters are equivalent at compile time but are looked up in different TypeParameterAccessors at run time. // However, whenever we convert something at a type boundary, we always do a direct conversion from the real type (e.g. of a parameter) to the specialised type, where the only // difference is that the parameter has been specialised to the outer context. Because of this, we can know that if we have two equivalent TypeParameters, they must have // equivalent values in their respective mappers. if (from.isRuntimeEquivalent(to)) { return value; } if (from instanceof PrimitiveType && to instanceof PrimitiveType) { if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } return convertPrimitiveType(builder, value, (PrimitiveType) from, (PrimitiveType) to); } if (from instanceof ArrayType && to instanceof ArrayType) { // array casts are illegal unless the base types are the same, so they must have the same basic type if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } // immutability will be checked by the type checker, but it doesn't have any effect on the native type, so we do not need to do anything special here ArrayType fromArray = (ArrayType) from; // the run-time type of an array never includes any references to type parameters, so they need to be stripped here ArrayType toArray = (ArrayType) stripTypeParameters(to); boolean needsProxying = checkRequiresConversion(fromArray.getBaseType(), toArray.getBaseType(), true) || checkRequiresConversion(toArray.getBaseType(), fromArray.getBaseType(), true); if (needsProxying) { return buildProxyArrayConversion(builder, value, fromArray, toArray, fromAccessor, toAccessor); } return LLVM.LLVMBuildBitCast(builder, value, findTemporaryType(toArray), ""); } if (from instanceof FunctionType && to instanceof FunctionType) { // function casts are illegal unless the parameter and return types are the same, so they must have the same basic type if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } FunctionType fromFunction = (FunctionType) from; FunctionType toFunction = (FunctionType) to; // a cast from a non-immutable function to an immutable function type is impossible // so perform a run-time check that this constraint is not violated if (!skipRuntimeChecks && !fromFunction.isImmutable() && toFunction.isImmutable()) { // this is only allowed if the run-time type of value shows that it is immutable LLVMBasicBlockRef functionImmutabilityCheckContinueBlock = LLVM.LLVMAddBasicBlock(builder, "functionImmutabilityCheckContinue"); // if the value is nullable, allow null values to pass through (we've already checked the nullability) if (from.canBeNullable()) { LLVMBasicBlockRef functionImmutabilityCheckBlock = LLVM.LLVMAddBasicBlock(builder, "functionImmutabilityCheck"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); LLVM.LLVMBuildCondBr(builder, isNotNull, functionImmutabilityCheckBlock, functionImmutabilityCheckContinueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, functionImmutabilityCheckBlock); } LLVMValueRef runtimeTypeMatches = rttiHelper.buildInstanceOfCheck(builder, landingPadContainer, value, Type.findTypeWithNullability(from, false), to, fromAccessor, toAccessor); LLVMBasicBlockRef immutabilityCastFailure = LLVM.LLVMAddBasicBlock(builder, "functionImmutabilityCheckFailure"); LLVM.LLVMBuildCondBr(builder, runtimeTypeMatches, functionImmutabilityCheckContinueBlock, immutabilityCastFailure); LLVM.LLVMPositionBuilderAtEnd(builder, immutabilityCastFailure); buildThrowCastError(builder, landingPadContainer, from.toString(), to.toString(), "non-immutable functions cannot be cast to immutable"); LLVM.LLVMPositionBuilderAtEnd(builder, functionImmutabilityCheckContinueBlock); } // strip any type parameters from the 'to' type, so that the RTTI doesn't contain anything which could confuse things // if we tried to convert to object and back to another type, RTTI containing type parameters would cause breakages in the cast instanceof checks toFunction = (FunctionType) stripTypeParameters(toFunction); boolean needsProxying = checkRequiresConversion(toFunction.getReturnType(), fromFunction.getReturnType(), true); Type[] fromParamTypes = fromFunction.getParameterTypes(); Type[] toParamTypes = toFunction.getParameterTypes(); needsProxying |= fromParamTypes.length != toParamTypes.length; for (int i = 0; !needsProxying & i < fromParamTypes.length; ++i) { needsProxying |= checkRequiresConversion(fromParamTypes[i], toParamTypes[i], true); } if (needsProxying) { return buildFunctionProxyConversion(builder, value, fromFunction, toFunction, fromAccessor, toAccessor); } if (!fromFunction.isRuntimeEquivalent(toFunction)) { // repack the function, after bitcasting the function pointer LLVMValueRef rtti = LLVM.LLVMBuildExtractValue(builder, value, 0, ""); LLVMValueRef callee = LLVM.LLVMBuildExtractValue(builder, value, 1, ""); LLVMValueRef function = LLVM.LLVMBuildExtractValue(builder, value, 2, ""); function = LLVM.LLVMBuildBitCast(builder, function, findRawFunctionPointerType(toFunction), ""); LLVMValueRef result = LLVM.LLVMGetUndef(findTemporaryType(toFunction)); result = LLVM.LLVMBuildInsertValue(builder, result, rtti, 0, ""); result = LLVM.LLVMBuildInsertValue(builder, result, callee, 1, ""); result = LLVM.LLVMBuildInsertValue(builder, result, function, 2, ""); return result; } return value; } if (from instanceof NamedType && to instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof ClassDefinition && ((NamedType) to).getResolvedTypeDefinition() instanceof ClassDefinition) { if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } // check whether 'to' is a super-class of 'from' NamedType fromNamed = (NamedType) from; NamedType toNamed = (NamedType) to; GenericTypeSpecialiser genericTypeSpecialiser = new GenericTypeSpecialiser(fromNamed); boolean isInherited = false; for (NamedType t : fromNamed.getResolvedTypeDefinition().getInheritanceLinearisation()) { NamedType superType = (NamedType) genericTypeSpecialiser.getSpecialisedType(t); if (!(superType.getResolvedTypeDefinition() instanceof ClassDefinition) || superType.getResolvedTypeDefinition() != toNamed.getResolvedTypeDefinition()) { continue; } Type[] fromArguments = superType.getTypeArguments(); Type[] toArguments = toNamed.getTypeArguments(); if ((fromArguments == null) != (toArguments == null) || (fromArguments != null && fromArguments.length != toArguments.length)) { continue; } boolean argumentsMatch = true; for (int i = 0; fromArguments != null && i < fromArguments.length; ++i) { if (toArguments[i] instanceof WildcardType) { // the type argument of 'to' is a wildcard, so the super-type matches as long as it encompasses the current type argument if (!((WildcardType) toArguments[i]).encompasses(fromArguments[i])) { argumentsMatch = false; break; } } else if (!toArguments[i].isRuntimeEquivalent(fromArguments[i])) { argumentsMatch = false; break; } } if (argumentsMatch) { isInherited = true; break; } } if (!isInherited && !skipRuntimeChecks) { LLVMBasicBlockRef instanceOfContinueBlock = LLVM.LLVMAddBasicBlock(builder, "castInstanceOfCheckContinue"); if (from.canBeNullable()) { // if the value is null, then skip the check LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); LLVMBasicBlockRef instanceOfCheckBlock = LLVM.LLVMAddBasicBlock(builder, "castInstanceOfCheck"); LLVM.LLVMBuildCondBr(builder, isNotNull, instanceOfCheckBlock, instanceOfContinueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfCheckBlock); } LLVMValueRef runtimeTypeMatches = rttiHelper.buildInstanceOfCheck(builder, landingPadContainer, value, Type.findTypeWithNullability(from, false), to, fromAccessor, toAccessor); LLVMBasicBlockRef castFailureBlock = LLVM.LLVMAddBasicBlock(builder, "castFailure"); LLVM.LLVMBuildCondBr(builder, runtimeTypeMatches, instanceOfContinueBlock, castFailureBlock); LLVM.LLVMPositionBuilderAtEnd(builder, castFailureBlock); LLVMValueRef rttiPointer = rttiHelper.getRTTIPointer(builder, value); LLVMValueRef rtti = LLVM.LLVMBuildLoad(builder, rttiPointer, ""); LLVMValueRef classNameUbyteArray = rttiHelper.lookupNamedTypeName(builder, rtti); LLVMValueRef classNameString = codeGenerator.buildStringCreation(builder, landingPadContainer, classNameUbyteArray); buildThrowCastError(builder, landingPadContainer, classNameString, to.toString(), null); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfContinueBlock); } // both from and to are class types, and we have made sure that we can convert between them // so bitcast value to the new type return LLVM.LLVMBuildBitCast(builder, value, findTemporaryType(to), ""); } if (from instanceof NamedType && to instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof CompoundDefinition && ((NamedType) to).getResolvedTypeDefinition() instanceof CompoundDefinition) { // compound type casts are illegal unless the type definitions are the same, so they must have the same type definition if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } if (!skipRuntimeChecks && !from.isRuntimeEquivalent(to)) { LLVMBasicBlockRef instanceOfContinueBlock = LLVM.LLVMAddBasicBlock(builder, "castInstanceOfCheckContinue"); if (from.canBeNullable()) { // if the value is null, then skip the check LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); LLVMBasicBlockRef instanceOfCheckBlock = LLVM.LLVMAddBasicBlock(builder, "castInstanceOfCheck"); LLVM.LLVMBuildCondBr(builder, isNotNull, instanceOfCheckBlock, instanceOfContinueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfCheckBlock); } LLVMValueRef runtimeTypeMatches = rttiHelper.buildInstanceOfCheck(builder, landingPadContainer, value, Type.findTypeWithNullability(from, false), to, fromAccessor, toAccessor); LLVMBasicBlockRef castFailureBlock = LLVM.LLVMAddBasicBlock(builder, "castFailure"); LLVM.LLVMBuildCondBr(builder, runtimeTypeMatches, instanceOfContinueBlock, castFailureBlock); LLVM.LLVMPositionBuilderAtEnd(builder, castFailureBlock); buildThrowCastError(builder, landingPadContainer, from.toString(), to.toString(), null); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfContinueBlock); // both from and to are compound types, and we have made sure that we can convert between them // so bitcast value to the new type value = LLVM.LLVMBuildBitCast(builder, value, findTemporaryType(to), ""); } return value; } if (from instanceof NamedType && to instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof InterfaceDefinition && ((NamedType) to).getResolvedTypeDefinition() instanceof ClassDefinition) { ObjectType objectType = new ObjectType(from.canBeNullable(), false, null); // there are no type parameters inside objectType, so use a null TypeParameterAccessor TypeParameterAccessor nullAccessor = new TypeParameterAccessor(builder, rttiHelper); LLVMValueRef objectValue = convertTemporary(builder, landingPadContainer, value, from, objectType, skipRuntimeChecks, fromAccessor, nullAccessor); return convertTemporary(builder, landingPadContainer, objectValue, objectType, to, skipRuntimeChecks, nullAccessor, toAccessor); } if (from instanceof NamedType && to instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof ClassDefinition && ((NamedType) to).getResolvedTypeDefinition() instanceof InterfaceDefinition) { ClassDefinition classDefinition = (ClassDefinition) ((NamedType) from).getResolvedTypeDefinition(); GenericTypeSpecialiser genericTypeSpecialiser = new GenericTypeSpecialiser((NamedType) from); NamedType toNamed = (NamedType) to; NamedType foundType = null; for (NamedType t : classDefinition.getInheritanceLinearisation()) { NamedType superType = (NamedType) genericTypeSpecialiser.getSpecialisedType(t); // check whether superType matches toNamed // we cannot just remove modifiers and check for equivalence, because toNamed might have wildcard type arguments which match superType's type arguments if (toNamed.getResolvedTypeDefinition() != superType.getResolvedTypeDefinition()) { continue; } Type[] toTypeArguments = toNamed.getTypeArguments(); Type[] superTypeArguments = superType.getTypeArguments(); if (((toTypeArguments == null) != (superTypeArguments == null)) || (toTypeArguments != null && toTypeArguments.length != superTypeArguments.length)) { continue; } boolean argumentsMatch = true; for (int i = 0; argumentsMatch && toTypeArguments != null && i < toTypeArguments.length; ++i) { if (toTypeArguments[i] instanceof WildcardType) { argumentsMatch = ((WildcardType) toTypeArguments[i]).encompasses(superTypeArguments[i]); } else { argumentsMatch = toTypeArguments[i].isRuntimeEquivalent(superTypeArguments[i]); } } if (argumentsMatch) { // Note: we want the unspecialised version of the super-type here, so that it can be specialised at run-time to have the same type arguments as the run-time type of the class we are converting from // one point to consider is, if 'from' has wildcard type arguments, we want to set the interface's type argument RTTI pointers to their real values, not a '?' foundType = t; break; } } if (foundType != null) { if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef continueBlock = null; // make sure we don't do a second null check if this is a cast from nullable to not-nullable if (from.canBeNullable() && to.isNullable()) { startBlock = LLVM.LLVMGetInsertBlock(builder); continueBlock = LLVM.LLVMAddBasicBlock(builder, "toInterfaceContinuation"); LLVMBasicBlockRef convertBlock = LLVM.LLVMAddBasicBlock(builder, "toInterfaceConversion"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); LLVM.LLVMBuildCondBr(builder, isNotNull, convertBlock, continueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, convertBlock); } LLVMTypeRef resultNativeType = findStandardType(to); // we know exactly where the VFT is at compile time, so we don't need to search for it at run time, just look it up TypeParameterAccessor foundAccessor = new TypeParameterAccessor(builder, this, rttiHelper, classDefinition, value); LLVMValueRef vft = virtualFunctionHandler.getVirtualFunctionTable(builder, landingPadContainer, value, (NamedType) from, foundType, fromAccessor, foundAccessor); LLVMValueRef objectPointer = convertTemporary(builder, landingPadContainer, value, from, new ObjectType(from.canBeNullable(), false, null), skipRuntimeChecks, fromAccessor, new TypeParameterAccessor(builder, rttiHelper)); LLVMValueRef interfaceValue = LLVM.LLVMGetUndef(resultNativeType); interfaceValue = LLVM.LLVMBuildInsertValue(builder, interfaceValue, vft, 0, ""); interfaceValue = LLVM.LLVMBuildInsertValue(builder, interfaceValue, objectPointer, 1, ""); // fill in the interface's wildcard type argument RTTI values Type[] toTypeArguments = toNamed.getTypeArguments(); Type[] foundTypeArguments = foundType.getTypeArguments(); int wildcardIndex = 0; TypeParameterAccessor wildcardTypeParameterAccessor = new TypeParameterAccessor(builder, this, rttiHelper, classDefinition, value); for (int i = 0; toTypeArguments != null && i < toTypeArguments.length; ++i) { if (toTypeArguments[i] instanceof WildcardType) { LLVMValueRef rtti = rttiHelper.buildRTTICreation(builder, foundTypeArguments[i], wildcardTypeParameterAccessor); interfaceValue = LLVM.LLVMBuildInsertValue(builder, interfaceValue, rtti, 2 + wildcardIndex, ""); ++wildcardIndex; } } if (from.canBeNullable() && to.isNullable()) { LLVMBasicBlockRef endConvertBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continueBlock); LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, resultNativeType, ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {LLVM.LLVMConstNull(resultNativeType), interfaceValue}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, endConvertBlock}; LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length); return phiNode; } return interfaceValue; } } if (to instanceof NamedType && ((NamedType) to).getResolvedTypeDefinition() instanceof InterfaceDefinition) { LLVMValueRef objectValue = null; Type objectType = null; if (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof ClassDefinition) { objectType = new ObjectType(from.canBeNullable(), ((NamedType) from).isContextuallyImmutable(), null); objectValue = convertTemporary(builder, landingPadContainer, value, from, objectType, skipRuntimeChecks, fromAccessor, new TypeParameterAccessor(builder, rttiHelper)); } else if (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof InterfaceDefinition) { objectType = new ObjectType(from.canBeNullable(), ((NamedType) from).isContextuallyImmutable(), null); objectValue = convertTemporary(builder, landingPadContainer, value, from, objectType, skipRuntimeChecks, fromAccessor, new TypeParameterAccessor(builder, rttiHelper)); } else if (from instanceof ObjectType || from instanceof WildcardType) { objectType = from; objectValue = value; } if (objectValue != null) { if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef continueBlock = null; // make sure we don't do a second null check if this is a cast from nullable to not-nullable if (objectType.canBeNullable() && to.isNullable()) { startBlock = LLVM.LLVMGetInsertBlock(builder); continueBlock = LLVM.LLVMAddBasicBlock(builder, "toInterfaceContinuation"); LLVMBasicBlockRef convertBlock = LLVM.LLVMAddBasicBlock(builder, "toInterfaceConversion"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, objectValue, objectType); LLVM.LLVMBuildCondBr(builder, isNotNull, convertBlock, continueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, convertBlock); } LLVMTypeRef resultNativeType = findStandardType(to); NamedType toNamed = (NamedType) to; LLVMValueRef objectRTTIPtr = rttiHelper.getRTTIPointer(builder, objectValue); LLVMValueRef objectRTTI = LLVM.LLVMBuildLoad(builder, objectRTTIPtr, ""); LLVMValueRef typeLookupResult = rttiHelper.lookupInstanceSuperType(builder, objectRTTI, toNamed, toAccessor); LLVMValueRef vftPointer = LLVM.LLVMBuildExtractValue(builder, typeLookupResult, 1, ""); LLVMTypeRef vftPointerType = LLVM.LLVMPointerType(virtualFunctionHandler.getVFTType(toNamed.getResolvedTypeDefinition()), 0); vftPointer = LLVM.LLVMBuildBitCast(builder, vftPointer, vftPointerType, ""); LLVMValueRef vftPointerIsNotNull = LLVM.LLVMBuildIsNotNull(builder, vftPointer, ""); LLVMBasicBlockRef castSuccessBlock = LLVM.LLVMAddBasicBlock(builder, "toInterfaceCastSuccess"); LLVMBasicBlockRef castFailureBlock = LLVM.LLVMAddBasicBlock(builder, "toInterfaceCastFailure"); LLVM.LLVMBuildCondBr(builder, vftPointerIsNotNull, castSuccessBlock, castFailureBlock); LLVM.LLVMPositionBuilderAtEnd(builder, castFailureBlock); if ((from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof ClassDefinition) || (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof InterfaceDefinition)) { // if we're coming from a class or an interface, then we know that we can look up the real class name LLVMValueRef classNameUbyteArray = rttiHelper.lookupNamedTypeName(builder, objectRTTI); LLVMValueRef classNameString = codeGenerator.buildStringCreation(builder, landingPadContainer, classNameUbyteArray); buildThrowCastError(builder, landingPadContainer, classNameString, to.toString(), null); } else { buildThrowCastError(builder, landingPadContainer, from.toString(), to.toString(), "this object does not implement " + to); } LLVM.LLVMPositionBuilderAtEnd(builder, castSuccessBlock); LLVMValueRef interfaceValue = LLVM.LLVMGetUndef(resultNativeType); interfaceValue = LLVM.LLVMBuildInsertValue(builder, interfaceValue, vftPointer, 0, ""); interfaceValue = LLVM.LLVMBuildInsertValue(builder, interfaceValue, objectValue, 1, ""); Type[] toTypeArguments = toNamed.getTypeArguments(); TypeParameterAccessor interfaceTypeParameterAccessor = null; int wildcardIndex = 0; for (int i = 0; toTypeArguments != null && i < toTypeArguments.length; ++i) { if (toTypeArguments[i] instanceof WildcardType) { if (interfaceTypeParameterAccessor == null) { LLVMValueRef interfaceRTTIValue = LLVM.LLVMBuildExtractValue(builder, typeLookupResult, 0, ""); interfaceRTTIValue = LLVM.LLVMBuildBitCast(builder, interfaceRTTIValue, LLVM.LLVMPointerType(rttiHelper.getRTTIStructType(toNamed), 0), ""); interfaceTypeParameterAccessor = new TypeParameterAccessor(builder, rttiHelper, toNamed.getResolvedTypeDefinition(), rttiHelper.getNamedTypeArgumentMapper(builder, interfaceRTTIValue)); } // extract the type argument's RTTI from the interface RTTI value, by looking up the value of the type parameter at index i LLVMValueRef unspecialisedRTTI = interfaceTypeParameterAccessor.findTypeParameterRTTI(toNamed.getResolvedTypeDefinition().getTypeParameters()[i]); // specialise the extracted type argument to the same level as its concrete type // here we assume that if the interface's unspecialised RTTI in the type search list references a type parameter, then the concrete type of that object is a named type which defines that parameter LLVMValueRef objectNamedRTTI = LLVM.LLVMBuildBitCast(builder, objectRTTI, rttiHelper.getGenericNamedRTTIType(), ""); LLVMValueRef specialisedRTTI = rttiHelper.buildRTTISpecialisation(builder, unspecialisedRTTI, rttiHelper.getNamedTypeArgumentMapper(builder, objectNamedRTTI)); // store the new RTTI block inside the interface's value interfaceValue = LLVM.LLVMBuildInsertValue(builder, interfaceValue, specialisedRTTI, 2 + wildcardIndex, ""); ++wildcardIndex; } } if (objectType.canBeNullable() && to.isNullable()) { LLVMBasicBlockRef endConvertBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continueBlock); LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, resultNativeType, ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {LLVM.LLVMConstNull(resultNativeType), interfaceValue}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, endConvertBlock}; LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length); return phiNode; } return interfaceValue; } } if (from instanceof TupleType) { // check for a single-element-tuple extraction TupleType fromTuple = (TupleType) from; if (fromTuple.getSubTypes().length == 1 && fromTuple.getSubTypes()[0].isRuntimeEquivalent(to)) { if (from.canBeNullable()) { if (!skipRuntimeChecks) { // if from is nullable and value is null, then we need to throw a CastError here buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } // extract the value of the tuple from the nullable structure value = LLVM.LLVMBuildExtractValue(builder, value, 1, ""); } return LLVM.LLVMBuildExtractValue(builder, value, 0, ""); } } if (to instanceof TupleType) { // check for a single-element-tuple insertion TupleType toTuple = (TupleType) to; if (toTuple.getSubTypes().length == 1 && toTuple.getSubTypes()[0].isRuntimeEquivalent(from)) { LLVMValueRef tupledValue = LLVM.LLVMGetUndef(findTemporaryType(new TupleType(false, toTuple.getSubTypes(), null))); tupledValue = LLVM.LLVMBuildInsertValue(builder, tupledValue, value, 0, ""); if (to.isNullable()) { LLVMValueRef result = LLVM.LLVMGetUndef(findTemporaryType(to)); result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, ""); return LLVM.LLVMBuildInsertValue(builder, result, tupledValue, 1, ""); } return tupledValue; } } if (from instanceof TupleType && to instanceof TupleType) { if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } TupleType fromTuple = (TupleType) from; TupleType toTuple = (TupleType) to; Type[] fromSubTypes = fromTuple.getSubTypes(); Type[] toSubTypes = toTuple.getSubTypes(); if (fromSubTypes.length != toSubTypes.length) { throw new IllegalArgumentException("Cannot convert from a " + from + " to a " + to); } boolean subTypesEquivalent = true; for (int i = 0; i < fromSubTypes.length; ++i) { if (!fromSubTypes[i].isRuntimeEquivalent(toSubTypes[i])) { subTypesEquivalent = false; break; } } if (subTypesEquivalent) { // just convert the nullability if (from.canBeNullable() && !to.isNullable()) { // extract the value of the tuple from the nullable structure // (we have already done the associated null check above) return LLVM.LLVMBuildExtractValue(builder, value, 1, ""); } if (!from.canBeNullable() && to.isNullable()) { LLVMValueRef result = LLVM.LLVMGetUndef(findTemporaryType(to)); // set the flag to one to indicate that this value is not null result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, ""); return LLVM.LLVMBuildInsertValue(builder, result, value, 1, ""); } throw new IllegalArgumentException("Unable to convert from a " + from + " to a " + to + " - their sub types and nullability are equivalent, but the types themselves are not"); } LLVMValueRef isNotNullValue = null; LLVMValueRef tupleValue = value; if (from.canBeNullable()) { isNotNullValue = LLVM.LLVMBuildExtractValue(builder, value, 0, ""); tupleValue = LLVM.LLVMBuildExtractValue(builder, value, 1, ""); } LLVMValueRef currentValue = LLVM.LLVMGetUndef(findTemporaryType(toTuple)); for (int i = 0; i < fromSubTypes.length; i++) { LLVMValueRef current = LLVM.LLVMBuildExtractValue(builder, tupleValue, i, ""); LLVMValueRef converted = convertTemporary(builder, landingPadContainer, current, fromSubTypes[i], toSubTypes[i], skipRuntimeChecks, fromAccessor, toAccessor); currentValue = LLVM.LLVMBuildInsertValue(builder, currentValue, converted, i, ""); } if (to.isNullable()) { LLVMValueRef result = LLVM.LLVMGetUndef(findTemporaryType(to)); if (from.canBeNullable()) { result = LLVM.LLVMBuildInsertValue(builder, result, isNotNullValue, 0, ""); } else { // set the flag to one to indicate that this value is not null result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, ""); } return LLVM.LLVMBuildInsertValue(builder, result, currentValue, 1, ""); } // return the value directly, since the to type is not nullable return currentValue; } if ((from instanceof ObjectType || (from instanceof NamedType && ((NamedType) from).getResolvedTypeParameter() != null) || from instanceof WildcardType) && to instanceof ObjectType) { // object casts are always legal if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } // immutability will be checked by the type checker, and doesn't have any effect on the native type, so we do not need to do anything special here return value; } if (to instanceof ObjectType || (to instanceof NamedType && ((NamedType) to).getResolvedTypeParameter() != null) || to instanceof WildcardType) { // anything can convert to object if (from instanceof NullType) { if (!to.canBeNullable()) { throw new IllegalArgumentException("Cannot convert from NullType to a not-null object/type parameter/wildcard type"); } if (!skipRuntimeChecks && !to.isNullable() && !(to instanceof WildcardType && to.canBeNullable())) { // make sure to is actually nullable (if it is a TypeParameter, we can't check this at compile time) buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } return LLVM.LLVMConstNull(findTemporaryType(to)); } if (from instanceof ArrayType || (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof ClassDefinition) || (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof InterfaceDefinition) || (from instanceof NamedType && ((NamedType) from).getResolvedTypeParameter() != null) || from instanceof ObjectType || from instanceof WildcardType) { if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable() && !(to instanceof WildcardType && to.canBeNullable())) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } if (!skipRuntimeChecks && ((to instanceof NamedType && ((NamedType) to).getResolvedTypeParameter() != null) || to instanceof WildcardType)) { // build an instanceof check for the 'to' type LLVMBasicBlockRef continuationBlock = LLVM.LLVMAddBasicBlock(builder, "toTypeParamContinuation"); LLVMValueRef notNullValue = value; Type notNullFromType = Type.findTypeWithNullability(from, false); if (from.canBeNullable()) { // only do the instanceof check it if it is not null - if it is null then the conversion should succeed (if 'to' was nullable then we would already have failed) // if 'to' is not nullable, then we have already done the null check, so don't repeat it if (to.isNullable() || (to instanceof WildcardType && to.canBeNullable())) { LLVMBasicBlockRef notNullBlock = LLVM.LLVMAddBasicBlock(builder, "toTypeParamConversionNotNull"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); LLVM.LLVMBuildCondBr(builder, isNotNull, notNullBlock, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, notNullBlock); } // skip run-time checking on this nullable -> not-null conversion, as we have already done them notNullValue = convertTemporary(builder, landingPadContainer, value, from, notNullFromType, true, fromAccessor, fromAccessor); } LLVMValueRef isInstance = rttiHelper.buildInstanceOfCheck(builder, landingPadContainer, notNullValue, notNullFromType, to, fromAccessor, toAccessor); LLVMBasicBlockRef instanceOfFailureBlock = LLVM.LLVMAddBasicBlock(builder, "castToTypeParamInstanceOfFailure"); LLVM.LLVMBuildCondBr(builder, isInstance, continuationBlock, instanceOfFailureBlock); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfFailureBlock); buildThrowCastError(builder, landingPadContainer, from.toString(), to.toString(), null); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); } if (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof InterfaceDefinition) { // extract the object part of the interface's type return LLVM.LLVMBuildExtractValue(builder, value, 1, ""); } // object, class, type parameter, wildcard, and array types can be safely bitcast to object types return LLVM.LLVMBuildBitCast(builder, value, findTemporaryType(to), ""); } Type notNullFromType = Type.findTypeWithNullability(from, false); LLVMValueRef notNullValue = value; LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef notNullBlock; LLVMBasicBlockRef continuationBlock = null; if (from.canBeNullable()) { if (to.isNullable() || (to instanceof WildcardType && to.canBeNullable())) { continuationBlock = LLVM.LLVMAddBasicBlock(builder, "toObjectConversionContinuation"); notNullBlock = LLVM.LLVMAddBasicBlock(builder, "toObjectConversionNotNull"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); startBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildCondBr(builder, isNotNull, notNullBlock, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, notNullBlock); } else if (!skipRuntimeChecks) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } // skip run-time checking on this nullable -> not-null conversion, as we have already done them notNullValue = convertTemporary(builder, landingPadContainer, value, from, notNullFromType, true, fromAccessor, fromAccessor); } if (!skipRuntimeChecks && ((to instanceof NamedType && ((NamedType) to).getResolvedTypeParameter() != null) || to instanceof WildcardType)) { // do an instanceof check to make sure we are allowed to convert to this type parameter/wildcard LLVMValueRef isInstanceOfToType = rttiHelper.buildInstanceOfCheck(builder, landingPadContainer, notNullValue, notNullFromType, to, fromAccessor, toAccessor); LLVMBasicBlockRef instanceOfSuccessBlock = LLVM.LLVMAddBasicBlock(builder, "castObjectInstanceOfSuccess"); LLVMBasicBlockRef instanceOfFailureBlock = LLVM.LLVMAddBasicBlock(builder, "castObjectInstanceOfFailure"); LLVM.LLVMBuildCondBr(builder, isInstanceOfToType, instanceOfSuccessBlock, instanceOfFailureBlock); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfFailureBlock); buildThrowCastError(builder, landingPadContainer, from.toString(), to.toString(), null); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfSuccessBlock); } LLVMTypeRef nativeType = LLVM.LLVMPointerType(findSpecialisedObjectType(notNullFromType), 0); // allocate memory for the object LLVMValueRef pointer = codeGenerator.buildHeapAllocation(builder, nativeType); // store the object's run-time type information LLVMValueRef rtti; if (notNullFromType instanceof FunctionType) { // for function types, take the RTTI out of the value, don't generate it from the static type rtti = LLVM.LLVMBuildExtractValue(builder, notNullValue, 0, ""); } else { // make sure this type's RTTI doesn't reference any type parameters // otherwise, the RTTI would turn out wrong (due to the TypeParameterAccessor) and people would be able to cast // things in ways that would crash at runtime: e.g. (uint, T) to object to (uint, string) if T was string // to fix this, we set the RTTI to (uint, object), which is the only type that this should actually be castable to once it is an object rtti = rttiHelper.buildRTTICreation(builder, stripTypeParameters(notNullFromType), fromAccessor); } LLVMValueRef rttiPointer = rttiHelper.getRTTIPointer(builder, pointer); LLVM.LLVMBuildStore(builder, rtti, rttiPointer); // build the base change VFT, and store it as the object's VFT LLVMValueRef baseChangeVFT = virtualFunctionHandler.getBaseChangeObjectVFT(notNullFromType); LLVMValueRef vftElementPointer = virtualFunctionHandler.getFirstVirtualFunctionTablePointer(builder, pointer); LLVM.LLVMBuildStore(builder, baseChangeVFT, vftElementPointer); // store the value inside the object LLVMValueRef elementPointer = LLVM.LLVMBuildStructGEP(builder, pointer, 2, ""); notNullValue = convertTemporaryToStandard(builder, notNullValue, notNullFromType); LLVM.LLVMBuildStore(builder, notNullValue, elementPointer); // cast away the part of the type that contains the value LLVMValueRef notNullResult = LLVM.LLVMBuildBitCast(builder, pointer, findTemporaryType(to), ""); if (from.canBeNullable() && (to.isNullable() || (to instanceof WildcardType && to.canBeNullable()))) { LLVMBasicBlockRef endNotNullBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); LLVMValueRef resultPhi = LLVM.LLVMBuildPhi(builder, findTemporaryType(to), ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {LLVM.LLVMConstNull(findTemporaryType(to)), notNullResult}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, endNotNullBlock}; LLVM.LLVMAddIncoming(resultPhi, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length); return resultPhi; } return notNullResult; } if (from instanceof ObjectType || (from instanceof NamedType && ((NamedType) from).getResolvedTypeParameter() != null) || from instanceof WildcardType) { LLVMValueRef notNullValue = value; LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef notNullBlock = null; LLVMBasicBlockRef continuationBlock = null; if (from.canBeNullable()) { if (to.isNullable() || (to instanceof WildcardType && to.canBeNullable())) { continuationBlock = LLVM.LLVMAddBasicBlock(builder, "fromObjectConversionContinuation"); notNullBlock = LLVM.LLVMAddBasicBlock(builder, "fromObjectConversionNotNull"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); startBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildCondBr(builder, isNotNull, notNullBlock, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, notNullBlock); } else if (!skipRuntimeChecks) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } // skip run-time checking on this nullable -> not-null conversion, as we have already done them notNullValue = convertTemporary(builder, landingPadContainer, value, from, Type.findTypeWithNullability(from, false), true, fromAccessor, fromAccessor); } if (!skipRuntimeChecks) { LLVMValueRef isInstanceOfToType = rttiHelper.buildInstanceOfCheck(builder, landingPadContainer, notNullValue, Type.findTypeWithNullability(from, false), to, fromAccessor, toAccessor); LLVMBasicBlockRef instanceOfSuccessBlock = LLVM.LLVMAddBasicBlock(builder, "castObjectInstanceOfSuccess"); LLVMBasicBlockRef instanceOfFailureBlock = LLVM.LLVMAddBasicBlock(builder, "castObjectInstanceOfFailure"); LLVM.LLVMBuildCondBr(builder, isInstanceOfToType, instanceOfSuccessBlock, instanceOfFailureBlock); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfFailureBlock); buildThrowCastError(builder, landingPadContainer, from.toString(), to.toString(), null); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfSuccessBlock); } LLVMValueRef notNullResult; if ((to instanceof NamedType && ((NamedType) to).getResolvedTypeDefinition() instanceof ClassDefinition) || to instanceof ArrayType) { notNullResult = LLVM.LLVMBuildBitCast(builder, notNullValue, findTemporaryType(to), ""); } else { Type notNullToType = Type.findTypeWithNullability(to, false); LLVMTypeRef nativeType = LLVM.LLVMPointerType(findSpecialisedObjectType(notNullToType), 0); LLVMValueRef castedValue = LLVM.LLVMBuildBitCast(builder, notNullValue, nativeType, ""); LLVMValueRef elementPointer = LLVM.LLVMBuildStructGEP(builder, castedValue, 2, ""); notNullResult = convertStandardPointerToTemporary(builder, elementPointer, notNullToType); notNullResult = convertTemporary(builder, landingPadContainer, notNullResult, notNullToType, to, skipRuntimeChecks, toAccessor, toAccessor); } if (from.canBeNullable() && (to.isNullable() || (to instanceof WildcardType && to.canBeNullable()))) { LLVMBasicBlockRef endNotNullBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); LLVMValueRef resultPhi = LLVM.LLVMBuildPhi(builder, findTemporaryType(to), ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {LLVM.LLVMConstNull(findTemporaryType(to)), notNullResult}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, endNotNullBlock}; LLVM.LLVMAddIncoming(resultPhi, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length); return resultPhi; } return notNullResult; } throw new IllegalArgumentException("Unknown type conversion, from '" + from + "' to '" + to + "'"); }
public LLVMValueRef convertTemporary(LLVMBuilderRef builder, LandingPadContainer landingPadContainer, LLVMValueRef value, Type from, Type to, boolean skipRuntimeChecks, TypeParameterAccessor fromAccessor, TypeParameterAccessor toAccessor) { // Note concerning Type Parameters: // Sometimes, we will be at a boundary between two objects, such as a method call, converting from a type in one object's context to a type in another object's context. // For type parameters, you might expect this to cause a problem when the two type parameters are equivalent at compile time but are looked up in different TypeParameterAccessors at run time. // However, whenever we convert something at a type boundary, we always do a direct conversion from the real type (e.g. of a parameter) to the specialised type, where the only // difference is that the parameter has been specialised to the outer context. Because of this, we can know that if we have two equivalent TypeParameters, they must have // equivalent values in their respective mappers. if (from.isRuntimeEquivalent(to)) { return value; } if (from instanceof PrimitiveType && to instanceof PrimitiveType) { if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } return convertPrimitiveType(builder, value, (PrimitiveType) from, (PrimitiveType) to); } if (from instanceof ArrayType && to instanceof ArrayType) { // array casts are illegal unless the base types are the same, so they must have the same basic type if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } // immutability will be checked by the type checker, but it doesn't have any effect on the native type, so we do not need to do anything special here ArrayType fromArray = (ArrayType) from; // the run-time type of an array never includes any references to type parameters, so they need to be stripped here ArrayType toArray = (ArrayType) stripTypeParameters(to); boolean needsProxying = checkRequiresConversion(fromArray.getBaseType(), toArray.getBaseType(), true) || checkRequiresConversion(toArray.getBaseType(), fromArray.getBaseType(), true); if (needsProxying) { return buildProxyArrayConversion(builder, value, fromArray, toArray, fromAccessor, toAccessor); } return LLVM.LLVMBuildBitCast(builder, value, findTemporaryType(toArray), ""); } if (from instanceof FunctionType && to instanceof FunctionType) { // function casts are illegal unless the parameter and return types are the same, so they must have the same basic type if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } FunctionType fromFunction = (FunctionType) from; FunctionType toFunction = (FunctionType) to; // a cast from a non-immutable function to an immutable function type is impossible // so perform a run-time check that this constraint is not violated if (!skipRuntimeChecks && !fromFunction.isImmutable() && toFunction.isImmutable()) { // this is only allowed if the run-time type of value shows that it is immutable LLVMBasicBlockRef functionImmutabilityCheckContinueBlock = LLVM.LLVMAddBasicBlock(builder, "functionImmutabilityCheckContinue"); // if the value is nullable, allow null values to pass through (we've already checked the nullability) if (from.canBeNullable()) { LLVMBasicBlockRef functionImmutabilityCheckBlock = LLVM.LLVMAddBasicBlock(builder, "functionImmutabilityCheck"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); LLVM.LLVMBuildCondBr(builder, isNotNull, functionImmutabilityCheckBlock, functionImmutabilityCheckContinueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, functionImmutabilityCheckBlock); } LLVMValueRef runtimeTypeMatches = rttiHelper.buildInstanceOfCheck(builder, landingPadContainer, value, Type.findTypeWithNullability(from, false), to, fromAccessor, toAccessor); LLVMBasicBlockRef immutabilityCastFailure = LLVM.LLVMAddBasicBlock(builder, "functionImmutabilityCheckFailure"); LLVM.LLVMBuildCondBr(builder, runtimeTypeMatches, functionImmutabilityCheckContinueBlock, immutabilityCastFailure); LLVM.LLVMPositionBuilderAtEnd(builder, immutabilityCastFailure); buildThrowCastError(builder, landingPadContainer, from.toString(), to.toString(), "non-immutable functions cannot be cast to immutable"); LLVM.LLVMPositionBuilderAtEnd(builder, functionImmutabilityCheckContinueBlock); } // strip any type parameters from the 'to' type, so that the RTTI doesn't contain anything which could confuse things // if we tried to convert to object and back to another type, RTTI containing type parameters would cause breakages in the cast instanceof checks toFunction = (FunctionType) stripTypeParameters(toFunction); boolean needsProxying = checkRequiresConversion(toFunction.getReturnType(), fromFunction.getReturnType(), true); Type[] fromParamTypes = fromFunction.getParameterTypes(); Type[] toParamTypes = toFunction.getParameterTypes(); needsProxying |= fromParamTypes.length != toParamTypes.length; for (int i = 0; !needsProxying & i < fromParamTypes.length; ++i) { needsProxying |= checkRequiresConversion(fromParamTypes[i], toParamTypes[i], true); } if (needsProxying) { return buildFunctionProxyConversion(builder, value, fromFunction, toFunction, fromAccessor, toAccessor); } if (!fromFunction.isRuntimeEquivalent(toFunction)) { // repack the function, after bitcasting the function pointer LLVMValueRef rtti = LLVM.LLVMBuildExtractValue(builder, value, 0, ""); LLVMValueRef callee = LLVM.LLVMBuildExtractValue(builder, value, 1, ""); LLVMValueRef function = LLVM.LLVMBuildExtractValue(builder, value, 2, ""); function = LLVM.LLVMBuildBitCast(builder, function, findRawFunctionPointerType(toFunction), ""); LLVMValueRef result = LLVM.LLVMGetUndef(findTemporaryType(toFunction)); result = LLVM.LLVMBuildInsertValue(builder, result, rtti, 0, ""); result = LLVM.LLVMBuildInsertValue(builder, result, callee, 1, ""); result = LLVM.LLVMBuildInsertValue(builder, result, function, 2, ""); return result; } return value; } if (from instanceof NamedType && to instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof ClassDefinition && ((NamedType) to).getResolvedTypeDefinition() instanceof ClassDefinition) { if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } // check whether 'to' is a super-class of 'from' NamedType fromNamed = (NamedType) from; NamedType toNamed = (NamedType) to; GenericTypeSpecialiser genericTypeSpecialiser = new GenericTypeSpecialiser(fromNamed); boolean isInherited = false; for (NamedType t : fromNamed.getResolvedTypeDefinition().getInheritanceLinearisation()) { NamedType superType = (NamedType) genericTypeSpecialiser.getSpecialisedType(t); if (!(superType.getResolvedTypeDefinition() instanceof ClassDefinition) || superType.getResolvedTypeDefinition() != toNamed.getResolvedTypeDefinition()) { continue; } Type[] fromArguments = superType.getTypeArguments(); Type[] toArguments = toNamed.getTypeArguments(); if ((fromArguments == null) != (toArguments == null) || (fromArguments != null && fromArguments.length != toArguments.length)) { continue; } boolean argumentsMatch = true; for (int i = 0; fromArguments != null && i < fromArguments.length; ++i) { if (toArguments[i] instanceof WildcardType) { // the type argument of 'to' is a wildcard, so the super-type matches as long as it encompasses the current type argument if (!((WildcardType) toArguments[i]).encompasses(fromArguments[i])) { argumentsMatch = false; break; } } else if (!toArguments[i].isRuntimeEquivalent(fromArguments[i])) { argumentsMatch = false; break; } } if (argumentsMatch) { isInherited = true; break; } } if (!isInherited && !skipRuntimeChecks) { LLVMBasicBlockRef instanceOfContinueBlock = LLVM.LLVMAddBasicBlock(builder, "castInstanceOfCheckContinue"); if (from.canBeNullable()) { // if the value is null, then skip the check LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); LLVMBasicBlockRef instanceOfCheckBlock = LLVM.LLVMAddBasicBlock(builder, "castInstanceOfCheck"); LLVM.LLVMBuildCondBr(builder, isNotNull, instanceOfCheckBlock, instanceOfContinueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfCheckBlock); } LLVMValueRef runtimeTypeMatches = rttiHelper.buildInstanceOfCheck(builder, landingPadContainer, value, Type.findTypeWithNullability(from, false), to, fromAccessor, toAccessor); LLVMBasicBlockRef castFailureBlock = LLVM.LLVMAddBasicBlock(builder, "castFailure"); LLVM.LLVMBuildCondBr(builder, runtimeTypeMatches, instanceOfContinueBlock, castFailureBlock); LLVM.LLVMPositionBuilderAtEnd(builder, castFailureBlock); LLVMValueRef rttiPointer = rttiHelper.getRTTIPointer(builder, value); LLVMValueRef rtti = LLVM.LLVMBuildLoad(builder, rttiPointer, ""); LLVMValueRef classNameUbyteArray = rttiHelper.lookupNamedTypeName(builder, rtti); LLVMValueRef classNameString = codeGenerator.buildStringCreation(builder, landingPadContainer, classNameUbyteArray); buildThrowCastError(builder, landingPadContainer, classNameString, to.toString(), null); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfContinueBlock); } // both from and to are class types, and we have made sure that we can convert between them // so bitcast value to the new type return LLVM.LLVMBuildBitCast(builder, value, findTemporaryType(to), ""); } if (from instanceof NamedType && to instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof CompoundDefinition && ((NamedType) to).getResolvedTypeDefinition() instanceof CompoundDefinition) { // compound type casts are illegal unless the type definitions are the same, so they must have the same type definition if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } if (!skipRuntimeChecks && !from.isRuntimeEquivalent(to)) { LLVMBasicBlockRef instanceOfContinueBlock = LLVM.LLVMAddBasicBlock(builder, "castInstanceOfCheckContinue"); if (from.canBeNullable()) { // if the value is null, then skip the check LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); LLVMBasicBlockRef instanceOfCheckBlock = LLVM.LLVMAddBasicBlock(builder, "castInstanceOfCheck"); LLVM.LLVMBuildCondBr(builder, isNotNull, instanceOfCheckBlock, instanceOfContinueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfCheckBlock); } LLVMValueRef runtimeTypeMatches = rttiHelper.buildInstanceOfCheck(builder, landingPadContainer, value, Type.findTypeWithNullability(from, false), to, fromAccessor, toAccessor); LLVMBasicBlockRef castFailureBlock = LLVM.LLVMAddBasicBlock(builder, "castFailure"); LLVM.LLVMBuildCondBr(builder, runtimeTypeMatches, instanceOfContinueBlock, castFailureBlock); LLVM.LLVMPositionBuilderAtEnd(builder, castFailureBlock); buildThrowCastError(builder, landingPadContainer, from.toString(), to.toString(), null); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfContinueBlock); // both from and to are compound types, and we have made sure that we can convert between them // so bitcast value to the new type value = LLVM.LLVMBuildBitCast(builder, value, findTemporaryType(to), ""); } return value; } if (from instanceof NamedType && to instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof InterfaceDefinition && ((NamedType) to).getResolvedTypeDefinition() instanceof ClassDefinition) { ObjectType objectType = new ObjectType(from.canBeNullable(), false, null); // there are no type parameters inside objectType, so use a null TypeParameterAccessor TypeParameterAccessor nullAccessor = new TypeParameterAccessor(builder, rttiHelper); LLVMValueRef objectValue = convertTemporary(builder, landingPadContainer, value, from, objectType, skipRuntimeChecks, fromAccessor, nullAccessor); return convertTemporary(builder, landingPadContainer, objectValue, objectType, to, skipRuntimeChecks, nullAccessor, toAccessor); } if (from instanceof NamedType && to instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof ClassDefinition && ((NamedType) to).getResolvedTypeDefinition() instanceof InterfaceDefinition) { ClassDefinition classDefinition = (ClassDefinition) ((NamedType) from).getResolvedTypeDefinition(); GenericTypeSpecialiser genericTypeSpecialiser = new GenericTypeSpecialiser((NamedType) from); NamedType toNamed = (NamedType) to; NamedType foundType = null; NamedType specialisedFoundType = null; for (NamedType t : classDefinition.getInheritanceLinearisation()) { NamedType superType = (NamedType) genericTypeSpecialiser.getSpecialisedType(t); // check whether superType matches toNamed // we cannot just remove modifiers and check for equivalence, because toNamed might have wildcard type arguments which match superType's type arguments if (toNamed.getResolvedTypeDefinition() != superType.getResolvedTypeDefinition()) { continue; } Type[] toTypeArguments = toNamed.getTypeArguments(); Type[] superTypeArguments = superType.getTypeArguments(); if (((toTypeArguments == null) != (superTypeArguments == null)) || (toTypeArguments != null && toTypeArguments.length != superTypeArguments.length)) { continue; } boolean argumentsMatch = true; for (int i = 0; argumentsMatch && toTypeArguments != null && i < toTypeArguments.length; ++i) { if (toTypeArguments[i] instanceof WildcardType) { argumentsMatch = ((WildcardType) toTypeArguments[i]).encompasses(superTypeArguments[i]); } else { argumentsMatch = toTypeArguments[i].isRuntimeEquivalent(superTypeArguments[i]); } } if (argumentsMatch) { // Note: we want the unspecialised version of the super-type here, so that it can be specialised at run-time to have the same type arguments as the run-time type of the class we are converting from // one point to consider is, if 'from' has wildcard type arguments, we want to set the interface's type argument RTTI pointers to their real values, not a '?' foundType = t; specialisedFoundType = superType; break; } } if (foundType != null) { if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef continueBlock = null; // make sure we don't do a second null check if this is a cast from nullable to not-nullable if (from.canBeNullable() && to.isNullable()) { startBlock = LLVM.LLVMGetInsertBlock(builder); continueBlock = LLVM.LLVMAddBasicBlock(builder, "toInterfaceContinuation"); LLVMBasicBlockRef convertBlock = LLVM.LLVMAddBasicBlock(builder, "toInterfaceConversion"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); LLVM.LLVMBuildCondBr(builder, isNotNull, convertBlock, continueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, convertBlock); } LLVMTypeRef resultNativeType = findStandardType(to); // we know exactly where the VFT is at compile time, so we don't need to search for it at run time, just look it up TypeParameterAccessor foundAccessor = new TypeParameterAccessor(builder, this, rttiHelper, classDefinition, value); LLVMValueRef vft = virtualFunctionHandler.getVirtualFunctionTable(builder, landingPadContainer, value, (NamedType) from, specialisedFoundType, fromAccessor, foundAccessor); LLVMValueRef objectPointer = convertTemporary(builder, landingPadContainer, value, from, new ObjectType(from.canBeNullable(), false, null), skipRuntimeChecks, fromAccessor, new TypeParameterAccessor(builder, rttiHelper)); LLVMValueRef interfaceValue = LLVM.LLVMGetUndef(resultNativeType); interfaceValue = LLVM.LLVMBuildInsertValue(builder, interfaceValue, vft, 0, ""); interfaceValue = LLVM.LLVMBuildInsertValue(builder, interfaceValue, objectPointer, 1, ""); // fill in the interface's wildcard type argument RTTI values Type[] toTypeArguments = toNamed.getTypeArguments(); Type[] foundTypeArguments = foundType.getTypeArguments(); int wildcardIndex = 0; TypeParameterAccessor wildcardTypeParameterAccessor = new TypeParameterAccessor(builder, this, rttiHelper, classDefinition, value); for (int i = 0; toTypeArguments != null && i < toTypeArguments.length; ++i) { if (toTypeArguments[i] instanceof WildcardType) { LLVMValueRef rtti = rttiHelper.buildRTTICreation(builder, foundTypeArguments[i], wildcardTypeParameterAccessor); interfaceValue = LLVM.LLVMBuildInsertValue(builder, interfaceValue, rtti, 2 + wildcardIndex, ""); ++wildcardIndex; } } if (from.canBeNullable() && to.isNullable()) { LLVMBasicBlockRef endConvertBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continueBlock); LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, resultNativeType, ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {LLVM.LLVMConstNull(resultNativeType), interfaceValue}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, endConvertBlock}; LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length); return phiNode; } return interfaceValue; } } if (to instanceof NamedType && ((NamedType) to).getResolvedTypeDefinition() instanceof InterfaceDefinition) { LLVMValueRef objectValue = null; Type objectType = null; if (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof ClassDefinition) { objectType = new ObjectType(from.canBeNullable(), ((NamedType) from).isContextuallyImmutable(), null); objectValue = convertTemporary(builder, landingPadContainer, value, from, objectType, skipRuntimeChecks, fromAccessor, new TypeParameterAccessor(builder, rttiHelper)); } else if (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof InterfaceDefinition) { objectType = new ObjectType(from.canBeNullable(), ((NamedType) from).isContextuallyImmutable(), null); objectValue = convertTemporary(builder, landingPadContainer, value, from, objectType, skipRuntimeChecks, fromAccessor, new TypeParameterAccessor(builder, rttiHelper)); } else if (from instanceof ObjectType || from instanceof WildcardType) { objectType = from; objectValue = value; } if (objectValue != null) { if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef continueBlock = null; // make sure we don't do a second null check if this is a cast from nullable to not-nullable if (objectType.canBeNullable() && to.isNullable()) { startBlock = LLVM.LLVMGetInsertBlock(builder); continueBlock = LLVM.LLVMAddBasicBlock(builder, "toInterfaceContinuation"); LLVMBasicBlockRef convertBlock = LLVM.LLVMAddBasicBlock(builder, "toInterfaceConversion"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, objectValue, objectType); LLVM.LLVMBuildCondBr(builder, isNotNull, convertBlock, continueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, convertBlock); } LLVMTypeRef resultNativeType = findStandardType(to); NamedType toNamed = (NamedType) to; LLVMValueRef objectRTTIPtr = rttiHelper.getRTTIPointer(builder, objectValue); LLVMValueRef objectRTTI = LLVM.LLVMBuildLoad(builder, objectRTTIPtr, ""); LLVMValueRef typeLookupResult = rttiHelper.lookupInstanceSuperType(builder, objectRTTI, toNamed, toAccessor); LLVMValueRef vftPointer = LLVM.LLVMBuildExtractValue(builder, typeLookupResult, 1, ""); LLVMTypeRef vftPointerType = LLVM.LLVMPointerType(virtualFunctionHandler.getVFTType(toNamed.getResolvedTypeDefinition()), 0); vftPointer = LLVM.LLVMBuildBitCast(builder, vftPointer, vftPointerType, ""); LLVMValueRef vftPointerIsNotNull = LLVM.LLVMBuildIsNotNull(builder, vftPointer, ""); LLVMBasicBlockRef castSuccessBlock = LLVM.LLVMAddBasicBlock(builder, "toInterfaceCastSuccess"); LLVMBasicBlockRef castFailureBlock = LLVM.LLVMAddBasicBlock(builder, "toInterfaceCastFailure"); LLVM.LLVMBuildCondBr(builder, vftPointerIsNotNull, castSuccessBlock, castFailureBlock); LLVM.LLVMPositionBuilderAtEnd(builder, castFailureBlock); if ((from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof ClassDefinition) || (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof InterfaceDefinition)) { // if we're coming from a class or an interface, then we know that we can look up the real class name LLVMValueRef classNameUbyteArray = rttiHelper.lookupNamedTypeName(builder, objectRTTI); LLVMValueRef classNameString = codeGenerator.buildStringCreation(builder, landingPadContainer, classNameUbyteArray); buildThrowCastError(builder, landingPadContainer, classNameString, to.toString(), null); } else { buildThrowCastError(builder, landingPadContainer, from.toString(), to.toString(), "this object does not implement " + to); } LLVM.LLVMPositionBuilderAtEnd(builder, castSuccessBlock); LLVMValueRef interfaceValue = LLVM.LLVMGetUndef(resultNativeType); interfaceValue = LLVM.LLVMBuildInsertValue(builder, interfaceValue, vftPointer, 0, ""); interfaceValue = LLVM.LLVMBuildInsertValue(builder, interfaceValue, objectValue, 1, ""); Type[] toTypeArguments = toNamed.getTypeArguments(); TypeParameterAccessor interfaceTypeParameterAccessor = null; int wildcardIndex = 0; for (int i = 0; toTypeArguments != null && i < toTypeArguments.length; ++i) { if (toTypeArguments[i] instanceof WildcardType) { if (interfaceTypeParameterAccessor == null) { LLVMValueRef interfaceRTTIValue = LLVM.LLVMBuildExtractValue(builder, typeLookupResult, 0, ""); interfaceRTTIValue = LLVM.LLVMBuildBitCast(builder, interfaceRTTIValue, LLVM.LLVMPointerType(rttiHelper.getRTTIStructType(toNamed), 0), ""); interfaceTypeParameterAccessor = new TypeParameterAccessor(builder, rttiHelper, toNamed.getResolvedTypeDefinition(), rttiHelper.getNamedTypeArgumentMapper(builder, interfaceRTTIValue)); } // extract the type argument's RTTI from the interface RTTI value, by looking up the value of the type parameter at index i LLVMValueRef unspecialisedRTTI = interfaceTypeParameterAccessor.findTypeParameterRTTI(toNamed.getResolvedTypeDefinition().getTypeParameters()[i]); // specialise the extracted type argument to the same level as its concrete type // here we assume that if the interface's unspecialised RTTI in the type search list references a type parameter, then the concrete type of that object is a named type which defines that parameter LLVMValueRef objectNamedRTTI = LLVM.LLVMBuildBitCast(builder, objectRTTI, rttiHelper.getGenericNamedRTTIType(), ""); LLVMValueRef specialisedRTTI = rttiHelper.buildRTTISpecialisation(builder, unspecialisedRTTI, rttiHelper.getNamedTypeArgumentMapper(builder, objectNamedRTTI)); // store the new RTTI block inside the interface's value interfaceValue = LLVM.LLVMBuildInsertValue(builder, interfaceValue, specialisedRTTI, 2 + wildcardIndex, ""); ++wildcardIndex; } } if (objectType.canBeNullable() && to.isNullable()) { LLVMBasicBlockRef endConvertBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continueBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continueBlock); LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, resultNativeType, ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {LLVM.LLVMConstNull(resultNativeType), interfaceValue}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, endConvertBlock}; LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length); return phiNode; } return interfaceValue; } } if (from instanceof TupleType) { // check for a single-element-tuple extraction TupleType fromTuple = (TupleType) from; if (fromTuple.getSubTypes().length == 1 && fromTuple.getSubTypes()[0].isRuntimeEquivalent(to)) { if (from.canBeNullable()) { if (!skipRuntimeChecks) { // if from is nullable and value is null, then we need to throw a CastError here buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } // extract the value of the tuple from the nullable structure value = LLVM.LLVMBuildExtractValue(builder, value, 1, ""); } return LLVM.LLVMBuildExtractValue(builder, value, 0, ""); } } if (to instanceof TupleType) { // check for a single-element-tuple insertion TupleType toTuple = (TupleType) to; if (toTuple.getSubTypes().length == 1 && toTuple.getSubTypes()[0].isRuntimeEquivalent(from)) { LLVMValueRef tupledValue = LLVM.LLVMGetUndef(findTemporaryType(new TupleType(false, toTuple.getSubTypes(), null))); tupledValue = LLVM.LLVMBuildInsertValue(builder, tupledValue, value, 0, ""); if (to.isNullable()) { LLVMValueRef result = LLVM.LLVMGetUndef(findTemporaryType(to)); result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, ""); return LLVM.LLVMBuildInsertValue(builder, result, tupledValue, 1, ""); } return tupledValue; } } if (from instanceof TupleType && to instanceof TupleType) { if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } TupleType fromTuple = (TupleType) from; TupleType toTuple = (TupleType) to; Type[] fromSubTypes = fromTuple.getSubTypes(); Type[] toSubTypes = toTuple.getSubTypes(); if (fromSubTypes.length != toSubTypes.length) { throw new IllegalArgumentException("Cannot convert from a " + from + " to a " + to); } boolean subTypesEquivalent = true; for (int i = 0; i < fromSubTypes.length; ++i) { if (!fromSubTypes[i].isRuntimeEquivalent(toSubTypes[i])) { subTypesEquivalent = false; break; } } if (subTypesEquivalent) { // just convert the nullability if (from.canBeNullable() && !to.isNullable()) { // extract the value of the tuple from the nullable structure // (we have already done the associated null check above) return LLVM.LLVMBuildExtractValue(builder, value, 1, ""); } if (!from.canBeNullable() && to.isNullable()) { LLVMValueRef result = LLVM.LLVMGetUndef(findTemporaryType(to)); // set the flag to one to indicate that this value is not null result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, ""); return LLVM.LLVMBuildInsertValue(builder, result, value, 1, ""); } throw new IllegalArgumentException("Unable to convert from a " + from + " to a " + to + " - their sub types and nullability are equivalent, but the types themselves are not"); } LLVMValueRef isNotNullValue = null; LLVMValueRef tupleValue = value; if (from.canBeNullable()) { isNotNullValue = LLVM.LLVMBuildExtractValue(builder, value, 0, ""); tupleValue = LLVM.LLVMBuildExtractValue(builder, value, 1, ""); } LLVMValueRef currentValue = LLVM.LLVMGetUndef(findTemporaryType(toTuple)); for (int i = 0; i < fromSubTypes.length; i++) { LLVMValueRef current = LLVM.LLVMBuildExtractValue(builder, tupleValue, i, ""); LLVMValueRef converted = convertTemporary(builder, landingPadContainer, current, fromSubTypes[i], toSubTypes[i], skipRuntimeChecks, fromAccessor, toAccessor); currentValue = LLVM.LLVMBuildInsertValue(builder, currentValue, converted, i, ""); } if (to.isNullable()) { LLVMValueRef result = LLVM.LLVMGetUndef(findTemporaryType(to)); if (from.canBeNullable()) { result = LLVM.LLVMBuildInsertValue(builder, result, isNotNullValue, 0, ""); } else { // set the flag to one to indicate that this value is not null result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, ""); } return LLVM.LLVMBuildInsertValue(builder, result, currentValue, 1, ""); } // return the value directly, since the to type is not nullable return currentValue; } if ((from instanceof ObjectType || (from instanceof NamedType && ((NamedType) from).getResolvedTypeParameter() != null) || from instanceof WildcardType) && to instanceof ObjectType) { // object casts are always legal if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable()) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } // immutability will be checked by the type checker, and doesn't have any effect on the native type, so we do not need to do anything special here return value; } if (to instanceof ObjectType || (to instanceof NamedType && ((NamedType) to).getResolvedTypeParameter() != null) || to instanceof WildcardType) { // anything can convert to object if (from instanceof NullType) { if (!to.canBeNullable()) { throw new IllegalArgumentException("Cannot convert from NullType to a not-null object/type parameter/wildcard type"); } if (!skipRuntimeChecks && !to.isNullable() && !(to instanceof WildcardType && to.canBeNullable())) { // make sure to is actually nullable (if it is a TypeParameter, we can't check this at compile time) buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } return LLVM.LLVMConstNull(findTemporaryType(to)); } if (from instanceof ArrayType || (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof ClassDefinition) || (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof InterfaceDefinition) || (from instanceof NamedType && ((NamedType) from).getResolvedTypeParameter() != null) || from instanceof ObjectType || from instanceof WildcardType) { if (!skipRuntimeChecks && from.canBeNullable() && !to.isNullable() && !(to instanceof WildcardType && to.canBeNullable())) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } if (!skipRuntimeChecks && ((to instanceof NamedType && ((NamedType) to).getResolvedTypeParameter() != null) || to instanceof WildcardType)) { // build an instanceof check for the 'to' type LLVMBasicBlockRef continuationBlock = LLVM.LLVMAddBasicBlock(builder, "toTypeParamContinuation"); LLVMValueRef notNullValue = value; Type notNullFromType = Type.findTypeWithNullability(from, false); if (from.canBeNullable()) { // only do the instanceof check it if it is not null - if it is null then the conversion should succeed (if 'to' was nullable then we would already have failed) // if 'to' is not nullable, then we have already done the null check, so don't repeat it if (to.isNullable() || (to instanceof WildcardType && to.canBeNullable())) { LLVMBasicBlockRef notNullBlock = LLVM.LLVMAddBasicBlock(builder, "toTypeParamConversionNotNull"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); LLVM.LLVMBuildCondBr(builder, isNotNull, notNullBlock, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, notNullBlock); } // skip run-time checking on this nullable -> not-null conversion, as we have already done them notNullValue = convertTemporary(builder, landingPadContainer, value, from, notNullFromType, true, fromAccessor, fromAccessor); } LLVMValueRef isInstance = rttiHelper.buildInstanceOfCheck(builder, landingPadContainer, notNullValue, notNullFromType, to, fromAccessor, toAccessor); LLVMBasicBlockRef instanceOfFailureBlock = LLVM.LLVMAddBasicBlock(builder, "castToTypeParamInstanceOfFailure"); LLVM.LLVMBuildCondBr(builder, isInstance, continuationBlock, instanceOfFailureBlock); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfFailureBlock); buildThrowCastError(builder, landingPadContainer, from.toString(), to.toString(), null); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); } if (from instanceof NamedType && ((NamedType) from).getResolvedTypeDefinition() instanceof InterfaceDefinition) { // extract the object part of the interface's type return LLVM.LLVMBuildExtractValue(builder, value, 1, ""); } // object, class, type parameter, wildcard, and array types can be safely bitcast to object types return LLVM.LLVMBuildBitCast(builder, value, findTemporaryType(to), ""); } Type notNullFromType = Type.findTypeWithNullability(from, false); LLVMValueRef notNullValue = value; LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef notNullBlock; LLVMBasicBlockRef continuationBlock = null; if (from.canBeNullable()) { if (to.isNullable() || (to instanceof WildcardType && to.canBeNullable())) { continuationBlock = LLVM.LLVMAddBasicBlock(builder, "toObjectConversionContinuation"); notNullBlock = LLVM.LLVMAddBasicBlock(builder, "toObjectConversionNotNull"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); startBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildCondBr(builder, isNotNull, notNullBlock, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, notNullBlock); } else if (!skipRuntimeChecks) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } // skip run-time checking on this nullable -> not-null conversion, as we have already done them notNullValue = convertTemporary(builder, landingPadContainer, value, from, notNullFromType, true, fromAccessor, fromAccessor); } if (!skipRuntimeChecks && ((to instanceof NamedType && ((NamedType) to).getResolvedTypeParameter() != null) || to instanceof WildcardType)) { // do an instanceof check to make sure we are allowed to convert to this type parameter/wildcard LLVMValueRef isInstanceOfToType = rttiHelper.buildInstanceOfCheck(builder, landingPadContainer, notNullValue, notNullFromType, to, fromAccessor, toAccessor); LLVMBasicBlockRef instanceOfSuccessBlock = LLVM.LLVMAddBasicBlock(builder, "castObjectInstanceOfSuccess"); LLVMBasicBlockRef instanceOfFailureBlock = LLVM.LLVMAddBasicBlock(builder, "castObjectInstanceOfFailure"); LLVM.LLVMBuildCondBr(builder, isInstanceOfToType, instanceOfSuccessBlock, instanceOfFailureBlock); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfFailureBlock); buildThrowCastError(builder, landingPadContainer, from.toString(), to.toString(), null); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfSuccessBlock); } LLVMTypeRef nativeType = LLVM.LLVMPointerType(findSpecialisedObjectType(notNullFromType), 0); // allocate memory for the object LLVMValueRef pointer = codeGenerator.buildHeapAllocation(builder, nativeType); // store the object's run-time type information LLVMValueRef rtti; if (notNullFromType instanceof FunctionType) { // for function types, take the RTTI out of the value, don't generate it from the static type rtti = LLVM.LLVMBuildExtractValue(builder, notNullValue, 0, ""); } else { // make sure this type's RTTI doesn't reference any type parameters // otherwise, the RTTI would turn out wrong (due to the TypeParameterAccessor) and people would be able to cast // things in ways that would crash at runtime: e.g. (uint, T) to object to (uint, string) if T was string // to fix this, we set the RTTI to (uint, object), which is the only type that this should actually be castable to once it is an object rtti = rttiHelper.buildRTTICreation(builder, stripTypeParameters(notNullFromType), fromAccessor); } LLVMValueRef rttiPointer = rttiHelper.getRTTIPointer(builder, pointer); LLVM.LLVMBuildStore(builder, rtti, rttiPointer); // build the base change VFT, and store it as the object's VFT LLVMValueRef baseChangeVFT = virtualFunctionHandler.getBaseChangeObjectVFT(notNullFromType); LLVMValueRef vftElementPointer = virtualFunctionHandler.getFirstVirtualFunctionTablePointer(builder, pointer); LLVM.LLVMBuildStore(builder, baseChangeVFT, vftElementPointer); // store the value inside the object LLVMValueRef elementPointer = LLVM.LLVMBuildStructGEP(builder, pointer, 2, ""); notNullValue = convertTemporaryToStandard(builder, notNullValue, notNullFromType); LLVM.LLVMBuildStore(builder, notNullValue, elementPointer); // cast away the part of the type that contains the value LLVMValueRef notNullResult = LLVM.LLVMBuildBitCast(builder, pointer, findTemporaryType(to), ""); if (from.canBeNullable() && (to.isNullable() || (to instanceof WildcardType && to.canBeNullable()))) { LLVMBasicBlockRef endNotNullBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); LLVMValueRef resultPhi = LLVM.LLVMBuildPhi(builder, findTemporaryType(to), ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {LLVM.LLVMConstNull(findTemporaryType(to)), notNullResult}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, endNotNullBlock}; LLVM.LLVMAddIncoming(resultPhi, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length); return resultPhi; } return notNullResult; } if (from instanceof ObjectType || (from instanceof NamedType && ((NamedType) from).getResolvedTypeParameter() != null) || from instanceof WildcardType) { LLVMValueRef notNullValue = value; LLVMBasicBlockRef startBlock = null; LLVMBasicBlockRef notNullBlock = null; LLVMBasicBlockRef continuationBlock = null; if (from.canBeNullable()) { if (to.isNullable() || (to instanceof WildcardType && to.canBeNullable())) { continuationBlock = LLVM.LLVMAddBasicBlock(builder, "fromObjectConversionContinuation"); notNullBlock = LLVM.LLVMAddBasicBlock(builder, "fromObjectConversionNotNull"); LLVMValueRef isNotNull = codeGenerator.buildNullCheck(builder, value, from); startBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildCondBr(builder, isNotNull, notNullBlock, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, notNullBlock); } else if (!skipRuntimeChecks) { buildCastNullCheck(builder, landingPadContainer, value, from, to, toAccessor); } // skip run-time checking on this nullable -> not-null conversion, as we have already done them notNullValue = convertTemporary(builder, landingPadContainer, value, from, Type.findTypeWithNullability(from, false), true, fromAccessor, fromAccessor); } if (!skipRuntimeChecks) { LLVMValueRef isInstanceOfToType = rttiHelper.buildInstanceOfCheck(builder, landingPadContainer, notNullValue, Type.findTypeWithNullability(from, false), to, fromAccessor, toAccessor); LLVMBasicBlockRef instanceOfSuccessBlock = LLVM.LLVMAddBasicBlock(builder, "castObjectInstanceOfSuccess"); LLVMBasicBlockRef instanceOfFailureBlock = LLVM.LLVMAddBasicBlock(builder, "castObjectInstanceOfFailure"); LLVM.LLVMBuildCondBr(builder, isInstanceOfToType, instanceOfSuccessBlock, instanceOfFailureBlock); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfFailureBlock); buildThrowCastError(builder, landingPadContainer, from.toString(), to.toString(), null); LLVM.LLVMPositionBuilderAtEnd(builder, instanceOfSuccessBlock); } LLVMValueRef notNullResult; if ((to instanceof NamedType && ((NamedType) to).getResolvedTypeDefinition() instanceof ClassDefinition) || to instanceof ArrayType) { notNullResult = LLVM.LLVMBuildBitCast(builder, notNullValue, findTemporaryType(to), ""); } else { Type notNullToType = Type.findTypeWithNullability(to, false); LLVMTypeRef nativeType = LLVM.LLVMPointerType(findSpecialisedObjectType(notNullToType), 0); LLVMValueRef castedValue = LLVM.LLVMBuildBitCast(builder, notNullValue, nativeType, ""); LLVMValueRef elementPointer = LLVM.LLVMBuildStructGEP(builder, castedValue, 2, ""); notNullResult = convertStandardPointerToTemporary(builder, elementPointer, notNullToType); notNullResult = convertTemporary(builder, landingPadContainer, notNullResult, notNullToType, to, skipRuntimeChecks, toAccessor, toAccessor); } if (from.canBeNullable() && (to.isNullable() || (to instanceof WildcardType && to.canBeNullable()))) { LLVMBasicBlockRef endNotNullBlock = LLVM.LLVMGetInsertBlock(builder); LLVM.LLVMBuildBr(builder, continuationBlock); LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock); LLVMValueRef resultPhi = LLVM.LLVMBuildPhi(builder, findTemporaryType(to), ""); LLVMValueRef[] incomingValues = new LLVMValueRef[] {LLVM.LLVMConstNull(findTemporaryType(to)), notNullResult}; LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, endNotNullBlock}; LLVM.LLVMAddIncoming(resultPhi, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length); return resultPhi; } return notNullResult; } throw new IllegalArgumentException("Unknown type conversion, from '" + from + "' to '" + to + "'"); }
diff --git a/src/com/ianhanniballake/recipebook/ui/RecipeListActivity.java b/src/com/ianhanniballake/recipebook/ui/RecipeListActivity.java index c39c205..e014974 100644 --- a/src/com/ianhanniballake/recipebook/ui/RecipeListActivity.java +++ b/src/com/ianhanniballake/recipebook/ui/RecipeListActivity.java @@ -1,159 +1,160 @@ package com.ianhanniballake.recipebook.ui; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.provider.BaseColumns; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.SimpleCursorAdapter; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Toast; import com.ianhanniballake.recipebook.R; import com.ianhanniballake.recipebook.provider.RecipeContract; /** * An activity representing a list of Recipes. This activity has different presentations for handset and tablet-size * devices. On handsets, the activity presents a list of items, which when touched, lead to a * {@link RecipeDetailActivity} representing item details. On tablets, the activity presents the list of items and item * details side-by-side using two vertical panes. */ public class RecipeListActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor> { /** * The serialization (saved instance state) Bundle key representing the activated item position. Only used on * tablets. */ private static final String STATE_ACTIVATED_POSITION = "activated_position"; /** * Adapter to display the list's data */ private SimpleCursorAdapter adapter; /** * The current activated item position. Only used on tablets. */ private int mActivatedPosition = AdapterView.INVALID_POSITION; /** * Whether or not the activity is in two-pane mode, i.e. running on a tablet device. */ boolean mTwoPane; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe_list); final AbsListView listView = (AbsListView) findViewById(android.R.id.list); if (findViewById(R.id.recipe_detail_summary) != null) { // The detail container view will be present only in the large-screen layouts (res/values-large and // res/values-sw600dp). If this view is present, then the activity should be in two-pane mode. mTwoPane = true; // In two-pane mode, list items should be given the 'activated' state when touched. listView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE); } - adapter = new SimpleCursorAdapter(this, R.layout.list_item_recipe, null, - new String[] { RecipeContract.Recipes.COLUMN_NAME_TITLE }, new int[] { R.id.title }, 0); + adapter = new SimpleCursorAdapter(this, R.layout.list_item_recipe, null, new String[] { + RecipeContract.Recipes.COLUMN_NAME_TITLE, RecipeContract.Recipes.COLUMN_NAME_DESCRIPTION }, new int[] { + R.id.title, R.id.description }, 0); listView.setAdapter(adapter); listView.setEmptyView(findViewById(android.R.id.empty)); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { if (mTwoPane) { // In two-pane mode, show the detail view in this activity by adding or replacing the detail // fragment using a fragment transaction. final RecipeDetailSummaryFragment summaryFragment = RecipeDetailSummaryFragment.newInstance(id); final RecipeDetailIngredientFragment ingredientFragment = RecipeDetailIngredientFragment .newInstance(id); final RecipeDetailInstructionFragment instructionFragment = RecipeDetailInstructionFragment .newInstance(id); final FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.recipe_detail_summary, summaryFragment); ft.replace(R.id.recipe_detail_ingredient, ingredientFragment); ft.replace(R.id.recipe_detail_instruction, instructionFragment); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } else { // In single-pane mode, simply start the detail activity for the selected item ID. final Intent detailIntent = new Intent(RecipeListActivity.this, RecipeDetailActivity.class); detailIntent.putExtra(BaseColumns._ID, id); startActivity(detailIntent); } } }); getSupportLoaderManager().initLoader(0, null, this); if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) { final int position = savedInstanceState.getInt(STATE_ACTIVATED_POSITION); if (position == AdapterView.INVALID_POSITION) listView.setItemChecked(mActivatedPosition, false); else listView.setItemChecked(position, true); mActivatedPosition = position; } // TODO: If exposing deep links into your app, handle intents here. } @Override public Loader<Cursor> onCreateLoader(final int id, final Bundle args) { return new CursorLoader(this, RecipeContract.Recipes.CONTENT_ID_URI_BASE, null, null, null, null); } @Override public boolean onCreateOptionsMenu(final Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.fragment_recipe_list, menu); return true; } @Override public void onLoaderReset(final Loader<Cursor> loader) { adapter.swapCursor(null); } @Override public void onLoadFinished(final Loader<Cursor> loader, final Cursor data) { adapter.swapCursor(data); } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.add: // TODO: Launch Add Activity Toast.makeText(this, R.string.add, Toast.LENGTH_SHORT).show(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onSaveInstanceState(final Bundle outState) { super.onSaveInstanceState(outState); if (mActivatedPosition != AdapterView.INVALID_POSITION) // Serialize and persist the activated item position. outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition); } }
true
true
protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe_list); final AbsListView listView = (AbsListView) findViewById(android.R.id.list); if (findViewById(R.id.recipe_detail_summary) != null) { // The detail container view will be present only in the large-screen layouts (res/values-large and // res/values-sw600dp). If this view is present, then the activity should be in two-pane mode. mTwoPane = true; // In two-pane mode, list items should be given the 'activated' state when touched. listView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE); } adapter = new SimpleCursorAdapter(this, R.layout.list_item_recipe, null, new String[] { RecipeContract.Recipes.COLUMN_NAME_TITLE }, new int[] { R.id.title }, 0); listView.setAdapter(adapter); listView.setEmptyView(findViewById(android.R.id.empty)); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { if (mTwoPane) { // In two-pane mode, show the detail view in this activity by adding or replacing the detail // fragment using a fragment transaction. final RecipeDetailSummaryFragment summaryFragment = RecipeDetailSummaryFragment.newInstance(id); final RecipeDetailIngredientFragment ingredientFragment = RecipeDetailIngredientFragment .newInstance(id); final RecipeDetailInstructionFragment instructionFragment = RecipeDetailInstructionFragment .newInstance(id); final FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.recipe_detail_summary, summaryFragment); ft.replace(R.id.recipe_detail_ingredient, ingredientFragment); ft.replace(R.id.recipe_detail_instruction, instructionFragment); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } else { // In single-pane mode, simply start the detail activity for the selected item ID. final Intent detailIntent = new Intent(RecipeListActivity.this, RecipeDetailActivity.class); detailIntent.putExtra(BaseColumns._ID, id); startActivity(detailIntent); } } }); getSupportLoaderManager().initLoader(0, null, this); if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) { final int position = savedInstanceState.getInt(STATE_ACTIVATED_POSITION); if (position == AdapterView.INVALID_POSITION) listView.setItemChecked(mActivatedPosition, false); else listView.setItemChecked(position, true); mActivatedPosition = position; } // TODO: If exposing deep links into your app, handle intents here. }
protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe_list); final AbsListView listView = (AbsListView) findViewById(android.R.id.list); if (findViewById(R.id.recipe_detail_summary) != null) { // The detail container view will be present only in the large-screen layouts (res/values-large and // res/values-sw600dp). If this view is present, then the activity should be in two-pane mode. mTwoPane = true; // In two-pane mode, list items should be given the 'activated' state when touched. listView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE); } adapter = new SimpleCursorAdapter(this, R.layout.list_item_recipe, null, new String[] { RecipeContract.Recipes.COLUMN_NAME_TITLE, RecipeContract.Recipes.COLUMN_NAME_DESCRIPTION }, new int[] { R.id.title, R.id.description }, 0); listView.setAdapter(adapter); listView.setEmptyView(findViewById(android.R.id.empty)); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { if (mTwoPane) { // In two-pane mode, show the detail view in this activity by adding or replacing the detail // fragment using a fragment transaction. final RecipeDetailSummaryFragment summaryFragment = RecipeDetailSummaryFragment.newInstance(id); final RecipeDetailIngredientFragment ingredientFragment = RecipeDetailIngredientFragment .newInstance(id); final RecipeDetailInstructionFragment instructionFragment = RecipeDetailInstructionFragment .newInstance(id); final FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.recipe_detail_summary, summaryFragment); ft.replace(R.id.recipe_detail_ingredient, ingredientFragment); ft.replace(R.id.recipe_detail_instruction, instructionFragment); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } else { // In single-pane mode, simply start the detail activity for the selected item ID. final Intent detailIntent = new Intent(RecipeListActivity.this, RecipeDetailActivity.class); detailIntent.putExtra(BaseColumns._ID, id); startActivity(detailIntent); } } }); getSupportLoaderManager().initLoader(0, null, this); if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) { final int position = savedInstanceState.getInt(STATE_ACTIVATED_POSITION); if (position == AdapterView.INVALID_POSITION) listView.setItemChecked(mActivatedPosition, false); else listView.setItemChecked(position, true); mActivatedPosition = position; } // TODO: If exposing deep links into your app, handle intents here. }
diff --git a/sitebricks-mail/src/main/java/com/google/sitebricks/mail/MailClientHandler.java b/sitebricks-mail/src/main/java/com/google/sitebricks/mail/MailClientHandler.java index 40b788e..9abe108 100644 --- a/sitebricks-mail/src/main/java/com/google/sitebricks/mail/MailClientHandler.java +++ b/sitebricks-mail/src/main/java/com/google/sitebricks/mail/MailClientHandler.java @@ -1,249 +1,250 @@ package com.google.sitebricks.mail; import com.google.common.collect.Sets; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A command/response handler for a single mail connection/user. * * @author [email protected] (Dhanji R. Prasanna) */ class MailClientHandler extends SimpleChannelHandler { private static final Logger log = LoggerFactory.getLogger(MailClientHandler.class); public static final String CAPABILITY_PREFIX = "* CAPABILITY"; static final Pattern COMMAND_FAILED_REGEX = Pattern.compile("^[.] (NO|BAD) (.*)", Pattern.CASE_INSENSITIVE); static final Pattern SYSTEM_ERROR_REGEX = Pattern.compile("[*]\\s*bye\\s*system\\s*error\\s*", Pattern.CASE_INSENSITIVE); static final Pattern IDLE_ENDED_REGEX = Pattern.compile(".* OK IDLE terminated \\(success\\)\\s*", Pattern.CASE_INSENSITIVE); static final Pattern IDLE_EXISTS_REGEX = Pattern.compile("\\* (\\d+) exists\\s*", Pattern.CASE_INSENSITIVE); static final Pattern IDLE_EXPUNGE_REGEX = Pattern.compile("\\* (\\d+) expunge\\s*", Pattern.CASE_INSENSITIVE); private final Idler idler; private final CountDownLatch loginComplete = new CountDownLatch(2); private volatile boolean isLoggedIn = false; private volatile List<String> capabilities; private volatile FolderObserver observer; final AtomicBoolean idling = new AtomicBoolean(); // Panic button. private volatile boolean halt = false; private final LinkedBlockingDeque<Error> errorStack = new LinkedBlockingDeque<Error>(); private final Queue<CommandCompletion> completions = new ConcurrentLinkedQueue<CommandCompletion>(); private volatile PushedData pushedData; public MailClientHandler(Idler idler) { this.idler = idler; } private static class PushedData { final Set<Integer> pushAdds = Collections.synchronizedSet(Sets.<Integer>newHashSet()); final Set<Integer> pushRemoves = Collections.synchronizedSet(Sets.<Integer>newHashSet()); } // DO NOT synchronize! public void enqueue(CommandCompletion completion) { completions.add(completion); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { String message = e.getMessage().toString(); + log.trace(message); if (SYSTEM_ERROR_REGEX.matcher(message).matches()) { log.warn("Disconnected by IMAP Server due to system error: {}", message); disconnectAbnormally(message); return; } try { if (halt) { log.error("This mail client is halted but continues to receive messages, ignoring!"); return; } if (message.startsWith(CAPABILITY_PREFIX)) { this.capabilities = Arrays.asList( message.substring(CAPABILITY_PREFIX.length() + 1).split("[ ]+")); loginComplete.countDown(); return; } if (!isLoggedIn) { if (message.matches("[.] OK .*@.* \\(Success\\)")) { // TODO make case-insensitive log.trace("Authentication success."); isLoggedIn = true; loginComplete.countDown(); } else { Matcher matcher = COMMAND_FAILED_REGEX.matcher(message); if (matcher.find()) { - log.trace("Authentication failed"); + log.trace("Authentication failed due to: {}", message); loginComplete.countDown(); errorStack.push(new Error(null /* logins have no completion */, extractError(matcher))); } } // TODO handle auth failed return; } // Copy to local var as the value can change underneath us. FolderObserver observer = this.observer; if (idling.get()) { message = message.toLowerCase(); if (IDLE_ENDED_REGEX.matcher(message).matches()) { idling.compareAndSet(true, false); // Now fire the events. PushedData data = pushedData; pushedData = null; observer.changed(data.pushAdds.isEmpty() ? null : data.pushAdds, data.pushRemoves.isEmpty() ? null : data.pushRemoves); return; } // Queue up any push notifications to publish to the client in a second. Matcher existsMatcher = IDLE_EXISTS_REGEX.matcher(message); boolean matched = false; if (existsMatcher.matches()) { int number = Integer.parseInt(existsMatcher.group(1)); pushedData.pushAdds.add(number); pushedData.pushRemoves.remove(number); matched = true; } else { Matcher expungeMatcher = IDLE_EXPUNGE_REGEX.matcher(message); if (expungeMatcher.matches()) { int number = Integer.parseInt(expungeMatcher.group(1)); pushedData.pushRemoves.add(number); pushedData.pushAdds.remove(number); matched = true; } } // Stop idling, when we get the stopped idling message we can publish shit. if (matched) { idler.done(); return; } } complete(message); } catch (Exception ex) { CommandCompletion completion = completions.poll(); if (completion != null) completion.error(message, ex); else log.error("Strange exception during mail processing (no completions available!): {}", message, ex); throw ex; } } private void disconnectAbnormally(String message) { halt(); // Disconnect abnormally. The user code should reconnect using the mail client. errorStack.push(new Error(completions.poll(), message)); idler.disconnect(); } private String extractError(Matcher matcher) { return (matcher.groupCount()) > 1 ? matcher.group(2) : matcher.group(); } /** * This is synchronized to ensure that we process the queue serially. */ private synchronized void complete(String message) { // This is a weird problem with writing stuff while idling. Need to investigate it more, but // for now just ignore it. if ("* BAD [CLIENTBUG] Invalid tag".equalsIgnoreCase(message)) { log.warn("Invalid tag warning, ignored."); return; } CommandCompletion completion = completions.peek(); if (completion == null) { if ("+ idling".equalsIgnoreCase(message)) log.debug("IDLE entered."); else log.error("Could not find the completion for message {} (Was it ever issued?)", message); return; } if (completion.complete(message)) { completions.poll(); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { log.error("Exception caught! Disconnecting...", e.getCause()); disconnectAbnormally(e.getCause().getMessage()); } public List<String> getCapabilities() { return capabilities; } boolean awaitLogin() { try { loginComplete.await(); return errorStack.isEmpty(); // No error == success! } catch (InterruptedException e) { throw new RuntimeException("Interruption while awaiting server login", e); } } Error lastError() { return errorStack.pop(); } /** * Registers a FolderObserver to receive events happening with a particular * folder. Typically an IMAP IDLE feature. If called multiple times, will * overwrite the currently set observer. */ void observe(FolderObserver observer) { this.observer = observer; pushedData = new PushedData(); } void halt() { halt = true; } public boolean isHalted() { return halt; } static class Error { final CommandCompletion completion; final String error; Error(CommandCompletion completion, String error) { this.completion = completion; this.error = error; } } }
false
true
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { String message = e.getMessage().toString(); if (SYSTEM_ERROR_REGEX.matcher(message).matches()) { log.warn("Disconnected by IMAP Server due to system error: {}", message); disconnectAbnormally(message); return; } try { if (halt) { log.error("This mail client is halted but continues to receive messages, ignoring!"); return; } if (message.startsWith(CAPABILITY_PREFIX)) { this.capabilities = Arrays.asList( message.substring(CAPABILITY_PREFIX.length() + 1).split("[ ]+")); loginComplete.countDown(); return; } if (!isLoggedIn) { if (message.matches("[.] OK .*@.* \\(Success\\)")) { // TODO make case-insensitive log.trace("Authentication success."); isLoggedIn = true; loginComplete.countDown(); } else { Matcher matcher = COMMAND_FAILED_REGEX.matcher(message); if (matcher.find()) { log.trace("Authentication failed"); loginComplete.countDown(); errorStack.push(new Error(null /* logins have no completion */, extractError(matcher))); } } // TODO handle auth failed return; } // Copy to local var as the value can change underneath us. FolderObserver observer = this.observer; if (idling.get()) { message = message.toLowerCase(); if (IDLE_ENDED_REGEX.matcher(message).matches()) { idling.compareAndSet(true, false); // Now fire the events. PushedData data = pushedData; pushedData = null; observer.changed(data.pushAdds.isEmpty() ? null : data.pushAdds, data.pushRemoves.isEmpty() ? null : data.pushRemoves); return; } // Queue up any push notifications to publish to the client in a second. Matcher existsMatcher = IDLE_EXISTS_REGEX.matcher(message); boolean matched = false; if (existsMatcher.matches()) { int number = Integer.parseInt(existsMatcher.group(1)); pushedData.pushAdds.add(number); pushedData.pushRemoves.remove(number); matched = true; } else { Matcher expungeMatcher = IDLE_EXPUNGE_REGEX.matcher(message); if (expungeMatcher.matches()) { int number = Integer.parseInt(expungeMatcher.group(1)); pushedData.pushRemoves.add(number); pushedData.pushAdds.remove(number); matched = true; } } // Stop idling, when we get the stopped idling message we can publish shit. if (matched) { idler.done(); return; } } complete(message); } catch (Exception ex) { CommandCompletion completion = completions.poll(); if (completion != null) completion.error(message, ex); else log.error("Strange exception during mail processing (no completions available!): {}", message, ex); throw ex; } }
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { String message = e.getMessage().toString(); log.trace(message); if (SYSTEM_ERROR_REGEX.matcher(message).matches()) { log.warn("Disconnected by IMAP Server due to system error: {}", message); disconnectAbnormally(message); return; } try { if (halt) { log.error("This mail client is halted but continues to receive messages, ignoring!"); return; } if (message.startsWith(CAPABILITY_PREFIX)) { this.capabilities = Arrays.asList( message.substring(CAPABILITY_PREFIX.length() + 1).split("[ ]+")); loginComplete.countDown(); return; } if (!isLoggedIn) { if (message.matches("[.] OK .*@.* \\(Success\\)")) { // TODO make case-insensitive log.trace("Authentication success."); isLoggedIn = true; loginComplete.countDown(); } else { Matcher matcher = COMMAND_FAILED_REGEX.matcher(message); if (matcher.find()) { log.trace("Authentication failed due to: {}", message); loginComplete.countDown(); errorStack.push(new Error(null /* logins have no completion */, extractError(matcher))); } } // TODO handle auth failed return; } // Copy to local var as the value can change underneath us. FolderObserver observer = this.observer; if (idling.get()) { message = message.toLowerCase(); if (IDLE_ENDED_REGEX.matcher(message).matches()) { idling.compareAndSet(true, false); // Now fire the events. PushedData data = pushedData; pushedData = null; observer.changed(data.pushAdds.isEmpty() ? null : data.pushAdds, data.pushRemoves.isEmpty() ? null : data.pushRemoves); return; } // Queue up any push notifications to publish to the client in a second. Matcher existsMatcher = IDLE_EXISTS_REGEX.matcher(message); boolean matched = false; if (existsMatcher.matches()) { int number = Integer.parseInt(existsMatcher.group(1)); pushedData.pushAdds.add(number); pushedData.pushRemoves.remove(number); matched = true; } else { Matcher expungeMatcher = IDLE_EXPUNGE_REGEX.matcher(message); if (expungeMatcher.matches()) { int number = Integer.parseInt(expungeMatcher.group(1)); pushedData.pushRemoves.add(number); pushedData.pushAdds.remove(number); matched = true; } } // Stop idling, when we get the stopped idling message we can publish shit. if (matched) { idler.done(); return; } } complete(message); } catch (Exception ex) { CommandCompletion completion = completions.poll(); if (completion != null) completion.error(message, ex); else log.error("Strange exception during mail processing (no completions available!): {}", message, ex); throw ex; } }
diff --git a/src/com/fsck/k9/mail/transport/SmtpTransport.java b/src/com/fsck/k9/mail/transport/SmtpTransport.java index 29d8c18c..4a60c6cb 100644 --- a/src/com/fsck/k9/mail/transport/SmtpTransport.java +++ b/src/com/fsck/k9/mail/transport/SmtpTransport.java @@ -1,613 +1,615 @@ package com.fsck.k9.mail.transport; import android.util.Log; import com.fsck.k9.K9; import com.fsck.k9.mail.*; import com.fsck.k9.mail.Message.RecipientType; import com.fsck.k9.mail.filter.Base64; import com.fsck.k9.mail.filter.EOLConvertingOutputStream; import com.fsck.k9.mail.filter.LineWrapOutputStream; import com.fsck.k9.mail.filter.PeekableInputStream; import com.fsck.k9.mail.filter.SmtpDataStuffing; import com.fsck.k9.mail.store.TrustManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.TrustManager; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.*; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import org.apache.commons.codec.binary.Hex; import java.util.ArrayList; import java.util.List; public class SmtpTransport extends Transport { public static final int CONNECTION_SECURITY_NONE = 0; public static final int CONNECTION_SECURITY_TLS_OPTIONAL = 1; public static final int CONNECTION_SECURITY_TLS_REQUIRED = 2; public static final int CONNECTION_SECURITY_SSL_REQUIRED = 3; public static final int CONNECTION_SECURITY_SSL_OPTIONAL = 4; String mHost; int mPort; String mUsername; String mPassword; String mAuthType; int mConnectionSecurity; boolean mSecure; Socket mSocket; PeekableInputStream mIn; OutputStream mOut; private boolean m8bitEncodingAllowed; /** * smtp://user:password@server:port CONNECTION_SECURITY_NONE * smtp+tls://user:password@server:port CONNECTION_SECURITY_TLS_OPTIONAL * smtp+tls+://user:password@server:port CONNECTION_SECURITY_TLS_REQUIRED * smtp+ssl+://user:password@server:port CONNECTION_SECURITY_SSL_REQUIRED * smtp+ssl://user:password@server:port CONNECTION_SECURITY_SSL_OPTIONAL * * @param _uri */ public SmtpTransport(String _uri) throws MessagingException { URI uri; try { uri = new URI(_uri); } catch (URISyntaxException use) { throw new MessagingException("Invalid SmtpTransport URI", use); } String scheme = uri.getScheme(); if (scheme.equals("smtp")) { mConnectionSecurity = CONNECTION_SECURITY_NONE; mPort = 25; } else if (scheme.equals("smtp+tls")) { mConnectionSecurity = CONNECTION_SECURITY_TLS_OPTIONAL; mPort = 25; } else if (scheme.equals("smtp+tls+")) { mConnectionSecurity = CONNECTION_SECURITY_TLS_REQUIRED; mPort = 25; } else if (scheme.equals("smtp+ssl+")) { mConnectionSecurity = CONNECTION_SECURITY_SSL_REQUIRED; mPort = 465; } else if (scheme.equals("smtp+ssl")) { mConnectionSecurity = CONNECTION_SECURITY_SSL_OPTIONAL; mPort = 465; } else { throw new MessagingException("Unsupported protocol"); } mHost = uri.getHost(); if (uri.getPort() != -1) { mPort = uri.getPort(); } if (uri.getUserInfo() != null) { try { String[] userInfoParts = uri.getUserInfo().split(":"); mUsername = URLDecoder.decode(userInfoParts[0], "UTF-8"); if (userInfoParts.length > 1) { mPassword = URLDecoder.decode(userInfoParts[1], "UTF-8"); } if (userInfoParts.length > 2) { mAuthType = userInfoParts[2]; } } catch (UnsupportedEncodingException enc) { // This shouldn't happen since the encoding is hardcoded to UTF-8 Log.e(K9.LOG_TAG, "Couldn't urldecode username or password.", enc); } } } @Override public void open() throws MessagingException { try { SocketAddress socketAddress = new InetSocketAddress(mHost, mPort); if (mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED || mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) { SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED; sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, secure) }, new SecureRandom()); mSocket = sslContext.getSocketFactory().createSocket(); mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); mSecure = true; } else { mSocket = new Socket(); mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } // RFC 1047 mSocket.setSoTimeout(SOCKET_READ_TIMEOUT); mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(), 1024)); mOut = mSocket.getOutputStream(); // Eat the banner executeSimpleCommand(null); InetAddress localAddress = mSocket.getLocalAddress(); String localHost = localAddress.getHostName(); + String ipAddr = localAddress.getHostAddress(); - if (localHost.equals(localAddress.getHostAddress())) + if (localHost.equals(ipAddr) || localHost.contains("_")) { - // We don't have a FQDN, so use IP address. + // We don't have a FQDN or the hostname contains invalid + // characters (see issue 2143), so use IP address. if (localAddress instanceof Inet6Address) { - localHost = "[IPV6:" + localHost + "]"; + localHost = "[IPV6:" + ipAddr + "]"; } else { - localHost = "[" + localHost + "]"; + localHost = "[" + ipAddr + "]"; } } List<String> results = executeSimpleCommand("EHLO " + localHost); m8bitEncodingAllowed = results.contains("8BITMIME"); /* * TODO may need to add code to fall back to HELO I switched it from * using HELO on non STARTTLS connections because of AOL's mail * server. It won't let you use AUTH without EHLO. * We should really be paying more attention to the capabilities * and only attempting auth if it's available, and warning the user * if not. */ if (mConnectionSecurity == CONNECTION_SECURITY_TLS_OPTIONAL || mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { if (results.contains("STARTTLS")) { executeSimpleCommand("STARTTLS"); SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED; sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, secure) }, new SecureRandom()); mSocket = sslContext.getSocketFactory().createSocket(mSocket, mHost, mPort, true); mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(), 1024)); mOut = mSocket.getOutputStream(); mSecure = true; /* * Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically, * Exim. */ results = executeSimpleCommand("EHLO " + localHost); } else if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { throw new MessagingException("TLS not supported but required"); } } /* * result contains the results of the EHLO in concatenated form */ boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; for (String result : results) { if (result.matches(".*AUTH.*LOGIN.*$") == true) { authLoginSupported = true; } if (result.matches(".*AUTH.*PLAIN.*$") == true) { authPlainSupported = true; } if (result.matches(".*AUTH.*CRAM-MD5.*$") == true && mAuthType != null && mAuthType.equals("CRAM_MD5")) { authCramMD5Supported = true; } } if (mUsername != null && mUsername.length() > 0 && mPassword != null && mPassword.length() > 0) { if (authCramMD5Supported) { saslAuthCramMD5(mUsername, mPassword); } else if (authPlainSupported) { saslAuthPlain(mUsername, mPassword); } else if (authLoginSupported) { saslAuthLogin(mUsername, mPassword); } else { throw new MessagingException("No valid authentication mechanism found."); } } } catch (SSLException e) { throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } @Override public void sendMessage(Message message) throws MessagingException { close(); open(); if (m8bitEncodingAllowed) { message.setEncoding("8bit"); } Address[] from = message.getFrom(); boolean possibleSend = false; try { //TODO: Add BODY=8BITMIME parameter if appropriate? executeSimpleCommand("MAIL FROM: " + "<" + from[0].getAddress() + ">"); for (Address address : message.getRecipients(RecipientType.TO)) { executeSimpleCommand("RCPT TO: " + "<" + address.getAddress() + ">"); } for (Address address : message.getRecipients(RecipientType.CC)) { executeSimpleCommand("RCPT TO: " + "<" + address.getAddress() + ">"); } for (Address address : message.getRecipients(RecipientType.BCC)) { executeSimpleCommand("RCPT TO: " + "<" + address.getAddress() + ">"); } message.setRecipients(RecipientType.BCC, null); executeSimpleCommand("DATA"); EOLConvertingOutputStream msgOut = new EOLConvertingOutputStream( new SmtpDataStuffing( new LineWrapOutputStream( new BufferedOutputStream(mOut, 1024), 1000))); message.writeTo(msgOut); // We use BufferedOutputStream. So make sure to call flush() ! msgOut.flush(); possibleSend = true; // After the "\r\n." is attempted, we may have sent the message executeSimpleCommand("\r\n."); } catch (Exception e) { MessagingException me = new MessagingException("Unable to send message", e); me.setPermanentFailure(possibleSend); throw me; } finally { close(); } } @Override public void close() { try { executeSimpleCommand("QUIT"); } catch (Exception e) { } try { mIn.close(); } catch (Exception e) { } try { mOut.close(); } catch (Exception e) { } try { mSocket.close(); } catch (Exception e) { } mIn = null; mOut = null; mSocket = null; } private String readLine() throws IOException { StringBuffer sb = new StringBuffer(); int d; while ((d = mIn.read()) != -1) { if (((char)d) == '\r') { continue; } else if (((char)d) == '\n') { break; } else { sb.append((char)d); } } String ret = sb.toString(); if (K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP) Log.d(K9.LOG_TAG, "SMTP <<< " + ret); return ret; } private void writeLine(String s, boolean sensitive) throws IOException { if (K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP) { final String commandToLog; if (sensitive && !K9.DEBUG_SENSITIVE) { commandToLog = "SMTP >>> *sensitive*"; } else { commandToLog = "SMTP >>> " + s; } Log.d(K9.LOG_TAG, commandToLog); } /* * Note: We can use the string length to compute the buffer size since * only ASCII characters are allowed in SMTP commands i.e. this string * will never contain multi-byte characters. */ int len = s.length(); byte[] data = new byte[len + 2]; s.getBytes(0, len, data, 0); data[len+0] = '\r'; data[len+1] = '\n'; /* * Important: Send command + CRLF using just one write() call. Using * multiple calls will likely result in multiple TCP packets and some * SMTP servers misbehave if CR and LF arrive in separate pakets. * See issue 799. */ mOut.write(data); mOut.flush(); } private void checkLine(String line) throws MessagingException { if (line.length() < 1) { throw new MessagingException("SMTP response is 0 length"); } char c = line.charAt(0); if ((c == '4') || (c == '5')) { throw new MessagingException(line); } } private List<String> executeSimpleCommand(String command) throws IOException, MessagingException { return executeSimpleCommand(command, false); } private List<String> executeSimpleCommand(String command, boolean sensitive) throws IOException, MessagingException { List<String> results = new ArrayList<String>(); if (command != null) { writeLine(command, sensitive); } boolean cont = false; do { String line = readLine(); checkLine(line); if (line.length() > 4) { results.add(line.substring(4)); if (line.charAt(3) == '-') { cont = true; } else { cont = false; } } } while (cont); return results; } // C: AUTH LOGIN // S: 334 VXNlcm5hbWU6 // C: d2VsZG9u // S: 334 UGFzc3dvcmQ6 // C: dzNsZDBu // S: 235 2.0.0 OK Authenticated // // Lines 2-5 of the conversation contain base64-encoded information. The same conversation, with base64 strings decoded, reads: // // // C: AUTH LOGIN // S: 334 Username: // C: weldon // S: 334 Password: // C: w3ld0n // S: 235 2.0.0 OK Authenticated private void saslAuthLogin(String username, String password) throws MessagingException, AuthenticationFailedException, IOException { try { executeSimpleCommand("AUTH LOGIN"); executeSimpleCommand(new String(Base64.encodeBase64(username.getBytes())), true); executeSimpleCommand(new String(Base64.encodeBase64(password.getBytes())), true); } catch (MessagingException me) { if (me.getMessage().length() > 1 && me.getMessage().charAt(1) == '3') { throw new AuthenticationFailedException("AUTH LOGIN failed (" + me.getMessage() + ")"); } throw me; } } private void saslAuthPlain(String username, String password) throws MessagingException, AuthenticationFailedException, IOException { byte[] data = ("\000" + username + "\000" + password).getBytes(); data = new Base64().encode(data); try { executeSimpleCommand("AUTH PLAIN " + new String(data), true); } catch (MessagingException me) { if (me.getMessage().length() > 1 && me.getMessage().charAt(1) == '3') { throw new AuthenticationFailedException("AUTH PLAIN failed (" + me.getMessage() + ")"); } throw me; } } private void saslAuthCramMD5(String username, String password) throws MessagingException, AuthenticationFailedException, IOException { List<String> respList = executeSimpleCommand("AUTH CRAM-MD5"); if (respList.size() != 1) throw new AuthenticationFailedException("Unable to negotiate CRAM-MD5"); String b64Nonce = respList.get(0); byte[] nonce = Base64.decodeBase64(b64Nonce.getBytes("US-ASCII")); byte[] ipad = new byte[64]; byte[] opad = new byte[64]; byte[] secretBytes = password.getBytes("US-ASCII"); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { throw new AuthenticationFailedException("MD5 Not Available."); } if (secretBytes.length > 64) { secretBytes = md.digest(secretBytes); } System.arraycopy(secretBytes, 0, ipad, 0, secretBytes.length); System.arraycopy(secretBytes, 0, opad, 0, secretBytes.length); for (int i = 0; i < ipad.length; i++) ipad[i] ^= 0x36; for (int i = 0; i < opad.length; i++) opad[i] ^= 0x5c; md.update(ipad); byte[] firstPass = md.digest(nonce); md.update(opad); byte[] result = md.digest(firstPass); String plainCRAM = username + " " + new String(Hex.encodeHex(result)); byte[] b64CRAM = Base64.encodeBase64(plainCRAM.getBytes("US-ASCII")); String b64CRAMString = new String(b64CRAM, "US-ASCII"); try { executeSimpleCommand(b64CRAMString, true); } catch (MessagingException me) { throw new AuthenticationFailedException("Unable to negotiate MD5 CRAM"); } } }
false
true
public void open() throws MessagingException { try { SocketAddress socketAddress = new InetSocketAddress(mHost, mPort); if (mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED || mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) { SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED; sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, secure) }, new SecureRandom()); mSocket = sslContext.getSocketFactory().createSocket(); mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); mSecure = true; } else { mSocket = new Socket(); mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } // RFC 1047 mSocket.setSoTimeout(SOCKET_READ_TIMEOUT); mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(), 1024)); mOut = mSocket.getOutputStream(); // Eat the banner executeSimpleCommand(null); InetAddress localAddress = mSocket.getLocalAddress(); String localHost = localAddress.getHostName(); if (localHost.equals(localAddress.getHostAddress())) { // We don't have a FQDN, so use IP address. if (localAddress instanceof Inet6Address) { localHost = "[IPV6:" + localHost + "]"; } else { localHost = "[" + localHost + "]"; } } List<String> results = executeSimpleCommand("EHLO " + localHost); m8bitEncodingAllowed = results.contains("8BITMIME"); /* * TODO may need to add code to fall back to HELO I switched it from * using HELO on non STARTTLS connections because of AOL's mail * server. It won't let you use AUTH without EHLO. * We should really be paying more attention to the capabilities * and only attempting auth if it's available, and warning the user * if not. */ if (mConnectionSecurity == CONNECTION_SECURITY_TLS_OPTIONAL || mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { if (results.contains("STARTTLS")) { executeSimpleCommand("STARTTLS"); SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED; sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, secure) }, new SecureRandom()); mSocket = sslContext.getSocketFactory().createSocket(mSocket, mHost, mPort, true); mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(), 1024)); mOut = mSocket.getOutputStream(); mSecure = true; /* * Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically, * Exim. */ results = executeSimpleCommand("EHLO " + localHost); } else if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { throw new MessagingException("TLS not supported but required"); } } /* * result contains the results of the EHLO in concatenated form */ boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; for (String result : results) { if (result.matches(".*AUTH.*LOGIN.*$") == true) { authLoginSupported = true; } if (result.matches(".*AUTH.*PLAIN.*$") == true) { authPlainSupported = true; } if (result.matches(".*AUTH.*CRAM-MD5.*$") == true && mAuthType != null && mAuthType.equals("CRAM_MD5")) { authCramMD5Supported = true; } } if (mUsername != null && mUsername.length() > 0 && mPassword != null && mPassword.length() > 0) { if (authCramMD5Supported) { saslAuthCramMD5(mUsername, mPassword); } else if (authPlainSupported) { saslAuthPlain(mUsername, mPassword); } else if (authLoginSupported) { saslAuthLogin(mUsername, mPassword); } else { throw new MessagingException("No valid authentication mechanism found."); } } } catch (SSLException e) { throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
public void open() throws MessagingException { try { SocketAddress socketAddress = new InetSocketAddress(mHost, mPort); if (mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED || mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) { SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED; sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, secure) }, new SecureRandom()); mSocket = sslContext.getSocketFactory().createSocket(); mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); mSecure = true; } else { mSocket = new Socket(); mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } // RFC 1047 mSocket.setSoTimeout(SOCKET_READ_TIMEOUT); mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(), 1024)); mOut = mSocket.getOutputStream(); // Eat the banner executeSimpleCommand(null); InetAddress localAddress = mSocket.getLocalAddress(); String localHost = localAddress.getHostName(); String ipAddr = localAddress.getHostAddress(); if (localHost.equals(ipAddr) || localHost.contains("_")) { // We don't have a FQDN or the hostname contains invalid // characters (see issue 2143), so use IP address. if (localAddress instanceof Inet6Address) { localHost = "[IPV6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } List<String> results = executeSimpleCommand("EHLO " + localHost); m8bitEncodingAllowed = results.contains("8BITMIME"); /* * TODO may need to add code to fall back to HELO I switched it from * using HELO on non STARTTLS connections because of AOL's mail * server. It won't let you use AUTH without EHLO. * We should really be paying more attention to the capabilities * and only attempting auth if it's available, and warning the user * if not. */ if (mConnectionSecurity == CONNECTION_SECURITY_TLS_OPTIONAL || mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { if (results.contains("STARTTLS")) { executeSimpleCommand("STARTTLS"); SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED; sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, secure) }, new SecureRandom()); mSocket = sslContext.getSocketFactory().createSocket(mSocket, mHost, mPort, true); mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(), 1024)); mOut = mSocket.getOutputStream(); mSecure = true; /* * Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically, * Exim. */ results = executeSimpleCommand("EHLO " + localHost); } else if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { throw new MessagingException("TLS not supported but required"); } } /* * result contains the results of the EHLO in concatenated form */ boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; for (String result : results) { if (result.matches(".*AUTH.*LOGIN.*$") == true) { authLoginSupported = true; } if (result.matches(".*AUTH.*PLAIN.*$") == true) { authPlainSupported = true; } if (result.matches(".*AUTH.*CRAM-MD5.*$") == true && mAuthType != null && mAuthType.equals("CRAM_MD5")) { authCramMD5Supported = true; } } if (mUsername != null && mUsername.length() > 0 && mPassword != null && mPassword.length() > 0) { if (authCramMD5Supported) { saslAuthCramMD5(mUsername, mPassword); } else if (authPlainSupported) { saslAuthPlain(mUsername, mPassword); } else if (authLoginSupported) { saslAuthLogin(mUsername, mPassword); } else { throw new MessagingException("No valid authentication mechanism found."); } } } catch (SSLException e) { throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
diff --git a/src/com/android/phone/sip/SipSettings.java b/src/com/android/phone/sip/SipSettings.java index 247e64ae..c14a4039 100644 --- a/src/com/android/phone/sip/SipSettings.java +++ b/src/com/android/phone/sip/SipSettings.java @@ -1,438 +1,443 @@ /* * Copyright (C) 2010 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.android.phone.sip; import com.android.phone.R; import com.android.phone.SipUtil; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.net.sip.SipException; import android.net.sip.SipErrorCode; import android.net.sip.SipProfile; import android.net.sip.SipManager; import android.net.sip.SipRegistrationListener; import android.os.Bundle; import android.os.Parcelable; import android.os.Process; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceCategory; import android.preference.PreferenceScreen; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.Button; import java.io.IOException; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * The PreferenceActivity class for managing sip profile preferences. */ public class SipSettings extends PreferenceActivity { public static final String SIP_SHARED_PREFERENCES = "SIP_PREFERENCES"; static final String KEY_SIP_PROFILE = "sip_profile"; private static final String BUTTON_SIP_RECEIVE_CALLS = "sip_receive_calls_key"; private static final String PREF_SIP_LIST = "sip_account_list"; private static final String TAG = "SipSettings"; private static final int REQUEST_ADD_OR_EDIT_SIP_PROFILE = 1; private PackageManager mPackageManager; private SipManager mSipManager; private SipProfileDb mProfileDb; private SipProfile mProfile; // profile that's being edited private CheckBoxPreference mButtonSipReceiveCalls; private PreferenceCategory mSipListContainer; private Map<String, SipPreference> mSipPreferenceMap; private List<SipProfile> mSipProfileList; private SipSharedPreferences mSipSharedPreferences; private int mUid = Process.myUid(); private class SipPreference extends Preference { SipProfile mProfile; SipPreference(Context c, SipProfile p) { super(c); setProfile(p); } SipProfile getProfile() { return mProfile; } void setProfile(SipProfile p) { mProfile = p; setTitle(p.getProfileName()); updateSummary(mSipSharedPreferences.isReceivingCallsEnabled() ? getString(R.string.registration_status_checking_status) : getString(R.string.registration_status_not_receiving)); } void updateSummary(String registrationStatus) { int profileUid = mProfile.getCallingUid(); boolean isPrimary = mProfile.getUriString().equals( mSipSharedPreferences.getPrimaryAccount()); Log.v(TAG, "profile uid is " + profileUid + " isPrimary:" + isPrimary + " registration:" + registrationStatus + " Primary:" + mSipSharedPreferences.getPrimaryAccount() + " status:" + registrationStatus); String summary = ""; if ((profileUid > 0) && (profileUid != mUid)) { // from third party apps summary = getString(R.string.third_party_account_summary, getPackageNameFromUid(profileUid)); } else if (isPrimary) { summary = getString(R.string.primary_account_summary_with, registrationStatus); } else { summary = registrationStatus; } setSummary(summary); } } private String getPackageNameFromUid(int uid) { try { String[] pkgs = mPackageManager.getPackagesForUid(uid); ApplicationInfo ai = mPackageManager.getApplicationInfo(pkgs[0], 0); return ai.loadLabel(mPackageManager).toString(); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "cannot find name of uid " + uid, e); } return "uid:" + uid; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mSipManager = SipManager.newInstance(this); mSipSharedPreferences = new SipSharedPreferences(this); mProfileDb = new SipProfileDb(this); mPackageManager = getPackageManager(); setContentView(R.layout.sip_settings_ui); addPreferencesFromResource(R.xml.sip_setting); mSipListContainer = (PreferenceCategory) findPreference(PREF_SIP_LIST); registerForAddSipListener(); registerForReceiveCallsCheckBox(); updateProfilesStatus(); } @Override public void onResume() { super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); unregisterForContextMenu(getListView()); } @Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent intent) { if (resultCode != RESULT_OK && resultCode != RESULT_FIRST_USER) return; new Thread() { public void run() { try { if (mProfile != null) { Log.v(TAG, "Removed Profile:" + mProfile.getProfileName()); deleteProfile(mProfile); } SipProfile profile = intent.getParcelableExtra(KEY_SIP_PROFILE); if (resultCode == RESULT_OK) { Log.v(TAG, "New Profile Name:" + profile.getProfileName()); addProfile(profile); } updateProfilesStatus(); } catch (IOException e) { Log.v(TAG, "Can not handle the profile : " + e.getMessage()); } }}.start(); } private void registerForAddSipListener() { ((Button) findViewById(R.id.add_remove_account_button)) .setOnClickListener(new android.view.View.OnClickListener() { public void onClick(View v) { startSipEditor(null); } }); } private void registerForReceiveCallsCheckBox() { mButtonSipReceiveCalls = (CheckBoxPreference) findPreference (BUTTON_SIP_RECEIVE_CALLS); mButtonSipReceiveCalls.setChecked( mSipSharedPreferences.isReceivingCallsEnabled()); mButtonSipReceiveCalls.setOnPreferenceClickListener( new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { final boolean enabled = ((CheckBoxPreference) preference).isChecked(); new Thread(new Runnable() { public void run() { handleSipReceiveCallsOption(enabled); } }).start(); return true; } }); } private synchronized void handleSipReceiveCallsOption(boolean enabled) { mSipSharedPreferences.setReceivingCallsEnabled(enabled); List<SipProfile> sipProfileList = mProfileDb.retrieveSipProfileList(); for (SipProfile p : sipProfileList) { String sipUri = p.getUriString(); p = updateAutoRegistrationFlag(p, enabled); try { if (enabled) { mSipManager.open(p, SipUtil.createIncomingCallPendingIntent(), null); } else { mSipManager.close(sipUri); if (mSipSharedPreferences.isPrimaryAccount(sipUri)) { // re-open in order to make calls mSipManager.open(p); } } } catch (Exception e) { Log.e(TAG, "register failed", e); } } updateProfilesStatus(); } private SipProfile updateAutoRegistrationFlag( SipProfile p, boolean enabled) { SipProfile newProfile = new SipProfile.Builder(p) .setAutoRegistration(enabled) .build(); try { mProfileDb.deleteProfile(p); mProfileDb.saveProfile(newProfile); } catch (Exception e) { Log.e(TAG, "updateAutoRegistrationFlag error", e); } return newProfile; } private void updateProfilesStatus() { new Thread(new Runnable() { public void run() { try { retrieveSipLists(); } catch (Exception e) { Log.e(TAG, "isRegistered", e); } } }).start(); } private void retrieveSipLists() { mSipPreferenceMap = new LinkedHashMap<String, SipPreference>(); mSipProfileList = mProfileDb.retrieveSipProfileList(); processActiveProfilesFromSipService(); Collections.sort(mSipProfileList, new Comparator<SipProfile>() { public int compare(SipProfile p1, SipProfile p2) { return p1.getProfileName().compareTo(p2.getProfileName()); } public boolean equals(SipProfile p) { // not used return false; } }); mSipListContainer.removeAll(); for (SipProfile p : mSipProfileList) { addPreferenceFor(p); } if (!mSipSharedPreferences.isReceivingCallsEnabled()) return; for (SipProfile p : mSipProfileList) { if (mUid == p.getCallingUid()) { try { mSipManager.setRegistrationListener( p.getUriString(), createRegistrationListener()); } catch (SipException e) { Log.e(TAG, "cannot set registration listener", e); } } } } private void processActiveProfilesFromSipService() { SipProfile[] activeList = mSipManager.getListOfProfiles(); for (SipProfile activeProfile : activeList) { SipProfile profile = getProfileFromList(activeProfile); if (profile == null) { mSipProfileList.add(activeProfile); } else { profile.setCallingUid(activeProfile.getCallingUid()); } } } private SipProfile getProfileFromList(SipProfile activeProfile) { for (SipProfile p : mSipProfileList) { if (p.getUriString().equals(activeProfile.getUriString())) { return p; } } return null; } private void addPreferenceFor(SipProfile p) { String status; Log.v(TAG, "addPreferenceFor profile uri" + p.getUri()); SipPreference pref = new SipPreference(this, p); mSipPreferenceMap.put(p.getUriString(), pref); mSipListContainer.addPreference(pref); pref.setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference pref) { handleProfileClick(((SipPreference) pref).mProfile); return true; } }); } private void handleProfileClick(final SipProfile profile) { int uid = profile.getCallingUid(); if (uid == mUid || uid == 0) { startSipEditor(profile); return; } new AlertDialog.Builder(this) .setTitle(R.string.alert_dialog_close) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.close_profile, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int w) { deleteProfile(profile); } }) .setNegativeButton(android.R.string.cancel, null) .show(); } void deleteProfile(SipProfile p) { mSipProfileList.remove(p); SipPreference pref = mSipPreferenceMap.remove(p.getUriString()); mSipListContainer.removePreference(pref); } private void addProfile(SipProfile p) throws IOException { try { mSipManager.setRegistrationListener(p.getUriString(), createRegistrationListener()); } catch (Exception e) { Log.e(TAG, "cannot set registration listener", e); } mSipProfileList.add(p); addPreferenceFor(p); } private void startSipEditor(final SipProfile profile) { mProfile = profile; Intent intent = new Intent(this, SipEditor.class); intent.putExtra(KEY_SIP_PROFILE, (Parcelable) profile); startActivityForResult(intent, REQUEST_ADD_OR_EDIT_SIP_PROFILE); } private void showRegistrationMessage(final String profileUri, final String message) { runOnUiThread(new Runnable() { public void run() { SipPreference pref = mSipPreferenceMap.get(profileUri); if (pref != null) { pref.updateSummary(message); } } }); } private SipRegistrationListener createRegistrationListener() { return new SipRegistrationListener() { public void onRegistrationDone(String profileUri, long expiryTime) { showRegistrationMessage(profileUri, getString( R.string.registration_status_done)); } public void onRegistering(String profileUri) { showRegistrationMessage(profileUri, getString( R.string.registration_status_registering)); } public void onRegistrationFailed(String profileUri, int errorCode, String message) { switch (errorCode) { case SipErrorCode.IN_PROGRESS: showRegistrationMessage(profileUri, getString( R.string.registration_status_still_trying)); break; case SipErrorCode.INVALID_CREDENTIALS: showRegistrationMessage(profileUri, getString( R.string.registration_status_invalid_credentials)); break; case SipErrorCode.SERVER_UNREACHABLE: showRegistrationMessage(profileUri, getString( R.string.registration_status_server_unreachable)); break; case SipErrorCode.DATA_CONNECTION_LOST: - showRegistrationMessage(profileUri, getString( - R.string.registration_status_no_data)); + if (SipManager.isSipWifiOnly(getApplicationContext())){ + showRegistrationMessage(profileUri, getString( + R.string.registration_status_no_wifi_data)); + } else { + showRegistrationMessage(profileUri, getString( + R.string.registration_status_no_data)); + } break; case SipErrorCode.CLIENT_ERROR: showRegistrationMessage(profileUri, getString( R.string.registration_status_not_running)); break; default: showRegistrationMessage(profileUri, getString( R.string.registration_status_failed_try_later, message)); } } }; } }
true
true
private SipRegistrationListener createRegistrationListener() { return new SipRegistrationListener() { public void onRegistrationDone(String profileUri, long expiryTime) { showRegistrationMessage(profileUri, getString( R.string.registration_status_done)); } public void onRegistering(String profileUri) { showRegistrationMessage(profileUri, getString( R.string.registration_status_registering)); } public void onRegistrationFailed(String profileUri, int errorCode, String message) { switch (errorCode) { case SipErrorCode.IN_PROGRESS: showRegistrationMessage(profileUri, getString( R.string.registration_status_still_trying)); break; case SipErrorCode.INVALID_CREDENTIALS: showRegistrationMessage(profileUri, getString( R.string.registration_status_invalid_credentials)); break; case SipErrorCode.SERVER_UNREACHABLE: showRegistrationMessage(profileUri, getString( R.string.registration_status_server_unreachable)); break; case SipErrorCode.DATA_CONNECTION_LOST: showRegistrationMessage(profileUri, getString( R.string.registration_status_no_data)); break; case SipErrorCode.CLIENT_ERROR: showRegistrationMessage(profileUri, getString( R.string.registration_status_not_running)); break; default: showRegistrationMessage(profileUri, getString( R.string.registration_status_failed_try_later, message)); } } }; }
private SipRegistrationListener createRegistrationListener() { return new SipRegistrationListener() { public void onRegistrationDone(String profileUri, long expiryTime) { showRegistrationMessage(profileUri, getString( R.string.registration_status_done)); } public void onRegistering(String profileUri) { showRegistrationMessage(profileUri, getString( R.string.registration_status_registering)); } public void onRegistrationFailed(String profileUri, int errorCode, String message) { switch (errorCode) { case SipErrorCode.IN_PROGRESS: showRegistrationMessage(profileUri, getString( R.string.registration_status_still_trying)); break; case SipErrorCode.INVALID_CREDENTIALS: showRegistrationMessage(profileUri, getString( R.string.registration_status_invalid_credentials)); break; case SipErrorCode.SERVER_UNREACHABLE: showRegistrationMessage(profileUri, getString( R.string.registration_status_server_unreachable)); break; case SipErrorCode.DATA_CONNECTION_LOST: if (SipManager.isSipWifiOnly(getApplicationContext())){ showRegistrationMessage(profileUri, getString( R.string.registration_status_no_wifi_data)); } else { showRegistrationMessage(profileUri, getString( R.string.registration_status_no_data)); } break; case SipErrorCode.CLIENT_ERROR: showRegistrationMessage(profileUri, getString( R.string.registration_status_not_running)); break; default: showRegistrationMessage(profileUri, getString( R.string.registration_status_failed_try_later, message)); } } }; }
diff --git a/modules/omicsconnect-importer/org/molgenis/omicsconnect/view/DataSetChooser.java b/modules/omicsconnect-importer/org/molgenis/omicsconnect/view/DataSetChooser.java index 9cd8bcfca..c5f0fb24b 100644 --- a/modules/omicsconnect-importer/org/molgenis/omicsconnect/view/DataSetChooser.java +++ b/modules/omicsconnect-importer/org/molgenis/omicsconnect/view/DataSetChooser.java @@ -1,61 +1,60 @@ package org.molgenis.omicsconnect.view; import java.util.List; import org.molgenis.framework.ui.html.HtmlWidget; import org.molgenis.observ.DataSet; public class DataSetChooser extends HtmlWidget { private List<DataSet> dataSets; private Integer selectedDataSetId; public DataSetChooser(List<DataSet> dataSets, Integer selectedDataSetId) { super(DataSetChooser.class.getSimpleName(), null); this.dataSets = dataSets; this.selectedDataSetId = selectedDataSetId; } public Integer getSelectedDataSetId() { return selectedDataSetId; } public void setSelectedDataSetId(Integer selectedDataSetId) { this.selectedDataSetId = selectedDataSetId; } @Override public String toHtml() { StringBuilder sb = new StringBuilder(); sb.append("<div class='row-fluid grid'>"); sb.append("<div class='span2'><label>Choose a dataset:</label></div>"); - sb.append("<div class='btn-group btn-datasets' data-toggle='buttons-radio'>"); + sb.append("<div class='btn-group' data-toggle='buttons-radio'>"); for (DataSet ds : dataSets) { if ((selectedDataSetId != null) && ds.getId().equals(selectedDataSetId)) { sb.append("<button class='btn active' name='dataSetId' value='"); } else { sb.append("<button class='btn' name='dataSetId' value='"); } sb.append(ds.getId()).append("'>"); sb.append(ds.getName());// TODO html encode sb.append("</button>"); } sb.append("</div>"); sb.append("</div>"); sb.append("<script type='text/javascript'>"); - sb.append("$(function() {$('.btn').button(); $('.btn [value=" + selectedDataSetId + "]').click();});"); sb.append("$('input[name=__action]').val('selectDataSet')"); sb.append("</script>"); return sb.toString(); } }
false
true
public String toHtml() { StringBuilder sb = new StringBuilder(); sb.append("<div class='row-fluid grid'>"); sb.append("<div class='span2'><label>Choose a dataset:</label></div>"); sb.append("<div class='btn-group btn-datasets' data-toggle='buttons-radio'>"); for (DataSet ds : dataSets) { if ((selectedDataSetId != null) && ds.getId().equals(selectedDataSetId)) { sb.append("<button class='btn active' name='dataSetId' value='"); } else { sb.append("<button class='btn' name='dataSetId' value='"); } sb.append(ds.getId()).append("'>"); sb.append(ds.getName());// TODO html encode sb.append("</button>"); } sb.append("</div>"); sb.append("</div>"); sb.append("<script type='text/javascript'>"); sb.append("$(function() {$('.btn').button(); $('.btn [value=" + selectedDataSetId + "]').click();});"); sb.append("$('input[name=__action]').val('selectDataSet')"); sb.append("</script>"); return sb.toString(); }
public String toHtml() { StringBuilder sb = new StringBuilder(); sb.append("<div class='row-fluid grid'>"); sb.append("<div class='span2'><label>Choose a dataset:</label></div>"); sb.append("<div class='btn-group' data-toggle='buttons-radio'>"); for (DataSet ds : dataSets) { if ((selectedDataSetId != null) && ds.getId().equals(selectedDataSetId)) { sb.append("<button class='btn active' name='dataSetId' value='"); } else { sb.append("<button class='btn' name='dataSetId' value='"); } sb.append(ds.getId()).append("'>"); sb.append(ds.getName());// TODO html encode sb.append("</button>"); } sb.append("</div>"); sb.append("</div>"); sb.append("<script type='text/javascript'>"); sb.append("$('input[name=__action]').val('selectDataSet')"); sb.append("</script>"); return sb.toString(); }
diff --git a/src/gnu/prolog/vm/buildins/atomicterms/Predicate_atom_concat.java b/src/gnu/prolog/vm/buildins/atomicterms/Predicate_atom_concat.java index 4057f6a..57939da 100644 --- a/src/gnu/prolog/vm/buildins/atomicterms/Predicate_atom_concat.java +++ b/src/gnu/prolog/vm/buildins/atomicterms/Predicate_atom_concat.java @@ -1,213 +1,213 @@ /* GNU Prolog for Java * Copyright (C) 1997-1999 Constantine Plotnikov * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library 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. The text ol license can be also found * at http://www.gnu.org/copyleft/lgpl.html */ package gnu.prolog.vm.buildins.atomicterms; import gnu.prolog.term.AtomTerm; import gnu.prolog.term.Term; import gnu.prolog.term.VariableTerm; import gnu.prolog.vm.BacktrackInfo; import gnu.prolog.vm.Environment; import gnu.prolog.vm.Interpreter; import gnu.prolog.vm.PrologCode; import gnu.prolog.vm.PrologException; /** prolog code */ public class Predicate_atom_concat implements PrologCode { static final AtomTerm atomAtom = AtomTerm.get("atom"); static final AtomTerm nullAtom = AtomTerm.get(""); /** cutomized bactrackinfo */ private static class AtomConcatBacktrackInfo extends BacktrackInfo { AtomConcatBacktrackInfo(int atomPosition, int startUndoPosition, String atom) { super(-1,-1); this.atomPosition = atomPosition; this.startUndoPosition = startUndoPosition; this.atom = atom; } int atomPosition; int startUndoPosition; String atom; } /** this method is used for execution of code * @param interpreter interpreter in which context code is executed * @param backtrackMode true if predicate is called on backtracking and false otherwise * @param args arguments of code * @return either SUCCESS, SUCCESS_LAST, or FAIL. */ public int execute(Interpreter interpreter, boolean backtrackMode, gnu.prolog.term.Term args[]) throws PrologException { if (backtrackMode) { AtomConcatBacktrackInfo acbi = (AtomConcatBacktrackInfo)interpreter.popBacktrackInfo(); interpreter.undo(acbi.startUndoPosition); int al = acbi.atom.length(); int pos = acbi.atomPosition; VariableTerm v1 = (VariableTerm)args[0]; VariableTerm v2 = (VariableTerm)args[1]; if (acbi.atomPosition == al) { interpreter.addVariableUndo(v1); v1.value = args[2]; interpreter.addVariableUndo(v2); v2.value = nullAtom; return SUCCESS_LAST; } interpreter.addVariableUndo(v1); v1.value = AtomTerm.get(acbi.atom.substring(0,pos)); interpreter.addVariableUndo(v2); v2.value = AtomTerm.get(acbi.atom.substring(pos,al)); acbi.atomPosition++; interpreter.pushBacktrackInfo(acbi); return SUCCESS; } else { Term t1 = args[0]; Term t2 = args[1]; Term t12 = args[2]; int startUndoPosition = interpreter.getUndoPosition(); if (!(t1 instanceof VariableTerm || t1 instanceof AtomTerm)) { PrologException.typeError(atomAtom,t1); } if (!(t2 instanceof VariableTerm || t2 instanceof AtomTerm)) { PrologException.typeError(atomAtom,t2); } if (!(t12 instanceof VariableTerm || t12 instanceof AtomTerm)) { PrologException.typeError(atomAtom,t12); } if (t12 instanceof VariableTerm) { VariableTerm v12 = (VariableTerm)t12; if (t1 instanceof VariableTerm) { PrologException.instantiationError(); } if (t2 instanceof VariableTerm) { PrologException.instantiationError(); } AtomTerm a1 = (AtomTerm)t1; AtomTerm a2 = (AtomTerm)t2; AtomTerm a3 = AtomTerm.get(a1.value+a2.value); interpreter.addVariableUndo(v12); v12.value = a3; return SUCCESS_LAST; } else // t12 is AtomTerm { AtomTerm a12 = (AtomTerm)t12; String s12 = a12.value; if (t1 instanceof VariableTerm && t2 instanceof VariableTerm) { VariableTerm v1 = (VariableTerm)t1; VariableTerm v2 = (VariableTerm)t2; if (s12.length() == 0) { interpreter.addVariableUndo(v1); v1.value = a12; interpreter.addVariableUndo(v2); v2.value = a12; return SUCCESS_LAST; } interpreter.addVariableUndo(v1); v1.value = nullAtom; interpreter.addVariableUndo(v2); v2.value = a12; interpreter.pushBacktrackInfo( new AtomConcatBacktrackInfo(1,startUndoPosition,s12) ); return SUCCESS; } else if (t1 instanceof VariableTerm) { VariableTerm v1 = (VariableTerm)t1; AtomTerm a2 = (AtomTerm)t2; String s2 = a2.value; if (s12.endsWith(s2)) { interpreter.addVariableUndo(v1); v1.value = AtomTerm.get(s12.substring(0,s12.length()-s2.length())); return SUCCESS_LAST; } else { return FAIL; } } else if (t2 instanceof VariableTerm) { AtomTerm a1 = (AtomTerm)t1; VariableTerm v2 = (VariableTerm)t2; String s1 = a1.value; if (s12.startsWith(s1)) { interpreter.addVariableUndo(v2); int l1 = s1.length(); int l12 = s12.length(); v2.value = AtomTerm.get(s12.substring(l1,l12)); return SUCCESS_LAST; } else { return FAIL; } } else { AtomTerm a1 = (AtomTerm)t1; AtomTerm a2 = (AtomTerm)t2; String s1 = a1.value; - String s2 = a1.value; + String s2 = a2.value; if (s12.equals(s1+s2)) { return SUCCESS_LAST; } else { return FAIL; } } } } } /** this method is called when code is installed to the environment * code can be installed only for one environment. * @param environment environemnt to install the predicate */ public void install(Environment env) { } /** this method is called when code is uninstalled from the environment * @param environment environemnt to install the predicate */ public void uninstall(Environment env) { } }
true
true
public int execute(Interpreter interpreter, boolean backtrackMode, gnu.prolog.term.Term args[]) throws PrologException { if (backtrackMode) { AtomConcatBacktrackInfo acbi = (AtomConcatBacktrackInfo)interpreter.popBacktrackInfo(); interpreter.undo(acbi.startUndoPosition); int al = acbi.atom.length(); int pos = acbi.atomPosition; VariableTerm v1 = (VariableTerm)args[0]; VariableTerm v2 = (VariableTerm)args[1]; if (acbi.atomPosition == al) { interpreter.addVariableUndo(v1); v1.value = args[2]; interpreter.addVariableUndo(v2); v2.value = nullAtom; return SUCCESS_LAST; } interpreter.addVariableUndo(v1); v1.value = AtomTerm.get(acbi.atom.substring(0,pos)); interpreter.addVariableUndo(v2); v2.value = AtomTerm.get(acbi.atom.substring(pos,al)); acbi.atomPosition++; interpreter.pushBacktrackInfo(acbi); return SUCCESS; } else { Term t1 = args[0]; Term t2 = args[1]; Term t12 = args[2]; int startUndoPosition = interpreter.getUndoPosition(); if (!(t1 instanceof VariableTerm || t1 instanceof AtomTerm)) { PrologException.typeError(atomAtom,t1); } if (!(t2 instanceof VariableTerm || t2 instanceof AtomTerm)) { PrologException.typeError(atomAtom,t2); } if (!(t12 instanceof VariableTerm || t12 instanceof AtomTerm)) { PrologException.typeError(atomAtom,t12); } if (t12 instanceof VariableTerm) { VariableTerm v12 = (VariableTerm)t12; if (t1 instanceof VariableTerm) { PrologException.instantiationError(); } if (t2 instanceof VariableTerm) { PrologException.instantiationError(); } AtomTerm a1 = (AtomTerm)t1; AtomTerm a2 = (AtomTerm)t2; AtomTerm a3 = AtomTerm.get(a1.value+a2.value); interpreter.addVariableUndo(v12); v12.value = a3; return SUCCESS_LAST; } else // t12 is AtomTerm { AtomTerm a12 = (AtomTerm)t12; String s12 = a12.value; if (t1 instanceof VariableTerm && t2 instanceof VariableTerm) { VariableTerm v1 = (VariableTerm)t1; VariableTerm v2 = (VariableTerm)t2; if (s12.length() == 0) { interpreter.addVariableUndo(v1); v1.value = a12; interpreter.addVariableUndo(v2); v2.value = a12; return SUCCESS_LAST; } interpreter.addVariableUndo(v1); v1.value = nullAtom; interpreter.addVariableUndo(v2); v2.value = a12; interpreter.pushBacktrackInfo( new AtomConcatBacktrackInfo(1,startUndoPosition,s12) ); return SUCCESS; } else if (t1 instanceof VariableTerm) { VariableTerm v1 = (VariableTerm)t1; AtomTerm a2 = (AtomTerm)t2; String s2 = a2.value; if (s12.endsWith(s2)) { interpreter.addVariableUndo(v1); v1.value = AtomTerm.get(s12.substring(0,s12.length()-s2.length())); return SUCCESS_LAST; } else { return FAIL; } } else if (t2 instanceof VariableTerm) { AtomTerm a1 = (AtomTerm)t1; VariableTerm v2 = (VariableTerm)t2; String s1 = a1.value; if (s12.startsWith(s1)) { interpreter.addVariableUndo(v2); int l1 = s1.length(); int l12 = s12.length(); v2.value = AtomTerm.get(s12.substring(l1,l12)); return SUCCESS_LAST; } else { return FAIL; } } else { AtomTerm a1 = (AtomTerm)t1; AtomTerm a2 = (AtomTerm)t2; String s1 = a1.value; String s2 = a1.value; if (s12.equals(s1+s2)) { return SUCCESS_LAST; } else { return FAIL; } } } } }
public int execute(Interpreter interpreter, boolean backtrackMode, gnu.prolog.term.Term args[]) throws PrologException { if (backtrackMode) { AtomConcatBacktrackInfo acbi = (AtomConcatBacktrackInfo)interpreter.popBacktrackInfo(); interpreter.undo(acbi.startUndoPosition); int al = acbi.atom.length(); int pos = acbi.atomPosition; VariableTerm v1 = (VariableTerm)args[0]; VariableTerm v2 = (VariableTerm)args[1]; if (acbi.atomPosition == al) { interpreter.addVariableUndo(v1); v1.value = args[2]; interpreter.addVariableUndo(v2); v2.value = nullAtom; return SUCCESS_LAST; } interpreter.addVariableUndo(v1); v1.value = AtomTerm.get(acbi.atom.substring(0,pos)); interpreter.addVariableUndo(v2); v2.value = AtomTerm.get(acbi.atom.substring(pos,al)); acbi.atomPosition++; interpreter.pushBacktrackInfo(acbi); return SUCCESS; } else { Term t1 = args[0]; Term t2 = args[1]; Term t12 = args[2]; int startUndoPosition = interpreter.getUndoPosition(); if (!(t1 instanceof VariableTerm || t1 instanceof AtomTerm)) { PrologException.typeError(atomAtom,t1); } if (!(t2 instanceof VariableTerm || t2 instanceof AtomTerm)) { PrologException.typeError(atomAtom,t2); } if (!(t12 instanceof VariableTerm || t12 instanceof AtomTerm)) { PrologException.typeError(atomAtom,t12); } if (t12 instanceof VariableTerm) { VariableTerm v12 = (VariableTerm)t12; if (t1 instanceof VariableTerm) { PrologException.instantiationError(); } if (t2 instanceof VariableTerm) { PrologException.instantiationError(); } AtomTerm a1 = (AtomTerm)t1; AtomTerm a2 = (AtomTerm)t2; AtomTerm a3 = AtomTerm.get(a1.value+a2.value); interpreter.addVariableUndo(v12); v12.value = a3; return SUCCESS_LAST; } else // t12 is AtomTerm { AtomTerm a12 = (AtomTerm)t12; String s12 = a12.value; if (t1 instanceof VariableTerm && t2 instanceof VariableTerm) { VariableTerm v1 = (VariableTerm)t1; VariableTerm v2 = (VariableTerm)t2; if (s12.length() == 0) { interpreter.addVariableUndo(v1); v1.value = a12; interpreter.addVariableUndo(v2); v2.value = a12; return SUCCESS_LAST; } interpreter.addVariableUndo(v1); v1.value = nullAtom; interpreter.addVariableUndo(v2); v2.value = a12; interpreter.pushBacktrackInfo( new AtomConcatBacktrackInfo(1,startUndoPosition,s12) ); return SUCCESS; } else if (t1 instanceof VariableTerm) { VariableTerm v1 = (VariableTerm)t1; AtomTerm a2 = (AtomTerm)t2; String s2 = a2.value; if (s12.endsWith(s2)) { interpreter.addVariableUndo(v1); v1.value = AtomTerm.get(s12.substring(0,s12.length()-s2.length())); return SUCCESS_LAST; } else { return FAIL; } } else if (t2 instanceof VariableTerm) { AtomTerm a1 = (AtomTerm)t1; VariableTerm v2 = (VariableTerm)t2; String s1 = a1.value; if (s12.startsWith(s1)) { interpreter.addVariableUndo(v2); int l1 = s1.length(); int l12 = s12.length(); v2.value = AtomTerm.get(s12.substring(l1,l12)); return SUCCESS_LAST; } else { return FAIL; } } else { AtomTerm a1 = (AtomTerm)t1; AtomTerm a2 = (AtomTerm)t2; String s1 = a1.value; String s2 = a2.value; if (s12.equals(s1+s2)) { return SUCCESS_LAST; } else { return FAIL; } } } } }
diff --git a/src/test/java/com/camilolopes/readerweb/dbunit/DBUnitConfigurationTest.java b/src/test/java/com/camilolopes/readerweb/dbunit/DBUnitConfigurationTest.java index e5e0bbc..10c4fb2 100644 --- a/src/test/java/com/camilolopes/readerweb/dbunit/DBUnitConfigurationTest.java +++ b/src/test/java/com/camilolopes/readerweb/dbunit/DBUnitConfigurationTest.java @@ -1,30 +1,30 @@ package com.camilolopes.readerweb.dbunit; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:**/OrderPersistenceTests-context.xml"}) @TransactionConfiguration(defaultRollback=true,transactionManager="transactionManager") @Transactional public class DBUnitConfigurationTest extends DBUnitConfiguration{ @Before public void setUp() throws Exception { getSetUpOperation(); } @Test public void testConectionDataSet() throws Exception { assertNotNull(getDataSet()); int rowCount = getDataSet().getTable("user").getRowCount(); - int expectedTotalElement = 1; - assertEquals(expectedTotalElement,rowCount); + int atLeastRecord = 1; + assertTrue(rowCount>= atLeastRecord); } }
true
true
public void testConectionDataSet() throws Exception { assertNotNull(getDataSet()); int rowCount = getDataSet().getTable("user").getRowCount(); int expectedTotalElement = 1; assertEquals(expectedTotalElement,rowCount); }
public void testConectionDataSet() throws Exception { assertNotNull(getDataSet()); int rowCount = getDataSet().getTable("user").getRowCount(); int atLeastRecord = 1; assertTrue(rowCount>= atLeastRecord); }
diff --git a/eXoApplication/faq/webapp/src/main/java/org/exoplatform/faq/webui/popup/UIResponseForm.java b/eXoApplication/faq/webapp/src/main/java/org/exoplatform/faq/webui/popup/UIResponseForm.java index 24030633a..96f8a256f 100644 --- a/eXoApplication/faq/webapp/src/main/java/org/exoplatform/faq/webui/popup/UIResponseForm.java +++ b/eXoApplication/faq/webapp/src/main/java/org/exoplatform/faq/webui/popup/UIResponseForm.java @@ -1,707 +1,712 @@ /* * Copyright (C) 2003-2008 eXo Platform SAS. * * 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.faq.webui.popup; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import org.exoplatform.container.PortalContainer; import org.exoplatform.faq.service.Category; import org.exoplatform.faq.service.FAQService; import org.exoplatform.faq.service.FAQSetting; import org.exoplatform.faq.service.FileAttachment; import org.exoplatform.faq.service.Question; import org.exoplatform.faq.service.QuestionLanguage; import org.exoplatform.faq.service.impl.MultiLanguages; import org.exoplatform.faq.webui.FAQUtils; import org.exoplatform.faq.webui.UIFAQContainer; import org.exoplatform.faq.webui.UIFAQPortlet; import org.exoplatform.faq.webui.UIQuestions; import org.exoplatform.faq.webui.ValidatorDataInput; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIApplication; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.core.model.SelectItemOption; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormCheckBoxInput; import org.exoplatform.webui.form.UIFormInputInfo; import org.exoplatform.webui.form.UIFormInputWithActions; import org.exoplatform.webui.form.UIFormSelectBox; import org.exoplatform.webui.form.UIFormStringInput; import org.exoplatform.webui.form.UIFormTextAreaInput; import org.exoplatform.webui.form.UIFormWYSIWYGInput; import org.exoplatform.webui.form.UIFormInputWithActions.ActionData; /** * Created by The eXo Platform SAS * Author : Mai Van Ha * [email protected] * Apr 17, 2008 ,3:19:00 PM */ @ComponentConfig( lifecycle = UIFormLifecycle.class , template = "app:/templates/faq/webui/popup/UIResponseForm.gtmpl", events = { @EventConfig(listeners = UIResponseForm.AddNewAnswerActionListener.class), @EventConfig(listeners = UIResponseForm.SaveActionListener.class), @EventConfig(listeners = UIResponseForm.CancelActionListener.class), @EventConfig(listeners = UIResponseForm.AddRelationActionListener.class), @EventConfig(listeners = UIResponseForm.AttachmentActionListener.class), @EventConfig(listeners = UIResponseForm.RemoveAttachmentActionListener.class), @EventConfig(listeners = UIResponseForm.RemoveRelationActionListener.class), @EventConfig(listeners = UIResponseForm.ViewEditQuestionActionListener.class), @EventConfig(listeners = UIResponseForm.ChangeQuestionActionListener.class) } ) public class UIResponseForm extends UIForm implements UIPopupComponent { private static final String QUESTION_CONTENT = "QuestionContent" ; private static final String QUESTION_LANGUAGE = "Language" ; private static final String RESPONSE_CONTENT = "QuestionRespone" ; private static final String ATTATCH_MENTS = "QuestionAttach" ; private static final String REMOVE_FILE_ATTACH = "RemoveFile" ; private static final String FILE_ATTACHMENTS = "FileAttach" ; private static final String SHOW_ANSWER = "QuestionShowAnswer" ; private static final String IS_APPROVED = "IsApproved" ; private static Question question_ = null ; private static FAQService faqService = (FAQService)PortalContainer.getInstance().getComponentInstanceOfType(FAQService.class) ; private boolean isViewEditQuestion_ = true; private String labelContent_ = new String(); // form input : private UIFormStringInput questionContent_ ; private UIFormSelectBox questionLanguages_ ; private UIFormWYSIWYGInput responseQuestion_ ; private UIFormInputWithActions inputAttachment_ ; private UIFormCheckBoxInput checkShowAnswer_ ; private UIFormCheckBoxInput<Boolean> isApproved_ ; // question infor : private String questionId_ = new String() ; private List<String> listRelationQuestion = new ArrayList<String>() ; private List<String> listQuestIdRela = new ArrayList<String>() ; private List<FileAttachment> listFileAttach_ = new ArrayList<FileAttachment>() ; // form variable: private List<QuestionLanguage> listQuestionLanguage = new ArrayList<QuestionLanguage>() ; private List<SelectItemOption<String>> listLanguageToReponse = new ArrayList<SelectItemOption<String>>() ; @SuppressWarnings("unused") private String questionChanged_ = new String() ; @SuppressWarnings("unused") private String responseContent_ = new String () ; private String languageIsResponsed = "" ; private String link_ = "" ; private boolean isChildren_ = false ; private FAQSetting faqSetting_; private List<String> listResponse = new ArrayList<String>(); private List<String> listUserResponse = new ArrayList<String>(); private List<Date> listDateResponse = new ArrayList<Date>(); private int posOfResponse = 0; public void activate() throws Exception { } public void deActivate() throws Exception { } public String getLink() {return link_;} public void setLink(String link) { this.link_ = link;} public void setFAQSetting(FAQSetting faqSetting) {this.faqSetting_= faqSetting;} public UIResponseForm() throws Exception { isChildren_ = false ; questionContent_ = new UIFormTextAreaInput(QUESTION_CONTENT, QUESTION_CONTENT, null) ; responseQuestion_ = new UIFormWYSIWYGInput(RESPONSE_CONTENT, null, null , true) ; checkShowAnswer_ = new UIFormCheckBoxInput<Boolean>(SHOW_ANSWER, SHOW_ANSWER, false) ; isApproved_ = new UIFormCheckBoxInput<Boolean>(IS_APPROVED, IS_APPROVED, false) ; inputAttachment_ = new UIFormInputWithActions(ATTATCH_MENTS) ; inputAttachment_.addUIFormInput( new UIFormInputInfo(FILE_ATTACHMENTS, FILE_ATTACHMENTS, null) ) ; this.setActions(new String[]{"Attachment", "AddRelation", "Save", "Cancel"}) ; } @SuppressWarnings("unused") private int numberOfAnswer(){ return listResponse.size(); } public void setQuestionId(Question question, String languageViewed){ try{ if(listQuestIdRela!= null && !listQuestIdRela.isEmpty()) { listRelationQuestion.clear() ; listQuestIdRela.clear() ; } question_ = question ; listResponse.addAll(Arrays.asList(question.getAllResponses())); if(listResponse.size() == 1 && listResponse.get(0).trim().length() < 1){ listUserResponse.add(FAQUtils.getFullName(FAQUtils.getCurrentUser())); listDateResponse.add(new java.util.Date()); } else { listUserResponse.addAll(Arrays.asList(question.getResponseBy())); listDateResponse.addAll(Arrays.asList(question.getDateResponse())); } posOfResponse = 0; if(languageViewed != null && languageViewed.trim().length() > 0) { languageIsResponsed = languageViewed ; } else { languageIsResponsed = question.getLanguage(); } QuestionLanguage questionLanguage = new QuestionLanguage() ; questionLanguage.setLanguage(question.getLanguage()) ; questionLanguage.setQuestion(question.getQuestion()) ; if(question.getAllResponses() != null && question.getAllResponses().length > 0) { questionLanguage.setResponse(question.getAllResponses()) ; questionLanguage.setResponseBy(question.getResponseBy()); questionLanguage.setDateResponse(question.getDateResponse()); } else { questionLanguage.setResponse(new String[]{""}) ; } listQuestionLanguage.add(questionLanguage) ; listQuestionLanguage.addAll(faqService.getQuestionLanguages(question_.getId(), FAQUtils.getSystemProvider())) ; for(QuestionLanguage language : listQuestionLanguage) { listLanguageToReponse.add(new SelectItemOption<String>(language.getLanguage(), language.getLanguage())) ; if(language.getLanguage().equals(languageIsResponsed)) { questionChanged_ = language.getQuestion() ; questionContent_.setValue(language.getQuestion()) ; labelContent_ = language.getQuestion(); responseQuestion_.setValue(language.getResponse()[0]) ; } } this.setListRelation(); setListFileAttach(question.getAttachMent()) ; } catch (Exception e) { e.printStackTrace() ; } this.questionId_ = question.getId() ; checkShowAnswer_.setChecked(question_.isActivated()) ; isApproved_.setChecked(question_.isApproved()) ; try{ inputAttachment_.setActionField(FILE_ATTACHMENTS, getUploadFileList()) ; } catch (Exception e) { e.printStackTrace() ; } questionLanguages_ = new UIFormSelectBox(QUESTION_LANGUAGE, QUESTION_LANGUAGE, getListLanguageToReponse()) ; questionLanguages_.setSelectedValues(new String[]{languageIsResponsed}) ; questionLanguages_.setOnChange("ChangeQuestion") ; addChild(questionContent_) ; addChild(questionLanguages_) ; addChild(responseQuestion_) ; addChild(isApproved_) ; addChild(checkShowAnswer_) ; addChild(inputAttachment_) ; } public String getQuestionId(){ return questionId_ ; } public List<ActionData> getUploadFileList() { List<ActionData> uploadedFiles = new ArrayList<ActionData>() ; for(FileAttachment attachdata : listFileAttach_) { ActionData fileUpload = new ActionData() ; fileUpload.setActionListener("Download") ; fileUpload.setActionParameter(attachdata.getPath()); fileUpload.setActionType(ActionData.TYPE_ICON) ; fileUpload.setCssIconClass("AttachmentIcon") ; // "AttachmentIcon ZipFileIcon" fileUpload.setActionName(attachdata.getName() + " ("+attachdata.getSize()+" B)" ) ; fileUpload.setShowLabel(true) ; uploadedFiles.add(fileUpload) ; ActionData removeAction = new ActionData() ; removeAction.setActionListener("RemoveAttachment") ; removeAction.setActionName(REMOVE_FILE_ATTACH); removeAction.setActionParameter(attachdata.getPath()); removeAction.setCssIconClass("LabelLink"); removeAction.setActionType(ActionData.TYPE_LINK) ; uploadedFiles.add(removeAction) ; } return uploadedFiles ; } public void setListFileAttach(List<FileAttachment> listFileAttachment){ listFileAttach_.addAll(listFileAttachment) ; } public void setListFileAttach(FileAttachment fileAttachment){ listFileAttach_.add(fileAttachment) ; } @SuppressWarnings("unused") private List<FileAttachment> getListFile() { return listFileAttach_ ; } @SuppressWarnings("unused") private String getLanguageIsResponse() { return this.languageIsResponsed ; } public void refreshUploadFileList() throws Exception { ((UIFormInputWithActions)this.getChildById(ATTATCH_MENTS)).setActionField(FILE_ATTACHMENTS, getUploadFileList()) ; } private void setListRelation() throws Exception { String[] relations = question_.getRelations() ; this.setListIdQuesRela(Arrays.asList(relations)) ; if(relations != null && relations.length > 0) for(String relation : relations) { listRelationQuestion.add(faqService.getQuestionById(relation, FAQUtils.getSystemProvider()).getQuestion()) ; } } public List<String> getListRelation() { return listRelationQuestion ; } @SuppressWarnings("unused") private List<SelectItemOption<String>> getListLanguageToReponse() { return listLanguageToReponse ; } public List<String> getListIdQuesRela() { return this.listQuestIdRela ; } public void setListIdQuesRela(List<String> listId) { if(!listQuestIdRela.isEmpty()) { listQuestIdRela.clear() ; } listQuestIdRela.addAll(listId) ; } public void setListRelationQuestion(List<String> listQuestionContent) { this.listRelationQuestion.clear() ; this.listRelationQuestion.addAll(listQuestionContent) ; } @SuppressWarnings("unused") private List<String> getListRelationQuestion() { return this.listRelationQuestion ; } public void setIsChildren(boolean isChildren) { this.isChildren_ = isChildren ; this.removeChildById(QUESTION_CONTENT) ; this.removeChildById(QUESTION_LANGUAGE) ; this.removeChildById(RESPONSE_CONTENT) ; this.removeChildById(ATTATCH_MENTS) ; this.removeChildById(IS_APPROVED) ; this.removeChildById(SHOW_ANSWER) ; listFileAttach_.clear() ; listLanguageToReponse.clear() ; listQuestIdRela.clear() ; listQuestionLanguage.clear() ; listRelationQuestion.clear() ; } private boolean compareTowArraies(String[] array1, String[] array2){ List<String> list1 = new ArrayList<String>(); list1.addAll(Arrays.asList(array1)); int count = 0; for(String str : array2){ if(list1.contains(str)) count ++; } if(count == array1.length && count == array2.length) return true; return false; } // action : static public class SaveActionListener extends EventListener<UIResponseForm> { @SuppressWarnings("unchecked") public void execute(Event<UIResponseForm> event) throws Exception { ValidatorDataInput validatorDataInput = new ValidatorDataInput() ; UIResponseForm responseForm = event.getSource() ; String questionContent = ((UIFormTextAreaInput)responseForm.getChildById(QUESTION_CONTENT)).getValue() ; if(questionContent == null || questionContent.trim().length() < 1) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.question-null", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; return ; } questionContent = questionContent.replaceAll("<", "&lt;").replaceAll(">", "&gt;") ; UIFormWYSIWYGInput formWYSIWYGInput = responseForm.getChildById(RESPONSE_CONTENT) ; String responseQuestionContent = formWYSIWYGInput.getValue() ; java.util.Date date = new java.util.Date(); if(responseQuestionContent != null && responseQuestionContent.trim().length() >0 && validatorDataInput.fckContentIsNotEmpty(responseQuestionContent)) { if(!responseForm.listResponse.contains(responseQuestionContent)){ - responseForm.listResponse.set(responseForm.posOfResponse, responseQuestionContent); - responseForm.listDateResponse.set(responseForm.posOfResponse, date); - } - } else { + if(!responseForm.listResponse.isEmpty() && responseForm.listResponse.size() > 0){ + responseForm.listResponse.set(responseForm.posOfResponse, responseQuestionContent); + responseForm.listDateResponse.set(responseForm.posOfResponse, date); + } else { + responseForm.listResponse.add(responseQuestionContent); + responseForm.listDateResponse.add(date); + } + } + } else if(!responseForm.listResponse.isEmpty() && responseForm.listResponse.size() > 0){ responseForm.listResponse.remove(responseForm.posOfResponse); responseForm.listDateResponse.remove(responseForm.posOfResponse); } if(responseForm.listResponse.isEmpty()){ UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.response-null", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; return ; } if(question_.getLanguage().equals(responseForm.languageIsResponsed)) { question_.setQuestion(questionContent) ; if(!responseForm.compareTowArraies(question_.getAllResponses(), responseForm.listResponse.toArray(new String[]{}))){ question_.setResponseBy(responseForm.listUserResponse.toArray(new String[]{})); question_.setResponses(responseForm.listResponse.toArray(new String[]{})); question_.setDateResponse(responseForm.listDateResponse.toArray(new Date[]{})); } } else { question_.setQuestion(responseForm.listQuestionLanguage.get(0).getQuestion().replaceAll("<", "&lt;").replaceAll(">", "&gt;")) ; if(!responseForm.compareTowArraies(question_.getAllResponses(), responseForm.listQuestionLanguage.get(0).getResponse())){ question_.setResponseBy(responseForm.listUserResponse.toArray(new String[]{})); question_.setResponses(responseForm.listQuestionLanguage.get(0).getResponse()) ; question_.setDateResponse(responseForm.listDateResponse.toArray(new Date[]{})); } } for(QuestionLanguage questionLanguage : responseForm.listQuestionLanguage) { if(questionLanguage.getLanguage().equals(responseForm.languageIsResponsed) && !question_.getLanguage().equals(responseForm.languageIsResponsed)) { questionLanguage.setQuestion(questionContent) ; if(questionLanguage.getResponse() == null || !responseForm.compareTowArraies(questionLanguage.getResponse(), responseForm.listResponse.toArray(new String[]{}))){ questionLanguage.setResponseBy(responseForm.listUserResponse.toArray(new String[]{})); questionLanguage.setResponse(responseForm.listResponse.toArray(new String[]{})); questionLanguage.setDateResponse(responseForm.listDateResponse.toArray(new Date[]{})); } break; } } // set relateion of question: question_.setRelations(responseForm.getListIdQuesRela().toArray(new String[]{})) ; // set show question: question_.setApproved(((UIFormCheckBoxInput<Boolean>)responseForm.getChildById(IS_APPROVED)).isChecked()) ; question_.setActivated(((UIFormCheckBoxInput<Boolean>)responseForm.getChildById(SHOW_ANSWER)).isChecked()) ; question_.setAttachMent(responseForm.listFileAttach_) ; Node questionNode = null ; //link UIFAQPortlet portlet = responseForm.getAncestorOfType(UIFAQPortlet.class) ; UIQuestions questions = portlet.getChild(UIFAQContainer.class).getChild(UIQuestions.class) ; String link = responseForm.getLink().replaceFirst("UIResponseForm", "UIBreadcumbs").replaceFirst("Attachment", "ChangePath").replaceAll("&amp;", "&"); String selectedNode = Util.getUIPortal().getSelectedNode().getUri() ; String portalName = "/" + Util.getUIPortal().getName() ; if(link.indexOf(portalName) > 0) { if(link.indexOf(portalName + "/" + selectedNode) < 0){ link = link.replaceFirst(portalName, portalName + "/" + selectedNode) ; } } PortalRequestContext portalContext = Util.getPortalRequestContext(); String url = portalContext.getRequest().getRequestURL().toString(); url = url.replaceFirst("http://", "") ; url = url.substring(0, url.indexOf("/")) ; url = "http://" + url; String path = questions.getPathService(question_.getCategoryId())+"/"+question_.getCategoryId() ; link = link.replaceFirst("OBJECTID", path); link = url + link; question_.setLink(link) ; try{ FAQUtils.getEmailSetting(responseForm.faqSetting_, false, false); questionNode = faqService.saveQuestion(question_, false, FAQUtils.getSystemProvider(),responseForm.faqSetting_) ; MultiLanguages multiLanguages = new MultiLanguages() ; for(int i = 1; i < responseForm.listQuestionLanguage.size(); i ++) { multiLanguages.addLanguage(questionNode, responseForm.listQuestionLanguage.get(i)) ; } } catch (PathNotFoundException e) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIQuestions.msg.question-id-deleted", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; } catch (Exception e) { e.printStackTrace() ; } if(question_.getResponses() == null || question_.getResponses().trim().length() < 1) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.response-invalid", new String[]{question_.getLanguage()}, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; } //cancel if(!responseForm.isChildren_) { questions.setIsNotChangeLanguage() ; UIPopupAction popupAction = portlet.getChild(UIPopupAction.class) ; popupAction.deActivate() ; event.getRequestContext().addUIComponentToUpdateByAjax(popupAction) ; event.getRequestContext().addUIComponentToUpdateByAjax(questions) ; if(questionNode!= null && !questions.getCategoryId().equals(question_.getCategoryId())) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; Category category = faqService.getCategoryById(question_.getCategoryId(), FAQUtils.getSystemProvider()) ; uiApplication.addMessage(new ApplicationMessage("UIQuestions.msg.question-id-moved", new Object[]{category.getName()}, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; } } else { UIQuestionManagerForm questionManagerForm = responseForm.getParent() ; UIQuestionForm questionForm = questionManagerForm.getChild(UIQuestionForm.class) ; if(questionManagerForm.isEditQuestion && responseForm.getQuestionId().equals(questionForm.getQuestionId())) { questionForm.setIsChildOfManager(true) ; questionForm.setQuestionId(question_) ; } questionManagerForm.isResponseQuestion = false ; UIPopupContainer popupContainer = questionManagerForm.getParent() ; event.getRequestContext().addUIComponentToUpdateByAjax(popupContainer) ; } } } static public class CancelActionListener extends EventListener<UIResponseForm> { public void execute(Event<UIResponseForm> event) throws Exception { UIResponseForm response = event.getSource() ; UIFAQPortlet portlet = response.getAncestorOfType(UIFAQPortlet.class) ; if(!response.isChildren_) { UIPopupAction popupAction = portlet.getChild(UIPopupAction.class) ; popupAction.deActivate() ; event.getRequestContext().addUIComponentToUpdateByAjax(popupAction) ; } else { UIQuestionManagerForm questionManagerForm = portlet.findFirstComponentOfType(UIQuestionManagerForm.class) ; questionManagerForm.isResponseQuestion = false ; UIPopupContainer popupContainer = questionManagerForm.getAncestorOfType(UIPopupContainer.class) ; UIAttachMentForm attachMentForm = popupContainer.findFirstComponentOfType(UIAttachMentForm.class) ; if(attachMentForm != null) { UIPopupAction popupAction = popupContainer.getChild(UIPopupAction.class) ; popupAction.deActivate() ; } else { UIAddRelationForm addRelationForm = popupContainer.findFirstComponentOfType(UIAddRelationForm.class) ; if(addRelationForm != null) { UIPopupAction popupAction = popupContainer.getChild(UIPopupAction.class) ; popupAction.deActivate() ; } } event.getRequestContext().addUIComponentToUpdateByAjax(popupContainer) ; } } } static public class AddRelationActionListener extends EventListener<UIResponseForm> { public void execute(Event<UIResponseForm> event) throws Exception { UIResponseForm response = event.getSource() ; UIPopupContainer popupContainer = response.getAncestorOfType(UIPopupContainer.class); UIPopupAction popupAction = popupContainer.getChild(UIPopupAction.class).setRendered(true) ; UIAddRelationForm addRelationForm = popupAction.activate(UIAddRelationForm.class, 500) ; addRelationForm.setQuestionId(response.questionId_) ; addRelationForm.setRelationed(response.getListIdQuesRela()) ; event.getRequestContext().addUIComponentToUpdateByAjax(popupAction) ; } } static public class AttachmentActionListener extends EventListener<UIResponseForm> { public void execute(Event<UIResponseForm> event) throws Exception { UIResponseForm response = event.getSource() ; UIPopupContainer popupContainer = response.getAncestorOfType(UIPopupContainer.class) ; UIPopupAction uiChildPopup = popupContainer.getChild(UIPopupAction.class).setRendered(true) ; UIAttachMentForm attachMentForm = uiChildPopup.activate(UIAttachMentForm.class, 550) ; attachMentForm.setResponse(true) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiChildPopup) ; } } static public class RemoveAttachmentActionListener extends EventListener<UIResponseForm> { @SuppressWarnings("static-access") public void execute(Event<UIResponseForm> event) throws Exception { UIResponseForm questionForm = event.getSource() ; String attFileId = event.getRequestContext().getRequestParameter(OBJECTID); for (FileAttachment att : questionForm.listFileAttach_) { if (att.getPath()!= null && att.getPath().equals(attFileId)) { questionForm.listFileAttach_.remove(att) ; break; } else if(att.getId() != null && att.getId().equals(attFileId)) { questionForm.listFileAttach_.remove(att) ; break; } } questionForm.refreshUploadFileList() ; event.getRequestContext().addUIComponentToUpdateByAjax(questionForm) ; } } static public class RemoveRelationActionListener extends EventListener<UIResponseForm> { public void execute(Event<UIResponseForm> event) throws Exception { UIResponseForm questionForm = event.getSource() ; String quesId = event.getRequestContext().getRequestParameter(OBJECTID); for(int i = 0 ; i < questionForm.listQuestIdRela.size(); i ++) { if(questionForm.listQuestIdRela.get(i).equals(quesId)) { questionForm.listRelationQuestion.remove(i) ; break ; } } questionForm.listQuestIdRela.remove(quesId) ; event.getRequestContext().addUIComponentToUpdateByAjax(questionForm) ; } } static public class AddNewAnswerActionListener extends EventListener<UIResponseForm> { @SuppressWarnings("unchecked") public void execute(Event<UIResponseForm> event) throws Exception { UIResponseForm responseForm = event.getSource(); String pos = event.getRequestContext().getRequestParameter(OBJECTID); UIFormWYSIWYGInput formWYSIWYGInput = responseForm.getChildById(RESPONSE_CONTENT); String responseContent = formWYSIWYGInput.getValue(); java.util.Date date = new java.util.Date(); String user = FAQUtils.getFullName(FAQUtils.getCurrentUser()); if(pos.equals("New")){ ValidatorDataInput validatorDataInput = new ValidatorDataInput(); if(responseContent != null && validatorDataInput.fckContentIsNotEmpty(responseContent)){ if(!responseForm.listResponse.contains(responseContent)){ if(responseForm.listResponse.isEmpty()){ responseForm.listResponse.add(responseContent); responseForm.listDateResponse.add(date); responseForm.listUserResponse.add(user); } else { responseForm.listResponse.set(responseForm.posOfResponse, responseContent); responseForm.listDateResponse.set(responseForm.posOfResponse, date); } } responseForm.posOfResponse = responseForm.listResponse.size(); responseForm.listResponse.add(" "); responseForm.listDateResponse.add(date); responseForm.listUserResponse.add(user); formWYSIWYGInput.setValue(""); } else if(!responseForm.listResponse.isEmpty() && responseForm.listResponse.size() != responseForm.posOfResponse + 1){ responseForm.listResponse.remove(responseForm.posOfResponse); responseForm.listUserResponse.remove(responseForm.posOfResponse); responseForm.listDateResponse.remove(responseForm.posOfResponse); responseForm.posOfResponse = responseForm.listResponse.size(); responseForm.listResponse.add(" "); responseForm.listDateResponse.add(date); responseForm.listUserResponse.add(user); formWYSIWYGInput.setValue(""); } } else { int newPosResponse = Integer.parseInt(pos); if(newPosResponse == responseForm.posOfResponse) return; ValidatorDataInput validatorDataInput = new ValidatorDataInput(); if(responseContent == null || !validatorDataInput.fckContentIsNotEmpty(responseContent)){ responseForm.listResponse.remove(responseForm.posOfResponse); responseForm.listUserResponse.remove(responseForm.posOfResponse); responseForm.listDateResponse.remove(responseForm.posOfResponse); if(responseForm.posOfResponse < newPosResponse) newPosResponse--; } else if(!responseContent.equals(responseForm.listResponse.get(responseForm.posOfResponse))){ responseForm.listResponse.set(responseForm.posOfResponse, responseContent); responseForm.listDateResponse.set(responseForm.posOfResponse, date); } formWYSIWYGInput.setValue(responseForm.listResponse.get(newPosResponse)); responseForm.posOfResponse = newPosResponse; } event.getRequestContext().addUIComponentToUpdateByAjax(responseForm); } } static public class ViewEditQuestionActionListener extends EventListener<UIResponseForm> { public void execute(Event<UIResponseForm> event) throws Exception { UIResponseForm responseForm = event.getSource(); responseForm.isViewEditQuestion_ = true; event.getRequestContext().addUIComponentToUpdateByAjax(responseForm); } } static public class ChangeQuestionActionListener extends EventListener<UIResponseForm> { @SuppressWarnings("static-access") public void execute(Event<UIResponseForm> event) throws Exception { UIResponseForm responseForm = event.getSource() ; UIFormSelectBox formSelectBox = responseForm.getChildById(QUESTION_LANGUAGE) ; String language = formSelectBox.getValue() ; if(responseForm.languageIsResponsed != null && language.equals(responseForm.languageIsResponsed)) return ; UIFormWYSIWYGInput responseContent = responseForm.getChildById(RESPONSE_CONTENT) ; UIFormTextAreaInput questionContent = responseForm.getChildById(QUESTION_CONTENT) ; if(questionContent.getValue() == null || questionContent.getValue().trim().length() < 1) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.question-null", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; return ; } ValidatorDataInput validatorDataInput = new ValidatorDataInput(); java.util.Date date = new java.util.Date(); String user = FAQUtils.getFullName(FAQUtils.getCurrentUser()); for(QuestionLanguage questionLanguage : responseForm.listQuestionLanguage) { if(questionLanguage.getLanguage().equals(responseForm.languageIsResponsed)) { String content = responseContent.getValue(); if(content!= null && validatorDataInput.fckContentIsNotEmpty(content)) { if(!responseForm.listResponse.contains(content)){ if(responseForm.listResponse.isEmpty()){ responseForm.listResponse.add(content); responseForm.listDateResponse.add(date); responseForm.listUserResponse.add(user); } else { responseForm.listResponse.set(responseForm.posOfResponse, content); responseForm.listDateResponse.set(responseForm.posOfResponse, date); } } if(questionLanguage.getResponse() == null || !responseForm.compareTowArraies(questionLanguage.getResponse(),responseForm.listResponse.toArray(new String[]{}))) { //questionLanguage.setResponseBy(FAQUtils.getFullName(FAQUtils.getCurrentUser())); questionLanguage.setResponseBy(responseForm.listUserResponse.toArray(new String[]{})); questionLanguage.setResponse(responseForm.listResponse.toArray(new String[]{})) ; questionLanguage.setDateResponse(responseForm.listDateResponse.toArray(new Date[]{})); } } else { if(!responseForm.listResponse.isEmpty() && responseForm.listResponse.size() > responseForm.posOfResponse){ responseForm.listResponse.remove(responseForm.posOfResponse); responseForm.listDateResponse.remove(responseForm.posOfResponse); responseForm.listUserResponse.remove(responseForm.posOfResponse); } if(responseForm.listResponse.isEmpty()){ questionLanguage.setResponse(new String[]{" "}); questionLanguage.setDateResponse(null); questionLanguage.setResponseBy(null); } else { questionLanguage.setResponseBy(responseForm.listUserResponse.toArray(new String[]{})); questionLanguage.setResponse(responseForm.listResponse.toArray(new String[]{})) ; questionLanguage.setDateResponse(responseForm.listDateResponse.toArray(new Date[]{})); } } questionLanguage.setQuestion(questionContent.getValue().replaceAll("<", "&lt;").replaceAll(">", "&gt;")) ; break ; } } for(QuestionLanguage questionLanguage : responseForm.listQuestionLanguage) { if(questionLanguage.getLanguage().equals(language)) { responseForm.languageIsResponsed = language ; questionContent.setValue(questionLanguage.getQuestion()) ; responseForm.labelContent_ = questionLanguage.getQuestion(); responseContent.setValue(questionLanguage.getResponse()[0]) ; responseForm.posOfResponse = 0; responseForm.listResponse.clear(); responseForm.listResponse.addAll(Arrays.asList(questionLanguage.getResponse())); break ; } } responseForm.isViewEditQuestion_ = true; event.getRequestContext().addUIComponentToUpdateByAjax(responseForm) ; } } }
true
true
public void execute(Event<UIResponseForm> event) throws Exception { ValidatorDataInput validatorDataInput = new ValidatorDataInput() ; UIResponseForm responseForm = event.getSource() ; String questionContent = ((UIFormTextAreaInput)responseForm.getChildById(QUESTION_CONTENT)).getValue() ; if(questionContent == null || questionContent.trim().length() < 1) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.question-null", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; return ; } questionContent = questionContent.replaceAll("<", "&lt;").replaceAll(">", "&gt;") ; UIFormWYSIWYGInput formWYSIWYGInput = responseForm.getChildById(RESPONSE_CONTENT) ; String responseQuestionContent = formWYSIWYGInput.getValue() ; java.util.Date date = new java.util.Date(); if(responseQuestionContent != null && responseQuestionContent.trim().length() >0 && validatorDataInput.fckContentIsNotEmpty(responseQuestionContent)) { if(!responseForm.listResponse.contains(responseQuestionContent)){ responseForm.listResponse.set(responseForm.posOfResponse, responseQuestionContent); responseForm.listDateResponse.set(responseForm.posOfResponse, date); } } else { responseForm.listResponse.remove(responseForm.posOfResponse); responseForm.listDateResponse.remove(responseForm.posOfResponse); } if(responseForm.listResponse.isEmpty()){ UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.response-null", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; return ; } if(question_.getLanguage().equals(responseForm.languageIsResponsed)) { question_.setQuestion(questionContent) ; if(!responseForm.compareTowArraies(question_.getAllResponses(), responseForm.listResponse.toArray(new String[]{}))){ question_.setResponseBy(responseForm.listUserResponse.toArray(new String[]{})); question_.setResponses(responseForm.listResponse.toArray(new String[]{})); question_.setDateResponse(responseForm.listDateResponse.toArray(new Date[]{})); } } else { question_.setQuestion(responseForm.listQuestionLanguage.get(0).getQuestion().replaceAll("<", "&lt;").replaceAll(">", "&gt;")) ; if(!responseForm.compareTowArraies(question_.getAllResponses(), responseForm.listQuestionLanguage.get(0).getResponse())){ question_.setResponseBy(responseForm.listUserResponse.toArray(new String[]{})); question_.setResponses(responseForm.listQuestionLanguage.get(0).getResponse()) ; question_.setDateResponse(responseForm.listDateResponse.toArray(new Date[]{})); } } for(QuestionLanguage questionLanguage : responseForm.listQuestionLanguage) { if(questionLanguage.getLanguage().equals(responseForm.languageIsResponsed) && !question_.getLanguage().equals(responseForm.languageIsResponsed)) { questionLanguage.setQuestion(questionContent) ; if(questionLanguage.getResponse() == null || !responseForm.compareTowArraies(questionLanguage.getResponse(), responseForm.listResponse.toArray(new String[]{}))){ questionLanguage.setResponseBy(responseForm.listUserResponse.toArray(new String[]{})); questionLanguage.setResponse(responseForm.listResponse.toArray(new String[]{})); questionLanguage.setDateResponse(responseForm.listDateResponse.toArray(new Date[]{})); } break; } } // set relateion of question: question_.setRelations(responseForm.getListIdQuesRela().toArray(new String[]{})) ; // set show question: question_.setApproved(((UIFormCheckBoxInput<Boolean>)responseForm.getChildById(IS_APPROVED)).isChecked()) ; question_.setActivated(((UIFormCheckBoxInput<Boolean>)responseForm.getChildById(SHOW_ANSWER)).isChecked()) ; question_.setAttachMent(responseForm.listFileAttach_) ; Node questionNode = null ; //link UIFAQPortlet portlet = responseForm.getAncestorOfType(UIFAQPortlet.class) ; UIQuestions questions = portlet.getChild(UIFAQContainer.class).getChild(UIQuestions.class) ; String link = responseForm.getLink().replaceFirst("UIResponseForm", "UIBreadcumbs").replaceFirst("Attachment", "ChangePath").replaceAll("&amp;", "&"); String selectedNode = Util.getUIPortal().getSelectedNode().getUri() ; String portalName = "/" + Util.getUIPortal().getName() ; if(link.indexOf(portalName) > 0) { if(link.indexOf(portalName + "/" + selectedNode) < 0){ link = link.replaceFirst(portalName, portalName + "/" + selectedNode) ; } } PortalRequestContext portalContext = Util.getPortalRequestContext(); String url = portalContext.getRequest().getRequestURL().toString(); url = url.replaceFirst("http://", "") ; url = url.substring(0, url.indexOf("/")) ; url = "http://" + url; String path = questions.getPathService(question_.getCategoryId())+"/"+question_.getCategoryId() ; link = link.replaceFirst("OBJECTID", path); link = url + link; question_.setLink(link) ; try{ FAQUtils.getEmailSetting(responseForm.faqSetting_, false, false); questionNode = faqService.saveQuestion(question_, false, FAQUtils.getSystemProvider(),responseForm.faqSetting_) ; MultiLanguages multiLanguages = new MultiLanguages() ; for(int i = 1; i < responseForm.listQuestionLanguage.size(); i ++) { multiLanguages.addLanguage(questionNode, responseForm.listQuestionLanguage.get(i)) ; } } catch (PathNotFoundException e) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIQuestions.msg.question-id-deleted", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; } catch (Exception e) { e.printStackTrace() ; } if(question_.getResponses() == null || question_.getResponses().trim().length() < 1) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.response-invalid", new String[]{question_.getLanguage()}, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; } //cancel if(!responseForm.isChildren_) { questions.setIsNotChangeLanguage() ; UIPopupAction popupAction = portlet.getChild(UIPopupAction.class) ; popupAction.deActivate() ; event.getRequestContext().addUIComponentToUpdateByAjax(popupAction) ; event.getRequestContext().addUIComponentToUpdateByAjax(questions) ; if(questionNode!= null && !questions.getCategoryId().equals(question_.getCategoryId())) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; Category category = faqService.getCategoryById(question_.getCategoryId(), FAQUtils.getSystemProvider()) ; uiApplication.addMessage(new ApplicationMessage("UIQuestions.msg.question-id-moved", new Object[]{category.getName()}, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; } } else { UIQuestionManagerForm questionManagerForm = responseForm.getParent() ; UIQuestionForm questionForm = questionManagerForm.getChild(UIQuestionForm.class) ; if(questionManagerForm.isEditQuestion && responseForm.getQuestionId().equals(questionForm.getQuestionId())) { questionForm.setIsChildOfManager(true) ; questionForm.setQuestionId(question_) ; } questionManagerForm.isResponseQuestion = false ; UIPopupContainer popupContainer = questionManagerForm.getParent() ; event.getRequestContext().addUIComponentToUpdateByAjax(popupContainer) ; } }
public void execute(Event<UIResponseForm> event) throws Exception { ValidatorDataInput validatorDataInput = new ValidatorDataInput() ; UIResponseForm responseForm = event.getSource() ; String questionContent = ((UIFormTextAreaInput)responseForm.getChildById(QUESTION_CONTENT)).getValue() ; if(questionContent == null || questionContent.trim().length() < 1) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.question-null", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; return ; } questionContent = questionContent.replaceAll("<", "&lt;").replaceAll(">", "&gt;") ; UIFormWYSIWYGInput formWYSIWYGInput = responseForm.getChildById(RESPONSE_CONTENT) ; String responseQuestionContent = formWYSIWYGInput.getValue() ; java.util.Date date = new java.util.Date(); if(responseQuestionContent != null && responseQuestionContent.trim().length() >0 && validatorDataInput.fckContentIsNotEmpty(responseQuestionContent)) { if(!responseForm.listResponse.contains(responseQuestionContent)){ if(!responseForm.listResponse.isEmpty() && responseForm.listResponse.size() > 0){ responseForm.listResponse.set(responseForm.posOfResponse, responseQuestionContent); responseForm.listDateResponse.set(responseForm.posOfResponse, date); } else { responseForm.listResponse.add(responseQuestionContent); responseForm.listDateResponse.add(date); } } } else if(!responseForm.listResponse.isEmpty() && responseForm.listResponse.size() > 0){ responseForm.listResponse.remove(responseForm.posOfResponse); responseForm.listDateResponse.remove(responseForm.posOfResponse); } if(responseForm.listResponse.isEmpty()){ UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.response-null", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; return ; } if(question_.getLanguage().equals(responseForm.languageIsResponsed)) { question_.setQuestion(questionContent) ; if(!responseForm.compareTowArraies(question_.getAllResponses(), responseForm.listResponse.toArray(new String[]{}))){ question_.setResponseBy(responseForm.listUserResponse.toArray(new String[]{})); question_.setResponses(responseForm.listResponse.toArray(new String[]{})); question_.setDateResponse(responseForm.listDateResponse.toArray(new Date[]{})); } } else { question_.setQuestion(responseForm.listQuestionLanguage.get(0).getQuestion().replaceAll("<", "&lt;").replaceAll(">", "&gt;")) ; if(!responseForm.compareTowArraies(question_.getAllResponses(), responseForm.listQuestionLanguage.get(0).getResponse())){ question_.setResponseBy(responseForm.listUserResponse.toArray(new String[]{})); question_.setResponses(responseForm.listQuestionLanguage.get(0).getResponse()) ; question_.setDateResponse(responseForm.listDateResponse.toArray(new Date[]{})); } } for(QuestionLanguage questionLanguage : responseForm.listQuestionLanguage) { if(questionLanguage.getLanguage().equals(responseForm.languageIsResponsed) && !question_.getLanguage().equals(responseForm.languageIsResponsed)) { questionLanguage.setQuestion(questionContent) ; if(questionLanguage.getResponse() == null || !responseForm.compareTowArraies(questionLanguage.getResponse(), responseForm.listResponse.toArray(new String[]{}))){ questionLanguage.setResponseBy(responseForm.listUserResponse.toArray(new String[]{})); questionLanguage.setResponse(responseForm.listResponse.toArray(new String[]{})); questionLanguage.setDateResponse(responseForm.listDateResponse.toArray(new Date[]{})); } break; } } // set relateion of question: question_.setRelations(responseForm.getListIdQuesRela().toArray(new String[]{})) ; // set show question: question_.setApproved(((UIFormCheckBoxInput<Boolean>)responseForm.getChildById(IS_APPROVED)).isChecked()) ; question_.setActivated(((UIFormCheckBoxInput<Boolean>)responseForm.getChildById(SHOW_ANSWER)).isChecked()) ; question_.setAttachMent(responseForm.listFileAttach_) ; Node questionNode = null ; //link UIFAQPortlet portlet = responseForm.getAncestorOfType(UIFAQPortlet.class) ; UIQuestions questions = portlet.getChild(UIFAQContainer.class).getChild(UIQuestions.class) ; String link = responseForm.getLink().replaceFirst("UIResponseForm", "UIBreadcumbs").replaceFirst("Attachment", "ChangePath").replaceAll("&amp;", "&"); String selectedNode = Util.getUIPortal().getSelectedNode().getUri() ; String portalName = "/" + Util.getUIPortal().getName() ; if(link.indexOf(portalName) > 0) { if(link.indexOf(portalName + "/" + selectedNode) < 0){ link = link.replaceFirst(portalName, portalName + "/" + selectedNode) ; } } PortalRequestContext portalContext = Util.getPortalRequestContext(); String url = portalContext.getRequest().getRequestURL().toString(); url = url.replaceFirst("http://", "") ; url = url.substring(0, url.indexOf("/")) ; url = "http://" + url; String path = questions.getPathService(question_.getCategoryId())+"/"+question_.getCategoryId() ; link = link.replaceFirst("OBJECTID", path); link = url + link; question_.setLink(link) ; try{ FAQUtils.getEmailSetting(responseForm.faqSetting_, false, false); questionNode = faqService.saveQuestion(question_, false, FAQUtils.getSystemProvider(),responseForm.faqSetting_) ; MultiLanguages multiLanguages = new MultiLanguages() ; for(int i = 1; i < responseForm.listQuestionLanguage.size(); i ++) { multiLanguages.addLanguage(questionNode, responseForm.listQuestionLanguage.get(i)) ; } } catch (PathNotFoundException e) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIQuestions.msg.question-id-deleted", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; } catch (Exception e) { e.printStackTrace() ; } if(question_.getResponses() == null || question_.getResponses().trim().length() < 1) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.response-invalid", new String[]{question_.getLanguage()}, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; } //cancel if(!responseForm.isChildren_) { questions.setIsNotChangeLanguage() ; UIPopupAction popupAction = portlet.getChild(UIPopupAction.class) ; popupAction.deActivate() ; event.getRequestContext().addUIComponentToUpdateByAjax(popupAction) ; event.getRequestContext().addUIComponentToUpdateByAjax(questions) ; if(questionNode!= null && !questions.getCategoryId().equals(question_.getCategoryId())) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; Category category = faqService.getCategoryById(question_.getCategoryId(), FAQUtils.getSystemProvider()) ; uiApplication.addMessage(new ApplicationMessage("UIQuestions.msg.question-id-moved", new Object[]{category.getName()}, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; } } else { UIQuestionManagerForm questionManagerForm = responseForm.getParent() ; UIQuestionForm questionForm = questionManagerForm.getChild(UIQuestionForm.class) ; if(questionManagerForm.isEditQuestion && responseForm.getQuestionId().equals(questionForm.getQuestionId())) { questionForm.setIsChildOfManager(true) ; questionForm.setQuestionId(question_) ; } questionManagerForm.isResponseQuestion = false ; UIPopupContainer popupContainer = questionManagerForm.getParent() ; event.getRequestContext().addUIComponentToUpdateByAjax(popupContainer) ; } }
diff --git a/sch-kp-web/src/main/java/hu/sch/web/kp/pages/admin/CreateNewPerson.java b/sch-kp-web/src/main/java/hu/sch/web/kp/pages/admin/CreateNewPerson.java index a26393ae..6bfd7f69 100644 --- a/sch-kp-web/src/main/java/hu/sch/web/kp/pages/admin/CreateNewPerson.java +++ b/sch-kp-web/src/main/java/hu/sch/web/kp/pages/admin/CreateNewPerson.java @@ -1,102 +1,104 @@ /** * Copyright (c) 2009, Peter Major * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Peter Major nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the Kir-Dev Team, Hungary * and its contributors. * * THIS SOFTWARE IS PROVIDED BY Peter Major ''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 Peter Major BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package hu.sch.web.kp.pages.admin; import hu.sch.domain.profile.Person; import hu.sch.services.exceptions.PersonNotFoundException; import hu.sch.web.error.NotFound; import hu.sch.web.kp.templates.SecuredPageTemplate; import hu.sch.web.profile.pages.admin.AdminPage; import org.apache.wicket.PageParameters; import org.apache.wicket.RestartResponseException; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.model.CompoundPropertyModel; /** * * @author aldaris */ public class CreateNewPerson extends SecuredPageTemplate { private Person person = new Person(); public CreateNewPerson() { if (!isCurrentUserAdmin()) { throw new RestartResponseException(NotFound.class); } Form<Person> form = new Form<Person>("form", new CompoundPropertyModel<Person>(person)) { @Override protected void onSubmit() { person.setStudentUserStatus("urn:mace:terena.org:schac:status:sch.hu:student_status:other"); person.setStatus("Active"); ldapManager.bindPerson(person); setResponsePage(AdminPage.class, new PageParameters("uid=" + person.getUid())); return; } }; final WebMarkupContainer wmc = new WebMarkupContainer("wmc"); TextField<String> uidTF = new TextField<String>("uid"); final Label notifier = new Label("notifier", ""); AjaxFormComponentUpdatingBehavior afcup = new AjaxFormComponentUpdatingBehavior("onblur") { @Override protected void onUpdate(AjaxRequestTarget target) { - try { - ldapManager.getPersonByUid(person.getUid()); - notifier.setDefaultModelObject("Foglalt uid!"); - } catch (PersonNotFoundException pnfe) { - notifier.setDefaultModelObject("Szabad uid"); + if (person.getUid() != null) { + try { + ldapManager.getPersonByUid(person.getUid()); + notifier.setDefaultModelObject("Foglalt uid!"); + } catch (PersonNotFoundException pnfe) { + notifier.setDefaultModelObject("Szabad uid"); + } } if (target != null) { target.addComponent(wmc); } } }; uidTF.add(afcup); wmc.add(uidTF); wmc.add(notifier); wmc.setOutputMarkupId(true); form.add(wmc); form.add(new TextField<String>("lastName")); form.add(new TextField<String>("firstName")); form.add(new TextField<String>("mail")); add(form); } }
true
true
public CreateNewPerson() { if (!isCurrentUserAdmin()) { throw new RestartResponseException(NotFound.class); } Form<Person> form = new Form<Person>("form", new CompoundPropertyModel<Person>(person)) { @Override protected void onSubmit() { person.setStudentUserStatus("urn:mace:terena.org:schac:status:sch.hu:student_status:other"); person.setStatus("Active"); ldapManager.bindPerson(person); setResponsePage(AdminPage.class, new PageParameters("uid=" + person.getUid())); return; } }; final WebMarkupContainer wmc = new WebMarkupContainer("wmc"); TextField<String> uidTF = new TextField<String>("uid"); final Label notifier = new Label("notifier", ""); AjaxFormComponentUpdatingBehavior afcup = new AjaxFormComponentUpdatingBehavior("onblur") { @Override protected void onUpdate(AjaxRequestTarget target) { try { ldapManager.getPersonByUid(person.getUid()); notifier.setDefaultModelObject("Foglalt uid!"); } catch (PersonNotFoundException pnfe) { notifier.setDefaultModelObject("Szabad uid"); } if (target != null) { target.addComponent(wmc); } } }; uidTF.add(afcup); wmc.add(uidTF); wmc.add(notifier); wmc.setOutputMarkupId(true); form.add(wmc); form.add(new TextField<String>("lastName")); form.add(new TextField<String>("firstName")); form.add(new TextField<String>("mail")); add(form); }
public CreateNewPerson() { if (!isCurrentUserAdmin()) { throw new RestartResponseException(NotFound.class); } Form<Person> form = new Form<Person>("form", new CompoundPropertyModel<Person>(person)) { @Override protected void onSubmit() { person.setStudentUserStatus("urn:mace:terena.org:schac:status:sch.hu:student_status:other"); person.setStatus("Active"); ldapManager.bindPerson(person); setResponsePage(AdminPage.class, new PageParameters("uid=" + person.getUid())); return; } }; final WebMarkupContainer wmc = new WebMarkupContainer("wmc"); TextField<String> uidTF = new TextField<String>("uid"); final Label notifier = new Label("notifier", ""); AjaxFormComponentUpdatingBehavior afcup = new AjaxFormComponentUpdatingBehavior("onblur") { @Override protected void onUpdate(AjaxRequestTarget target) { if (person.getUid() != null) { try { ldapManager.getPersonByUid(person.getUid()); notifier.setDefaultModelObject("Foglalt uid!"); } catch (PersonNotFoundException pnfe) { notifier.setDefaultModelObject("Szabad uid"); } } if (target != null) { target.addComponent(wmc); } } }; uidTF.add(afcup); wmc.add(uidTF); wmc.add(notifier); wmc.setOutputMarkupId(true); form.add(wmc); form.add(new TextField<String>("lastName")); form.add(new TextField<String>("firstName")); form.add(new TextField<String>("mail")); add(form); }
diff --git a/src/com/buildbotwatcher/BuildActivity.java b/src/com/buildbotwatcher/BuildActivity.java index 02a99c9..387fd50 100644 --- a/src/com/buildbotwatcher/BuildActivity.java +++ b/src/com/buildbotwatcher/BuildActivity.java @@ -1,56 +1,60 @@ package com.buildbotwatcher; import java.sql.Time; import com.buildbotwatcher.worker.Build; import com.buildbotwatcher.worker.Builder; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import android.widget.TextView; public class BuildActivity extends Activity { private Build _build; private Builder _builder; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.build); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { getActionBar().setDisplayHomeAsUpEnabled(true); } Bundle bundle = getIntent().getExtras(); _build = (Build) bundle.get("build"); _builder = (Builder) bundle.get("builder"); setTitle(String.valueOf(_build.getNumber())); - ((TextView) findViewById(R.id.result)).setText(_build.getText().get("build")); + TextView res = (TextView) findViewById(R.id.result); + if (_build.getText().containsKey("build")) + res.setText(_build.getText().get("build")); + else + res.setText(String.format(getResources().getString(R.string.build_failure), _build.getText().get("failed"))); ((TextView) findViewById(R.id.builder)).setText(_builder.getName()); ((TextView) findViewById(R.id.number)).setText(String.valueOf(_build.getNumber())); ((TextView) findViewById(R.id.reason)).setText(String.valueOf(_build.getReason())); ((TextView) findViewById(R.id.slave)).setText(_build.getSlaveName()); ((TextView) findViewById(R.id.start)).setText(_build.getTimeStart().toLocaleString()); ((TextView) findViewById(R.id.end)).setText(_build.getTimeEnd().toLocaleString()); Time duration = new Time(_build.getTimeEnd().getTime() - _build.getTimeStart().getTime()); ((TextView) findViewById(R.id.duration)).setText(String.format("%02d:%02d", duration.getMinutes(), duration.getSeconds())); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent intent = new Intent(this, BuilderActivity.class); intent.putExtra("builder", _builder); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.build); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { getActionBar().setDisplayHomeAsUpEnabled(true); } Bundle bundle = getIntent().getExtras(); _build = (Build) bundle.get("build"); _builder = (Builder) bundle.get("builder"); setTitle(String.valueOf(_build.getNumber())); ((TextView) findViewById(R.id.result)).setText(_build.getText().get("build")); ((TextView) findViewById(R.id.builder)).setText(_builder.getName()); ((TextView) findViewById(R.id.number)).setText(String.valueOf(_build.getNumber())); ((TextView) findViewById(R.id.reason)).setText(String.valueOf(_build.getReason())); ((TextView) findViewById(R.id.slave)).setText(_build.getSlaveName()); ((TextView) findViewById(R.id.start)).setText(_build.getTimeStart().toLocaleString()); ((TextView) findViewById(R.id.end)).setText(_build.getTimeEnd().toLocaleString()); Time duration = new Time(_build.getTimeEnd().getTime() - _build.getTimeStart().getTime()); ((TextView) findViewById(R.id.duration)).setText(String.format("%02d:%02d", duration.getMinutes(), duration.getSeconds())); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.build); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { getActionBar().setDisplayHomeAsUpEnabled(true); } Bundle bundle = getIntent().getExtras(); _build = (Build) bundle.get("build"); _builder = (Builder) bundle.get("builder"); setTitle(String.valueOf(_build.getNumber())); TextView res = (TextView) findViewById(R.id.result); if (_build.getText().containsKey("build")) res.setText(_build.getText().get("build")); else res.setText(String.format(getResources().getString(R.string.build_failure), _build.getText().get("failed"))); ((TextView) findViewById(R.id.builder)).setText(_builder.getName()); ((TextView) findViewById(R.id.number)).setText(String.valueOf(_build.getNumber())); ((TextView) findViewById(R.id.reason)).setText(String.valueOf(_build.getReason())); ((TextView) findViewById(R.id.slave)).setText(_build.getSlaveName()); ((TextView) findViewById(R.id.start)).setText(_build.getTimeStart().toLocaleString()); ((TextView) findViewById(R.id.end)).setText(_build.getTimeEnd().toLocaleString()); Time duration = new Time(_build.getTimeEnd().getTime() - _build.getTimeStart().getTime()); ((TextView) findViewById(R.id.duration)).setText(String.format("%02d:%02d", duration.getMinutes(), duration.getSeconds())); }
diff --git a/classes/com/sapienter/jbilling/server/order/CurrentOrder.java b/classes/com/sapienter/jbilling/server/order/CurrentOrder.java index d5ab2ad5..93f8a314 100644 --- a/classes/com/sapienter/jbilling/server/order/CurrentOrder.java +++ b/classes/com/sapienter/jbilling/server/order/CurrentOrder.java @@ -1,240 +1,241 @@ /* jBilling - The Enterprise Open Source Billing System Copyright (C) 2003-2009 Enterprise jBilling Software Ltd. and Emiliano Conde This file is part of jbilling. jbilling 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. jbilling 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 jbilling. If not, see <http://www.gnu.org/licenses/>. */ package com.sapienter.jbilling.server.order; import java.util.Date; import java.util.GregorianCalendar; import java.util.ResourceBundle; import org.apache.log4j.Logger; import com.sapienter.jbilling.common.SessionInternalError; import com.sapienter.jbilling.common.Util; import com.sapienter.jbilling.server.order.db.OrderDAS; import com.sapienter.jbilling.server.order.db.OrderDTO; import com.sapienter.jbilling.server.user.EntityBL; import com.sapienter.jbilling.server.user.UserBL; import com.sapienter.jbilling.server.util.Constants; import com.sapienter.jbilling.server.util.Context; import com.sapienter.jbilling.server.util.MapPeriodToCalendar; import com.sapienter.jbilling.server.util.audit.EventLogger; import com.sapienter.jbilling.server.util.db.CurrencyDTO; import java.util.List; import org.springmodules.cache.CachingModel; import org.springmodules.cache.FlushingModel; import org.springmodules.cache.provider.CacheProviderFacade; public class CurrentOrder { private final Date eventDate; private final Integer userId; private final UserBL user; private static final Logger LOG = Logger.getLogger(CurrentOrder.class); private OrderBL order = null; private final EventLogger eLogger = EventLogger.getInstance(); // cache management private CacheProviderFacade cache; private CachingModel cacheModel; private FlushingModel flushModel; protected CurrentOrder(Integer userId, Date eventDate) { LOG.debug("Current order constructed with user " + userId + " event date " + eventDate); if (userId == null || eventDate == null) { throw new IllegalArgumentException("user and date are mandatory for current " + "orders [" + userId + '-' + eventDate + ']'); } this.userId = userId; this.eventDate = eventDate; user = new UserBL(userId); cache = (CacheProviderFacade) Context.getBean(Context.Name.CACHE); cacheModel = (CachingModel) Context.getBean( Context.Name.CACHE_MODEL_RW); flushModel = (FlushingModel) Context.getBean( Context.Name.CACHE_FLUSH_MODEL_RW); } /** * Returns the ID of a one-time order, where to add an event. * Returns null if no applicable order * @return */ public Integer getCurrent() { // find in the cache Integer retValue = (Integer) cache.getFromCache(userId.toString() + Util.truncateDate(eventDate) , cacheModel); - if (retValue != null) { + // a hit is only a hit if the order is still active + if (retValue != null && new OrderDAS().find(retValue).getStatusId() == Constants.ORDER_STATUS_ACTIVE) { LOG.debug("cache hit for " + retValue); return retValue; } Integer subscriptionId = user.getEntity().getCustomer().getCurrentOrderId(); Integer entityId = null; Integer currencyId = null; if (subscriptionId == null) { return null; } try { order = new OrderBL(subscriptionId); entityId = order.getEntity().getBaseUserByUserId().getCompany().getId(); currencyId = order.getEntity().getCurrencyId(); } catch (Exception e) { throw new SessionInternalError("Error looking for main subscription order", CurrentOrder.class, e); } int futurePeriods = 0; boolean orderFound = false; do { LOG.debug("Calculating one timer date. Future periods " + futurePeriods); final Date newOrderDate = calculateDate(futurePeriods); if (newOrderDate == null) { // this is an error, there isn't a good date give the event date and // the main subscription order return null; } // now that the date is set, let's see if there is a one-time order for that date boolean somePresent = false; try { List<OrderDTO> rows = new OrderDAS().findOneTimersByDate(userId, newOrderDate); for (OrderDTO oneTime : rows) { somePresent = true; order.set(oneTime.getId()); if (order.getEntity().getStatusId().equals( Constants.ORDER_STATUS_FINISHED)) { LOG.debug("Found one timer " + oneTime.getId() + " but status is finished"); } else { orderFound = true; LOG.debug("Found existing one-time order"); break; } } } catch (Exception e) { throw new SessionInternalError( "Error looking for one time orders", CurrentOrder.class, e); } if (somePresent && !orderFound) { eLogger.auditBySystem(entityId, userId, Constants.TABLE_PUCHASE_ORDER, order.getEntity().getId(), EventLogger.MODULE_MEDIATION, EventLogger.CURRENT_ORDER_FINISHED, subscriptionId, null, null); } else if (!somePresent) { // there aren't any one-time orders for this date at all, create one create(newOrderDate, currencyId, entityId); orderFound = true; LOG.debug("Created new one-time order"); } // non present -> create new one with correct date // some present & none found -> try next date // some present & found -> use the found one futurePeriods++; } while (!orderFound); // the result is in 'order' retValue = order.getEntity().getId(); cache.putInCache(userId.toString() + Util.truncateDate(eventDate), cacheModel, retValue); LOG.debug("Returning " + retValue); return retValue; } /** * Assumes that the order has been set with the main subscription order * @return */ private Date calculateDate(int futurePeriods) { GregorianCalendar cal = new GregorianCalendar(); // start from the active since if it is there, otherwise the create time final Date startingTime = order.getEntity().getActiveSince() == null ? order .getEntity().getCreateDate() : order.getEntity() .getActiveSince(); // calculate the event date with the added future periods Date actualEventDate = eventDate; cal.setTime(actualEventDate); for(int f = 0; f < futurePeriods; f++) { cal.add(MapPeriodToCalendar.map(order.getEntity().getOrderPeriod().getPeriodUnit().getId()), order.getEntity().getOrderPeriod().getValue()); } actualEventDate = cal.getTime(); // is the starting date beyond the time frame of the main order? if (order.getEntity().getActiveSince() != null && actualEventDate.before(order.getEntity().getActiveSince())) { LOG.error("The event for date " + actualEventDate + " can not be assigned for " + "order " + order.getEntity().getId() + " active since " + order.getEntity().getActiveSince()); return null; } Date newOrderDate = startingTime; cal.setTime(startingTime); while (cal.getTime().before(actualEventDate)) { newOrderDate = cal.getTime(); cal.add(MapPeriodToCalendar.map(order.getEntity().getOrderPeriod().getPeriodUnit().getId()), order.getEntity().getOrderPeriod().getValue()); } // is the found date beyond the time frame of the main order? if (order.getEntity().getActiveUntil() != null && newOrderDate.after(order.getEntity().getActiveUntil())) { LOG.error("The event for date " + actualEventDate + " can not be assigned for " + "order " + order.getEntity().getId() + " active until " + order.getEntity().getActiveUntil()); return null; } return newOrderDate; } public Integer create(Date activeSince, Integer currencyId, Integer entityId) { OrderDTO currentOrder = new OrderDTO(); currentOrder.setCurrency(new CurrencyDTO(currencyId)); // notes try { EntityBL entity = new EntityBL(entityId); ResourceBundle bundle = ResourceBundle.getBundle("entityNotifications", entity.getLocale()); currentOrder.setNotes(bundle.getString("order.current.notes")); } catch (Exception e) { throw new SessionInternalError("Error setting the new order notes", CurrentOrder.class, e); } currentOrder.setActiveSince(activeSince); // create the order if (order == null) { order = new OrderBL(); } order.set(currentOrder); order.addRelationships(userId, Constants.ORDER_PERIOD_ONCE, currencyId); return order.create(entityId, null, currentOrder); } }
true
true
public Integer getCurrent() { // find in the cache Integer retValue = (Integer) cache.getFromCache(userId.toString() + Util.truncateDate(eventDate) , cacheModel); if (retValue != null) { LOG.debug("cache hit for " + retValue); return retValue; } Integer subscriptionId = user.getEntity().getCustomer().getCurrentOrderId(); Integer entityId = null; Integer currencyId = null; if (subscriptionId == null) { return null; } try { order = new OrderBL(subscriptionId); entityId = order.getEntity().getBaseUserByUserId().getCompany().getId(); currencyId = order.getEntity().getCurrencyId(); } catch (Exception e) { throw new SessionInternalError("Error looking for main subscription order", CurrentOrder.class, e); } int futurePeriods = 0; boolean orderFound = false; do { LOG.debug("Calculating one timer date. Future periods " + futurePeriods); final Date newOrderDate = calculateDate(futurePeriods); if (newOrderDate == null) { // this is an error, there isn't a good date give the event date and // the main subscription order return null; } // now that the date is set, let's see if there is a one-time order for that date boolean somePresent = false; try { List<OrderDTO> rows = new OrderDAS().findOneTimersByDate(userId, newOrderDate); for (OrderDTO oneTime : rows) { somePresent = true; order.set(oneTime.getId()); if (order.getEntity().getStatusId().equals( Constants.ORDER_STATUS_FINISHED)) { LOG.debug("Found one timer " + oneTime.getId() + " but status is finished"); } else { orderFound = true; LOG.debug("Found existing one-time order"); break; } } } catch (Exception e) { throw new SessionInternalError( "Error looking for one time orders", CurrentOrder.class, e); } if (somePresent && !orderFound) { eLogger.auditBySystem(entityId, userId, Constants.TABLE_PUCHASE_ORDER, order.getEntity().getId(), EventLogger.MODULE_MEDIATION, EventLogger.CURRENT_ORDER_FINISHED, subscriptionId, null, null); } else if (!somePresent) { // there aren't any one-time orders for this date at all, create one create(newOrderDate, currencyId, entityId); orderFound = true; LOG.debug("Created new one-time order"); } // non present -> create new one with correct date // some present & none found -> try next date // some present & found -> use the found one futurePeriods++; } while (!orderFound); // the result is in 'order' retValue = order.getEntity().getId(); cache.putInCache(userId.toString() + Util.truncateDate(eventDate), cacheModel, retValue); LOG.debug("Returning " + retValue); return retValue; }
public Integer getCurrent() { // find in the cache Integer retValue = (Integer) cache.getFromCache(userId.toString() + Util.truncateDate(eventDate) , cacheModel); // a hit is only a hit if the order is still active if (retValue != null && new OrderDAS().find(retValue).getStatusId() == Constants.ORDER_STATUS_ACTIVE) { LOG.debug("cache hit for " + retValue); return retValue; } Integer subscriptionId = user.getEntity().getCustomer().getCurrentOrderId(); Integer entityId = null; Integer currencyId = null; if (subscriptionId == null) { return null; } try { order = new OrderBL(subscriptionId); entityId = order.getEntity().getBaseUserByUserId().getCompany().getId(); currencyId = order.getEntity().getCurrencyId(); } catch (Exception e) { throw new SessionInternalError("Error looking for main subscription order", CurrentOrder.class, e); } int futurePeriods = 0; boolean orderFound = false; do { LOG.debug("Calculating one timer date. Future periods " + futurePeriods); final Date newOrderDate = calculateDate(futurePeriods); if (newOrderDate == null) { // this is an error, there isn't a good date give the event date and // the main subscription order return null; } // now that the date is set, let's see if there is a one-time order for that date boolean somePresent = false; try { List<OrderDTO> rows = new OrderDAS().findOneTimersByDate(userId, newOrderDate); for (OrderDTO oneTime : rows) { somePresent = true; order.set(oneTime.getId()); if (order.getEntity().getStatusId().equals( Constants.ORDER_STATUS_FINISHED)) { LOG.debug("Found one timer " + oneTime.getId() + " but status is finished"); } else { orderFound = true; LOG.debug("Found existing one-time order"); break; } } } catch (Exception e) { throw new SessionInternalError( "Error looking for one time orders", CurrentOrder.class, e); } if (somePresent && !orderFound) { eLogger.auditBySystem(entityId, userId, Constants.TABLE_PUCHASE_ORDER, order.getEntity().getId(), EventLogger.MODULE_MEDIATION, EventLogger.CURRENT_ORDER_FINISHED, subscriptionId, null, null); } else if (!somePresent) { // there aren't any one-time orders for this date at all, create one create(newOrderDate, currencyId, entityId); orderFound = true; LOG.debug("Created new one-time order"); } // non present -> create new one with correct date // some present & none found -> try next date // some present & found -> use the found one futurePeriods++; } while (!orderFound); // the result is in 'order' retValue = order.getEntity().getId(); cache.putInCache(userId.toString() + Util.truncateDate(eventDate), cacheModel, retValue); LOG.debug("Returning " + retValue); return retValue; }
diff --git a/tests/src/org/jboss/messaging/tests/integration/chunkmessage/ChunkTestBase.java b/tests/src/org/jboss/messaging/tests/integration/chunkmessage/ChunkTestBase.java index 798e769f8..2baab2595 100644 --- a/tests/src/org/jboss/messaging/tests/integration/chunkmessage/ChunkTestBase.java +++ b/tests/src/org/jboss/messaging/tests/integration/chunkmessage/ChunkTestBase.java @@ -1,485 +1,486 @@ /* * JBoss, Home of Professional Open Source * Copyright 2005-2008, Red Hat Middleware LLC, 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.jboss.messaging.tests.integration.chunkmessage; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import org.jboss.messaging.core.client.ClientConsumer; import org.jboss.messaging.core.client.ClientMessage; import org.jboss.messaging.core.client.ClientProducer; import org.jboss.messaging.core.client.ClientSession; import org.jboss.messaging.core.client.ClientSessionFactory; import org.jboss.messaging.core.client.ClientFileMessage; import org.jboss.messaging.core.exception.MessagingException; import org.jboss.messaging.core.logging.Logger; import org.jboss.messaging.core.message.impl.MessageImpl; import org.jboss.messaging.core.remoting.impl.ByteBufferWrapper; import org.jboss.messaging.core.remoting.spi.MessagingBuffer; import org.jboss.messaging.core.server.MessagingService; import org.jboss.messaging.tests.util.ServiceTestBase; import org.jboss.messaging.util.DataConstants; import org.jboss.messaging.util.SimpleString; /** * A ChunkTestBase * * @author <a href="mailto:[email protected]">Clebert Suconic</a> * * Created Oct 29, 2008 11:43:52 AM * * */ public class ChunkTestBase extends ServiceTestBase { // Constants ----------------------------------------------------- private static final Logger log = Logger.getLogger(ChunkTestBase.class); protected final SimpleString ADDRESS = new SimpleString("SimpleAddress"); protected MessagingService messagingService; // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- // Constructors -------------------------------------------------- // Public -------------------------------------------------------- // Package protected --------------------------------------------- // Protected ----------------------------------------------------- @Override protected void tearDown() throws Exception { super.tearDown(); } protected void testChunks(final boolean realFiles, final boolean useFile, final boolean preAck, final boolean sendingBlocking, final int numberOfMessages, final int numberOfIntegers, final int waitOnConsumer, final long delayDelivery) throws Exception { testChunks(realFiles, useFile, preAck, sendingBlocking, numberOfMessages, numberOfIntegers, waitOnConsumer, delayDelivery, -1, false); } protected void testChunks(final boolean realFiles, final boolean useFile, final boolean preAck, final boolean sendingBlocking, final int numberOfMessages, final int numberOfIntegers, final int waitOnConsumer, final long delayDelivery, final int producerWindow, final boolean testTime) throws Exception { clearData(); messagingService = createService(realFiles); messagingService.start(); try { ClientSessionFactory sf = createInVMFactory(); if (sendingBlocking) { sf.setBlockOnNonPersistentSend(true); sf.setBlockOnPersistentSend(true); sf.setBlockOnAcknowledge(true); } if (producerWindow > 0) { sf.setSendWindowSize(producerWindow); } ClientSession session = sf.createSession(null, null, false, true, false, preAck, 0); session.createQueue(ADDRESS, ADDRESS, null, true, false, true); long initialSize = messagingService.getServer().getPostOffice().getPagingManager().getGlobalSize(); ClientProducer producer = session.createProducer(ADDRESS); if (useFile) { File tmpData = createLargeFile(getTemporaryDir(), "someFile.dat", numberOfIntegers); for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = session.createFileMessage(true); ((ClientFileMessage)message).setFile(tmpData); message.putIntProperty(new SimpleString("counter-message"), i); long timeStart = System.currentTimeMillis(); if (delayDelivery > 0) { long time = System.currentTimeMillis(); message.putLongProperty(new SimpleString("original-time"), time); message.putLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME, time + delayDelivery); producer.send(message); } else { producer.send(message); } if (testTime) { System.out.println("Message sent in " + (System.currentTimeMillis() - timeStart)); } } } else { for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = session.createClientMessage(true); message.putIntProperty(new SimpleString("counter-message"), i); message.setBody(createLargeBuffer(numberOfIntegers)); long timeStart = System.currentTimeMillis(); if (delayDelivery > 0) { long time = System.currentTimeMillis(); message.putLongProperty(new SimpleString("original-time"), time); message.putLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME, time + delayDelivery); producer.send(message); } else { producer.send(message); } if (testTime) { System.out.println("Message sent in " + (System.currentTimeMillis() - timeStart)); } } } session.close(); if (realFiles) { messagingService.stop(); messagingService = createService(realFiles); messagingService.start(); sf = createInVMFactory(); } session = sf.createSession(null, null, false, true, true, preAck, 0); ClientConsumer consumer = null; if (realFiles) { consumer = session.createFileConsumer(new File(getClientLargeMessagesDir()), ADDRESS); } else { consumer = session.createConsumer(ADDRESS); } session.start(); for (int i = 0; i < numberOfMessages; i++) { long start = System.currentTimeMillis(); ClientMessage message = consumer.receive(waitOnConsumer + delayDelivery); assertNotNull(message); if (realFiles) { assertTrue (message instanceof ClientFileMessage); } if (testTime) { System.out.println("Message received in " + (System.currentTimeMillis() - start)); } start = System.currentTimeMillis(); if (delayDelivery > 0) { long originalTime = (Long)message.getProperty(new SimpleString("original-time")); assertTrue((System.currentTimeMillis() - originalTime) + "<" + delayDelivery, System.currentTimeMillis() - originalTime >= delayDelivery); } if (!preAck) { message.acknowledge(); } assertNotNull(message); if (delayDelivery <= 0) { // right now there is no guarantee of ordered delivered on multiple scheduledMessages assertEquals(i, ((Integer)message.getProperty(new SimpleString("counter-message"))).intValue()); } if (!testTime) { if (message instanceof ClientFileMessage) { checkFileRead(((ClientFileMessage)message).getFile(), numberOfIntegers); } else { MessagingBuffer buffer = message.getBody(); buffer.rewind(); assertEquals(numberOfIntegers * DataConstants.SIZE_INT, buffer.limit()); for (int b = 0; b < numberOfIntegers; b++) { assertEquals(b, buffer.getInt()); } } } } session.close(); - assertEquals(initialSize, messagingService.getServer().getPostOffice().getPagingManager().getGlobalSize()); + long globalSize = messagingService.getServer().getPostOffice().getPagingManager().getGlobalSize(); + assertTrue(globalSize == initialSize || globalSize == 0); assertEquals(0, messagingService.getServer().getPostOffice().getBinding(ADDRESS).getQueue().getDeliveringCount()); assertEquals(0, messagingService.getServer().getPostOffice().getBinding(ADDRESS).getQueue().getMessageCount()); validateNoFilesOnLargeDir(); } finally { try { messagingService.stop(); } catch (Throwable ignored) { } } } protected MessagingBuffer createLargeBuffer(final int numberOfIntegers) { ByteBuffer ioBuffer = ByteBuffer.allocate(DataConstants.SIZE_INT * numberOfIntegers); MessagingBuffer body = new ByteBufferWrapper(ioBuffer); for (int i = 0; i < numberOfIntegers; i++) { body.putInt(i); } body.flip(); return body; } protected ClientFileMessage createLargeClientMessage(final ClientSession session, final int numberOfIntegers) throws Exception { ClientFileMessage clientMessage = session.createFileMessage(true); File tmpFile = createLargeFile(getTemporaryDir(), "tmpUpload.data", numberOfIntegers); clientMessage.setFile(tmpFile); return clientMessage; } /** * @param name * @param numberOfIntegers * @return * @throws FileNotFoundException * @throws IOException */ protected File createLargeFile(final String directory, final String name, final int numberOfIntegers) throws FileNotFoundException, IOException { File tmpFile = new File(directory + "/" + name); log.info("Creating file " + tmpFile); RandomAccessFile random = new RandomAccessFile(tmpFile, "rw"); FileChannel channel = random.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(4 * 1000); for (int i = 0; i < numberOfIntegers; i++) { if (buffer.position() > 0 && i % 1000 == 0) { buffer.flip(); channel.write(buffer); buffer.clear(); } buffer.putInt(i); } if (buffer.position() > 0) { buffer.flip(); channel.write(buffer); } channel.close(); random.close(); log.info("file " + tmpFile + " created"); return tmpFile; } /** * @param session * @param queueToRead * @param numberOfIntegers * @throws MessagingException * @throws FileNotFoundException * @throws IOException */ protected void readMessage(final ClientSession session, final SimpleString queueToRead, final int numberOfIntegers) throws MessagingException, FileNotFoundException, IOException { session.start(); ClientConsumer consumer = session.createFileConsumer(new File(getClientLargeMessagesDir()), queueToRead); ClientMessage clientMessage = consumer.receive(5000); assertNotNull(clientMessage); if (!(clientMessage instanceof ClientFileMessage)) { System.out.println("Size = " + clientMessage.getBodySize()); } if (clientMessage instanceof ClientFileMessage) { assertTrue(clientMessage instanceof ClientFileMessage); ClientFileMessage fileClientMessage = (ClientFileMessage)clientMessage; assertNotNull(fileClientMessage); File receivedFile = fileClientMessage.getFile(); checkFileRead(receivedFile, numberOfIntegers); } clientMessage.acknowledge(); session.commit(); consumer.close(); } /** * @param receivedFile * @throws FileNotFoundException * @throws IOException */ protected void checkFileRead(final File receivedFile, final int numberOfIntegers) throws FileNotFoundException, IOException { RandomAccessFile random2 = new RandomAccessFile(receivedFile, "r"); FileChannel channel2 = random2.getChannel(); ByteBuffer buffer2 = ByteBuffer.allocate(1000 * 4); channel2.position(0l); for (int i = 0; i < numberOfIntegers;) { channel2.read(buffer2); buffer2.flip(); for (int j = 0; j < buffer2.limit() / 4; j++, i++) { assertEquals(i, buffer2.getInt()); } buffer2.clear(); } channel2.close(); } /** * Deleting a file on LargeDire is an asynchronous process. Wee need to keep looking for a while if the file hasn't been deleted yet */ protected void validateNoFilesOnLargeDir() throws Exception { File largeMessagesFileDir = new File(getLargeMessagesDir()); // Deleting the file is async... we keep looking for a period of the time until the file is really gone for (int i = 0; i < 100; i++) { if (largeMessagesFileDir.listFiles().length > 0) { Thread.sleep(10); } else { break; } } assertEquals(0, largeMessagesFileDir.listFiles().length); } // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- }
true
true
protected void testChunks(final boolean realFiles, final boolean useFile, final boolean preAck, final boolean sendingBlocking, final int numberOfMessages, final int numberOfIntegers, final int waitOnConsumer, final long delayDelivery, final int producerWindow, final boolean testTime) throws Exception { clearData(); messagingService = createService(realFiles); messagingService.start(); try { ClientSessionFactory sf = createInVMFactory(); if (sendingBlocking) { sf.setBlockOnNonPersistentSend(true); sf.setBlockOnPersistentSend(true); sf.setBlockOnAcknowledge(true); } if (producerWindow > 0) { sf.setSendWindowSize(producerWindow); } ClientSession session = sf.createSession(null, null, false, true, false, preAck, 0); session.createQueue(ADDRESS, ADDRESS, null, true, false, true); long initialSize = messagingService.getServer().getPostOffice().getPagingManager().getGlobalSize(); ClientProducer producer = session.createProducer(ADDRESS); if (useFile) { File tmpData = createLargeFile(getTemporaryDir(), "someFile.dat", numberOfIntegers); for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = session.createFileMessage(true); ((ClientFileMessage)message).setFile(tmpData); message.putIntProperty(new SimpleString("counter-message"), i); long timeStart = System.currentTimeMillis(); if (delayDelivery > 0) { long time = System.currentTimeMillis(); message.putLongProperty(new SimpleString("original-time"), time); message.putLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME, time + delayDelivery); producer.send(message); } else { producer.send(message); } if (testTime) { System.out.println("Message sent in " + (System.currentTimeMillis() - timeStart)); } } } else { for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = session.createClientMessage(true); message.putIntProperty(new SimpleString("counter-message"), i); message.setBody(createLargeBuffer(numberOfIntegers)); long timeStart = System.currentTimeMillis(); if (delayDelivery > 0) { long time = System.currentTimeMillis(); message.putLongProperty(new SimpleString("original-time"), time); message.putLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME, time + delayDelivery); producer.send(message); } else { producer.send(message); } if (testTime) { System.out.println("Message sent in " + (System.currentTimeMillis() - timeStart)); } } } session.close(); if (realFiles) { messagingService.stop(); messagingService = createService(realFiles); messagingService.start(); sf = createInVMFactory(); } session = sf.createSession(null, null, false, true, true, preAck, 0); ClientConsumer consumer = null; if (realFiles) { consumer = session.createFileConsumer(new File(getClientLargeMessagesDir()), ADDRESS); } else { consumer = session.createConsumer(ADDRESS); } session.start(); for (int i = 0; i < numberOfMessages; i++) { long start = System.currentTimeMillis(); ClientMessage message = consumer.receive(waitOnConsumer + delayDelivery); assertNotNull(message); if (realFiles) { assertTrue (message instanceof ClientFileMessage); } if (testTime) { System.out.println("Message received in " + (System.currentTimeMillis() - start)); } start = System.currentTimeMillis(); if (delayDelivery > 0) { long originalTime = (Long)message.getProperty(new SimpleString("original-time")); assertTrue((System.currentTimeMillis() - originalTime) + "<" + delayDelivery, System.currentTimeMillis() - originalTime >= delayDelivery); } if (!preAck) { message.acknowledge(); } assertNotNull(message); if (delayDelivery <= 0) { // right now there is no guarantee of ordered delivered on multiple scheduledMessages assertEquals(i, ((Integer)message.getProperty(new SimpleString("counter-message"))).intValue()); } if (!testTime) { if (message instanceof ClientFileMessage) { checkFileRead(((ClientFileMessage)message).getFile(), numberOfIntegers); } else { MessagingBuffer buffer = message.getBody(); buffer.rewind(); assertEquals(numberOfIntegers * DataConstants.SIZE_INT, buffer.limit()); for (int b = 0; b < numberOfIntegers; b++) { assertEquals(b, buffer.getInt()); } } } } session.close(); assertEquals(initialSize, messagingService.getServer().getPostOffice().getPagingManager().getGlobalSize()); assertEquals(0, messagingService.getServer().getPostOffice().getBinding(ADDRESS).getQueue().getDeliveringCount()); assertEquals(0, messagingService.getServer().getPostOffice().getBinding(ADDRESS).getQueue().getMessageCount()); validateNoFilesOnLargeDir(); } finally { try { messagingService.stop(); } catch (Throwable ignored) { } } }
protected void testChunks(final boolean realFiles, final boolean useFile, final boolean preAck, final boolean sendingBlocking, final int numberOfMessages, final int numberOfIntegers, final int waitOnConsumer, final long delayDelivery, final int producerWindow, final boolean testTime) throws Exception { clearData(); messagingService = createService(realFiles); messagingService.start(); try { ClientSessionFactory sf = createInVMFactory(); if (sendingBlocking) { sf.setBlockOnNonPersistentSend(true); sf.setBlockOnPersistentSend(true); sf.setBlockOnAcknowledge(true); } if (producerWindow > 0) { sf.setSendWindowSize(producerWindow); } ClientSession session = sf.createSession(null, null, false, true, false, preAck, 0); session.createQueue(ADDRESS, ADDRESS, null, true, false, true); long initialSize = messagingService.getServer().getPostOffice().getPagingManager().getGlobalSize(); ClientProducer producer = session.createProducer(ADDRESS); if (useFile) { File tmpData = createLargeFile(getTemporaryDir(), "someFile.dat", numberOfIntegers); for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = session.createFileMessage(true); ((ClientFileMessage)message).setFile(tmpData); message.putIntProperty(new SimpleString("counter-message"), i); long timeStart = System.currentTimeMillis(); if (delayDelivery > 0) { long time = System.currentTimeMillis(); message.putLongProperty(new SimpleString("original-time"), time); message.putLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME, time + delayDelivery); producer.send(message); } else { producer.send(message); } if (testTime) { System.out.println("Message sent in " + (System.currentTimeMillis() - timeStart)); } } } else { for (int i = 0; i < numberOfMessages; i++) { ClientMessage message = session.createClientMessage(true); message.putIntProperty(new SimpleString("counter-message"), i); message.setBody(createLargeBuffer(numberOfIntegers)); long timeStart = System.currentTimeMillis(); if (delayDelivery > 0) { long time = System.currentTimeMillis(); message.putLongProperty(new SimpleString("original-time"), time); message.putLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME, time + delayDelivery); producer.send(message); } else { producer.send(message); } if (testTime) { System.out.println("Message sent in " + (System.currentTimeMillis() - timeStart)); } } } session.close(); if (realFiles) { messagingService.stop(); messagingService = createService(realFiles); messagingService.start(); sf = createInVMFactory(); } session = sf.createSession(null, null, false, true, true, preAck, 0); ClientConsumer consumer = null; if (realFiles) { consumer = session.createFileConsumer(new File(getClientLargeMessagesDir()), ADDRESS); } else { consumer = session.createConsumer(ADDRESS); } session.start(); for (int i = 0; i < numberOfMessages; i++) { long start = System.currentTimeMillis(); ClientMessage message = consumer.receive(waitOnConsumer + delayDelivery); assertNotNull(message); if (realFiles) { assertTrue (message instanceof ClientFileMessage); } if (testTime) { System.out.println("Message received in " + (System.currentTimeMillis() - start)); } start = System.currentTimeMillis(); if (delayDelivery > 0) { long originalTime = (Long)message.getProperty(new SimpleString("original-time")); assertTrue((System.currentTimeMillis() - originalTime) + "<" + delayDelivery, System.currentTimeMillis() - originalTime >= delayDelivery); } if (!preAck) { message.acknowledge(); } assertNotNull(message); if (delayDelivery <= 0) { // right now there is no guarantee of ordered delivered on multiple scheduledMessages assertEquals(i, ((Integer)message.getProperty(new SimpleString("counter-message"))).intValue()); } if (!testTime) { if (message instanceof ClientFileMessage) { checkFileRead(((ClientFileMessage)message).getFile(), numberOfIntegers); } else { MessagingBuffer buffer = message.getBody(); buffer.rewind(); assertEquals(numberOfIntegers * DataConstants.SIZE_INT, buffer.limit()); for (int b = 0; b < numberOfIntegers; b++) { assertEquals(b, buffer.getInt()); } } } } session.close(); long globalSize = messagingService.getServer().getPostOffice().getPagingManager().getGlobalSize(); assertTrue(globalSize == initialSize || globalSize == 0); assertEquals(0, messagingService.getServer().getPostOffice().getBinding(ADDRESS).getQueue().getDeliveringCount()); assertEquals(0, messagingService.getServer().getPostOffice().getBinding(ADDRESS).getQueue().getMessageCount()); validateNoFilesOnLargeDir(); } finally { try { messagingService.stop(); } catch (Throwable ignored) { } } }
diff --git a/src/org/ligi/fast/BaseAppGatherAsyncTask.java b/src/org/ligi/fast/BaseAppGatherAsyncTask.java index d448d75..636ebd8 100644 --- a/src/org/ligi/fast/BaseAppGatherAsyncTask.java +++ b/src/org/ligi/fast/BaseAppGatherAsyncTask.java @@ -1,45 +1,45 @@ package org.ligi.fast; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import android.os.AsyncTask; import org.ligi.tracedroid.Log; import java.util.List; /** * Async-Task to Retrieve / Store Application Info needed by this App * * @author Marcus -ligi- Büschleb * <p/> * License GPLv3 */ public class BaseAppGatherAsyncTask extends AsyncTask<Void, AppInfo, Void> { private Context ctx; protected int appCount; public BaseAppGatherAsyncTask(Context ctx) { this.ctx = ctx; } @Override protected Void doInBackground(Void... params) { Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); try { List<ResolveInfo> resolveInfos = ctx.getPackageManager().queryIntentActivities(mainIntent, 0); appCount = resolveInfos.size(); for (ResolveInfo info : resolveInfos) { AppInfo act_appinfo = new AppInfo(ctx, info); publishProgress(act_appinfo); } } catch (Exception e) { - Log.d("Exception occured when getting activities skipping....!"); + Log.d("Exception occurred when getting activities skipping...!"); } return null; } }
true
true
protected Void doInBackground(Void... params) { Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); try { List<ResolveInfo> resolveInfos = ctx.getPackageManager().queryIntentActivities(mainIntent, 0); appCount = resolveInfos.size(); for (ResolveInfo info : resolveInfos) { AppInfo act_appinfo = new AppInfo(ctx, info); publishProgress(act_appinfo); } } catch (Exception e) { Log.d("Exception occured when getting activities skipping....!"); } return null; }
protected Void doInBackground(Void... params) { Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); try { List<ResolveInfo> resolveInfos = ctx.getPackageManager().queryIntentActivities(mainIntent, 0); appCount = resolveInfos.size(); for (ResolveInfo info : resolveInfos) { AppInfo act_appinfo = new AppInfo(ctx, info); publishProgress(act_appinfo); } } catch (Exception e) { Log.d("Exception occurred when getting activities skipping...!"); } return null; }
diff --git a/src/io/AidDAO.java b/src/io/AidDAO.java index f2d34ec..a98330f 100644 --- a/src/io/AidDAO.java +++ b/src/io/AidDAO.java @@ -1,814 +1,814 @@ /* Copyright (C) 2012 Nicholas Wright This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io; import java.awt.Image; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.LinkedList; import java.util.logging.Logger; import javax.imageio.ImageIO; import filter.FilterItem; import filter.FilterState; /** * Class for database communication. */ public class AidDAO{ private static final HashMap<String, String> prepStmts = new HashMap<String, String>(); protected static Logger logger = Logger.getLogger(AidDAO.class.getName()); protected final String RS_CLOSE_ERR = "Could not close ResultSet: "; protected final String SQL_OP_ERR = "MySQL operation failed: "; protected final ConnectionPool connPool; public AidDAO(ConnectionPool connPool){ this.connPool = connPool; } static{ init(); } /** * Initialize the class, preparing the statements needed for the methods. */ private static void init(){ generateStatements(); addPrepStmt("addCache" , "INSERT INTO cache (id) VALUES (?) ON DUPLICATE KEY UPDATE timestamp = NOW()"); addPrepStmt("addThumb" , "INSERT INTO thumbs (url, filename, thumb) VALUES(?,?,?)"); addPrepStmt("getThumb" , "SELECT thumb FROM thumbs WHERE url = ? ORDER BY filename ASC"); addPrepStmt("pending" , "SELECT count(*) FROM filter WHERE status = 1"); addPrepStmt("isCached" , "SELECT timestamp FROM `cache` WHERE `id` = ?"); addPrepStmt("isArchive" , "SELECT * FROM `archive` WHERE `id` = ?"); addPrepStmt("isDnw" , "SELECT * FROM `dnw` WHERE `id` = ?"); addPrepStmt("prune" , "DELETE FROM `cache` WHERE `timestamp` < ?"); addPrepStmt("isHashed" , "SELECT id FROM `index` WHERE `id` = ?"); - addPrepStmt("addIndex" , "INSERT INTO index (id, dir, filename, size, location) VALUES (?,?,?,?,(SELECT tag_id FROM location_tags WHERE location = ?)) "); + addPrepStmt("addIndex" , "INSERT INTO `index` (id, dir, filename, size, location) VALUES (?,?,?,?,(SELECT tag_id FROM location_tags WHERE location = ?)) "); addPrepStmt("deleteIndex" , "DELETE FROM index WHERE id = ?"); addPrepStmt("deleteFilter" , "DELETE FROM filter WHERE id = ?"); addPrepStmt("deleteDnw" , "DELETE FROM dnw WHERE id = ?"); addPrepStmt("deleteBlock" , "DELETE FROM block WHERE id = ?"); addPrepStmt("deleteArchive" , "DELETE FROM archive WHERE id = ?"); addPrepStmt("isBlacklisted" , "SELECT * FROM `block` WHERE `id` = ?"); addPrepStmt("getDirectory" , "SELECT id FROM dirlist WHERE dirpath = ?"); addPrepStmt("getFilename" , "SELECT id FROM filelist WHERE filename = ?"); addPrepStmt("getSetting" , "SELECT param FROM settings WHERE name = ?"); addPrepStmt("getPath" , "SELECT CONCAT(dirlist.dirpath,filelist.filename) FROM (select dir, filename FROM index WHERE id =?) AS a JOIN filelist ON a.filename=filelist.id Join dirlist on a.dir=dirlist.id"); addPrepStmt("hlUpdateBlock" , "INSERT IGNORE INTO block (id) VALUES (?)"); addPrepStmt("hlUpdateDnw" , "INSERT IGNORE INTO dnw (id) VALUES (?)"); addPrepStmt("addFilter" , "INSERT IGNORE INTO filter (id, board, reason, status) VALUES (?,?,?,?)"); addPrepStmt("updateFilter" , "UPDATE filter SET status = ? WHERE id = ?"); addPrepStmt("filterState" , "SELECT status FROM filter WHERE id = ?"); addPrepStmt("pendingFilter" , "SELECT board, reason, id FROM filter WHERE status = 1 ORDER BY board, reason ASC"); addPrepStmt("filterTime" , "UPDATE filter SET timestamp = ? WHERE id = ?"); addPrepStmt("oldestFilter" , "SELECT id FROM filter ORDER BY timestamp ASC LIMIT 1"); addPrepStmt("compareBlacklisted", "SELECT a.id, CONCAT(dirlist.dirpath,filelist.filename) FROM (select index.id,dir, filename FROM block join index on block.id = index.id) AS a JOIN filelist ON a.filename=filelist.id Join dirlist ON a.dir=dirlist.id"); addPrepStmt("isValidTag" , "SELECT tag_id FROM location_tags WHERE location = ?"); } private static void generateStatements(){ for(AidTables table : AidTables.values()){ addPrepStmt("size"+table.toString(), "SELECT count(*) FROM "+table.toString()); } } protected Connection getConnection(){ try { return connPool.getConnection(); } catch (SQLException e) { logger.warning("Failed to get database connection"); } return null; } protected static void addPrepStmt(String id, String stmt){ try { if(prepStmts.containsKey(id)) throw new IllegalArgumentException("Key is already present"); prepStmts.put(id, stmt); } catch (NullPointerException npe){ logger.severe("Prepared Statement could not be created, invalid connection"); } catch (IllegalArgumentException iae){ logger.severe("Prepared Statement could not be created, "+iae.getMessage()); } } public boolean batchExecute(String[] statements){ Connection cn = getConnection(); Statement req = null; try { for(String sql : statements){ req = cn.createStatement(); req.execute(sql); req.close(); } } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getMessage()); return false; } finally { silentClose(cn, null, null); } return true; } public LinkedList<String> getBlacklistedFiles(){ LinkedList<String> images = new LinkedList<>(); String command = "compareBlacklisted"; ResultSet rs = null; PreparedStatement ps = getPrepStmt(command); try { rs = ps.executeQuery(); while(rs.next()){ images.add(rs.getString(1)); } return images; } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getMessage()); }finally{ closeAll(ps); silentClose(null, ps, rs); } return null; } // public void addPrepStmt(String id,String stmt,int param1, int param2){ // PreparedStatement toAdd = null; // try { // toAdd = cn.prepareStatement(stmt,param1,param2); // prepStmts.put(id, toAdd); // } catch (SQLException e) { // logger.severe("Prepared Statement could not be created,\n"+e.getMessage()+ // "\n"+id // +"\n"+stmt); // } // } // // public void addPrepStmt(String id,String stmt,int param1){ // PreparedStatement toAdd = null; // try { // toAdd = cn.prepareStatement(stmt,param1); // prepStmts.put(id, toAdd); // } catch (SQLException e) { // logger.severe("Prepared Statement could not be created,\n"+e.getMessage()+ // "\n"+id // +"\n"+stmt); // } catch (NullPointerException npe) { // logger.severe("Could not add Prepared Statment, invalid connection"); // } // } protected PreparedStatement getPrepStmt(String command){ if(prepStmts.containsKey(command)){ Connection cn = getConnection(); PreparedStatement prepStmt = null; try { prepStmt = cn.prepareStatement(prepStmts.get(command)); } catch (SQLException e) { logger.warning("Failed to create prepared statement for command \""+command+"\""); } return prepStmt; }else{ logger.warning("Prepared statment command \""+command+"\" not found.\nHas this object been initialized?"); return null; } } protected void silentClose(Connection cn, PreparedStatement ps, ResultSet rs){ if(rs != null) try{rs.close();}catch(SQLException e){} if(ps != null) try{ps.close();}catch(SQLException e){} if(cn != null) try{cn.close();}catch(SQLException e){} } protected void closeAll(PreparedStatement ps){ Connection cn = null; ResultSet rs = null; if(ps == null) return; try{cn = ps.getConnection();}catch(SQLException e){} try{rs = ps.getResultSet();}catch(SQLException e){} if(rs != null) try{rs.close();}catch(SQLException e){} if(ps != null) try{ps.close();}catch(SQLException e){} if(cn != null) try{cn.close();}catch(SQLException e){} } /** * Add the current URL to the cache, or update it's Timestamp if it * already exists. Method will return true if the URL is already present, * otherwise false. * @param url URL to be added * @return true if URL is already present else false. * Retruns true on error. */ public boolean addCache(URL url){ String id = url.toString(); PreparedStatement ps = getPrepStmt("addCache"); try { ps.setString(1, id); int res = ps.executeUpdate(); if(res > 1) return true; // entry was present else return false; // entry is new } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getMessage()); } finally { closeAll(ps); } return true; } public void addThumb(String url,String filename, byte[] data){ Connection cn = getConnection(); Blob blob = null; PreparedStatement ps = getPrepStmt("addThumb"); try { blob = cn.createBlob(); blob.setBytes(1, data); ps.setString(1, url); ps.setString(2, filename); ps.setBlob(3, blob); ps.executeUpdate(); } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getMessage()); }finally{ try { if(blob != null) blob.free(); } catch (SQLException e) { logger.severe(e.getMessage()); } closeAll(ps); silentClose(cn, ps, null); } } public boolean addIndex(String hash, String path, long size, String location){ return fileDataInsert("addIndex", hash, path, size, location); } private boolean fileDataInsert(String command, String hash, String path, long size, String location){ PreparedStatement ps = getPrepStmt(command); try{ int[] pathId = addPath(path); if (pathId == null){ logger.warning("Invalid path data"); return false; } ps.setString(1, hash); ps.setInt(2, pathId[0]); ps.setInt(3, pathId[1]); ps.setLong(4, size); ps.setString(5, location); ps.execute(); return true; } catch(SQLException e){ logger.warning(SQL_OP_ERR+e.getMessage()); } finally { closeAll(ps); } return false; } /** * Get the number of pending filter items. * @return Number of pending items. */ public int getPending(){ return simpleIntQuery("pending"); } public ArrayList<Image> getThumb(String url){ Blob blob = null; ArrayList<Image> images = new ArrayList<Image>(); InputStream is; String command = "getThumb"; ResultSet rs = null; PreparedStatement ps = getPrepStmt(command); try { ps.setString(1, url); rs = ps.executeQuery(); while(rs.next()){ blob = rs.getBlob(1); is = new BufferedInputStream(blob.getBinaryStream()); images.add(ImageIO.read(is)); is.close(); blob.free(); } return images; } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getMessage()); } catch (IOException e) { logger.severe(e.getMessage()); }finally{ closeAll(ps); silentClose(null, ps, rs); } return null; } public int size(AidTables table){ return simpleIntQuery("size"+table.toString()); } /** * Check the ID against the cache. * @param uniqueID ID to check * @return true if the ID is present otherwise false. * Returns true on errors. */ public boolean isCached(URL url){ return isCached(url.toString()); } /** * Check the ID against the cache. * @param uniqueID ID to check * @return true if the ID is present otherwise false. * Returns true on errors. */ public boolean isCached(String uniqueID){ return simpleBooleanQuery("isCached", uniqueID, true); } public boolean isArchived(String hash){ return simpleBooleanQuery("isArchive", hash, true); } public boolean isDnw(String hash){ return simpleBooleanQuery("isDnw", hash, true); } public boolean isHashed(String hash){ return simpleBooleanQuery("isHashed", hash, true); } public boolean isBlacklisted(String hash){ return simpleBooleanQuery("isBlacklisted", hash, false); } public boolean isValidTag(String tag){ return simpleBooleanQuery("isValidTag", tag, false); } public int getTagId(String tag){ return simpleIntQuery("aadfa"); } public void update(String id, AidTables table){ PreparedStatement update = null; String command = null; if(table.equals(AidTables.Block)){ command = "hlUpdateBlock"; }else if (table.equals(AidTables.Dnw)){ command = "hlUpdateDnw"; }else{ logger.severe("Unhandled enum Table: "+table.toString()); return; } try{ update = getPrepStmt(command); update.setString(1, id); update.executeUpdate(); }catch (SQLException e){ logger.warning(SQL_OP_ERR+command+": "+e.getMessage()); }finally{ closeAll(update); } } private boolean simpleBooleanQuery(String command, String key, Boolean defaultReturn){ ResultSet rs = null; PreparedStatement ps = getPrepStmt(command); try { ps.setString(1, key); rs = ps.executeQuery(); boolean b = rs.next(); return b; } catch (SQLException e) { logger.warning(SQL_OP_ERR+command+": "+e.getMessage()); } finally{ closeAll(ps); } return defaultReturn; } private int simpleIntQuery(String command){ ResultSet rs = null; PreparedStatement ps = getPrepStmt(command); if(ps == null){ logger.warning("Could not carry out query for command \""+command+"\""); return -1; } try { rs = ps.executeQuery(); rs.next(); int intValue = rs.getInt(1); return intValue; } catch (SQLException e) { logger.warning(SQL_OP_ERR+command+": "+e.getMessage()); } finally{ closeAll(ps); } return -1; } private String simpleStringQuery(String command){ ResultSet rs = null; PreparedStatement ps = getPrepStmt(command); if(ps == null){ logger.warning("Could not carry out query for command \""+command+"\""); return null; } try { rs = ps.executeQuery(); rs.next(); String string = rs.getString(1); return string; } catch (SQLException e) { logger.warning(SQL_OP_ERR+command+": "+e.getMessage()); } finally{ closeAll(ps); closeResultSet(rs, command); } return null; } public void pruneCache(long maxAge){ PreparedStatement ps = getPrepStmt("prune"); try { ps.setTimestamp(1,new Timestamp(maxAge)); ps.executeUpdate(); } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getMessage()); } finally { closeAll(ps); } } public void delete(AidTables table, String id){ PreparedStatement ps = getPrepStmt("delete"+table.toString()); if(ps == null){ logger.warning("Could not delete entry "+ id +" for table "+table.toString()); return; } try { ps.setString(1, id); ps.executeUpdate(); } catch (Exception e) { logger.warning(SQL_OP_ERR+e.getMessage()); } finally { closeAll(ps); } } public void sendStatement(String sqlStatment){ Connection cn = getConnection(); Statement req = null; try { req = cn.createStatement(); req.execute(sqlStatment); req.close(); } catch (SQLException e) { logger.warning("Failed to execute statement id: "+sqlStatment+"\n"+e.getMessage()); } finally { if(req != null) try{req.close();} catch (SQLException e){} silentClose(cn, null, null); } } public String getSetting(DBsettings settingName){ String command = "getSetting"; ResultSet rs = null; PreparedStatement ps = getPrepStmt(command); try { ps.setString(1, settingName.toString()); rs = ps.executeQuery(); rs.next(); String string = rs.getString(1); return string; } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getMessage()); } finally{ closeAll(ps); silentClose(null, ps, rs); } return null; } /** * Get path associated with the given hash value. * * @param hash hash value to lookup * @return path as a String or null if not found */ public String getPath(String hash){ PreparedStatement ps = null; ResultSet rs = null; try{ ps = getPrepStmt("getPath"); rs = ps.executeQuery(); if(rs.next()){ return rs.getString(1); } } catch(SQLException e){ logger.warning(SQL_OP_ERR+e.getMessage()); } finally { closeAll(ps); } return null; } private int[] addPath(String fullPath){ int pathValue; Connection cn = null; PreparedStatement addDir = null; PreparedStatement addFile = null; try{ cn = getConnection(); addDir = cn.prepareStatement("INSERT INTO dirlist (dirpath) VALUES (?)",PreparedStatement.RETURN_GENERATED_KEYS); addFile = cn.prepareStatement("INSERT INTO filelist (filename) VALUES (?)",PreparedStatement.RETURN_GENERATED_KEYS); int split = fullPath.lastIndexOf("\\")+1; String filename = fullPath.substring(split).toLowerCase(); // bar.txt String path = fullPath.substring(0,split).toLowerCase(); // D:\foo\ int[] pathId = new int[2]; pathValue = pathLookupQuery("getDirectory", path); pathId[0] = pathAddQuery(addDir, pathValue, path); pathValue = pathLookupQuery("getFilename", filename); pathId[1] = pathAddQuery(addFile, pathValue, filename); return pathId; } catch (SQLException e) { logger.severe(e.getMessage()); } finally { silentClose(null, addDir, null); silentClose(cn, addFile, null); } return null; } private int pathLookupQuery(String command, String path) throws SQLException{ PreparedStatement ps = getPrepStmt(command); ps.setString(1, path); ResultSet rs = ps.executeQuery(); int pathValue = -1; try{ if(rs.next()){ pathValue = rs.getInt(1); } }catch (SQLException e){ throw e; }finally{ closeAll(ps); } return pathValue; } private int pathAddQuery(PreparedStatement ps, int pathLookUp, String path) throws SQLException{ int pathValue = -1; ResultSet rs = null; try{ if(pathLookUp == -1){ ps.setString(1, path); ps.execute(); rs = ps.getGeneratedKeys(); rs.next(); pathValue = rs.getInt(1); } else { pathValue = pathLookUp; } }catch (SQLException e){ throw e; } return pathValue; } private void closeResultSet(ResultSet rs, String command){ if(rs != null){ try{ rs.close(); }catch (SQLException e){ logger.warning(RS_CLOSE_ERR+e.getMessage()+" for command \""+command+"\""); } } } public boolean addFilter(FilterItem fi) { return addFilter(fi.getUrl().toString(), fi.getBoard(), fi.getReason(), fi.getState()); } /** * Adds a filter item to the database. * @param id id of the item * @param board board alias * @param reason reason for adding the filter * @param state initial state of the filter * @return true if the filter was added, else false */ public boolean addFilter(String id, String board, String reason, FilterState state) { PreparedStatement addFilter =getPrepStmt("addFilter"); try { addFilter.setString(1, id); addFilter.setString(2, board); addFilter.setString(3, reason); addFilter.setShort(4, (short) state.ordinal()); int res = addFilter.executeUpdate(); if(res == 0){ logger.warning("filter already exists!"); return false; }else{ return true; } } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getMessage()); } finally { closeAll(addFilter); } return false; } public void updateState(String id, FilterState state) { PreparedStatement updateFilter = getPrepStmt("updateFilter"); try { updateFilter.setShort(1, (short)state.ordinal()); updateFilter.setString(2, id); updateFilter.executeUpdate(); } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getMessage()); } finally { closeAll(updateFilter); } } public FilterState getFilterState(String id) { ResultSet rs = null; PreparedStatement ps = null; try { ps = getPrepStmt("filterState"); ps.setString(1, id); rs = ps.executeQuery(); if(rs.next()){ FilterState fs = FilterState.values()[(int)rs.getShort(1)]; return fs; } } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getMessage()); }finally{ closeAll(ps); } return FilterState.UNKNOWN; } /** * Returns all items in the filter with state set to pending (1). * @return a list of all pending filter items */ public LinkedList<FilterItem> getPendingFilters() { PreparedStatement pendingFilter = getPrepStmt("pendingFilter"); ResultSet rs = null; try { rs = pendingFilter.executeQuery(); LinkedList<FilterItem> result = new LinkedList<FilterItem>(); while(rs.next()){ URL url; url = new URL(rs.getString("id")); result.add(new FilterItem(url, rs.getString("board"), rs.getString("reason"), FilterState.PENDING)); } return result; } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getMessage()); } catch (MalformedURLException e) { logger.warning("Unable to create URL "+e.getMessage()); }finally{ closeAll(pendingFilter); } return new LinkedList<FilterItem>(); } public void updateFilterTimestamp(String id) { PreparedStatement updateTimestamp = getPrepStmt("filterTime"); try { updateTimestamp.setTimestamp(1, new Timestamp(Calendar.getInstance().getTimeInMillis())); updateTimestamp.setString(2, id); updateTimestamp.executeUpdate(); } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getMessage()); } finally { closeAll(updateTimestamp); } } public String getOldestFilter() { ResultSet rs = null; PreparedStatement getOldest = getPrepStmt("oldestFilter"); try { rs = getOldest.executeQuery(); if(rs.next()){ String s = rs.getString(1); return s; }else { return null; } } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getLocalizedMessage()); }finally{ closeAll(getOldest); } return null; } }
true
true
private static void init(){ generateStatements(); addPrepStmt("addCache" , "INSERT INTO cache (id) VALUES (?) ON DUPLICATE KEY UPDATE timestamp = NOW()"); addPrepStmt("addThumb" , "INSERT INTO thumbs (url, filename, thumb) VALUES(?,?,?)"); addPrepStmt("getThumb" , "SELECT thumb FROM thumbs WHERE url = ? ORDER BY filename ASC"); addPrepStmt("pending" , "SELECT count(*) FROM filter WHERE status = 1"); addPrepStmt("isCached" , "SELECT timestamp FROM `cache` WHERE `id` = ?"); addPrepStmt("isArchive" , "SELECT * FROM `archive` WHERE `id` = ?"); addPrepStmt("isDnw" , "SELECT * FROM `dnw` WHERE `id` = ?"); addPrepStmt("prune" , "DELETE FROM `cache` WHERE `timestamp` < ?"); addPrepStmt("isHashed" , "SELECT id FROM `index` WHERE `id` = ?"); addPrepStmt("addIndex" , "INSERT INTO index (id, dir, filename, size, location) VALUES (?,?,?,?,(SELECT tag_id FROM location_tags WHERE location = ?)) "); addPrepStmt("deleteIndex" , "DELETE FROM index WHERE id = ?"); addPrepStmt("deleteFilter" , "DELETE FROM filter WHERE id = ?"); addPrepStmt("deleteDnw" , "DELETE FROM dnw WHERE id = ?"); addPrepStmt("deleteBlock" , "DELETE FROM block WHERE id = ?"); addPrepStmt("deleteArchive" , "DELETE FROM archive WHERE id = ?"); addPrepStmt("isBlacklisted" , "SELECT * FROM `block` WHERE `id` = ?"); addPrepStmt("getDirectory" , "SELECT id FROM dirlist WHERE dirpath = ?"); addPrepStmt("getFilename" , "SELECT id FROM filelist WHERE filename = ?"); addPrepStmt("getSetting" , "SELECT param FROM settings WHERE name = ?"); addPrepStmt("getPath" , "SELECT CONCAT(dirlist.dirpath,filelist.filename) FROM (select dir, filename FROM index WHERE id =?) AS a JOIN filelist ON a.filename=filelist.id Join dirlist on a.dir=dirlist.id"); addPrepStmt("hlUpdateBlock" , "INSERT IGNORE INTO block (id) VALUES (?)"); addPrepStmt("hlUpdateDnw" , "INSERT IGNORE INTO dnw (id) VALUES (?)"); addPrepStmt("addFilter" , "INSERT IGNORE INTO filter (id, board, reason, status) VALUES (?,?,?,?)"); addPrepStmt("updateFilter" , "UPDATE filter SET status = ? WHERE id = ?"); addPrepStmt("filterState" , "SELECT status FROM filter WHERE id = ?"); addPrepStmt("pendingFilter" , "SELECT board, reason, id FROM filter WHERE status = 1 ORDER BY board, reason ASC"); addPrepStmt("filterTime" , "UPDATE filter SET timestamp = ? WHERE id = ?"); addPrepStmt("oldestFilter" , "SELECT id FROM filter ORDER BY timestamp ASC LIMIT 1"); addPrepStmt("compareBlacklisted", "SELECT a.id, CONCAT(dirlist.dirpath,filelist.filename) FROM (select index.id,dir, filename FROM block join index on block.id = index.id) AS a JOIN filelist ON a.filename=filelist.id Join dirlist ON a.dir=dirlist.id"); addPrepStmt("isValidTag" , "SELECT tag_id FROM location_tags WHERE location = ?"); }
private static void init(){ generateStatements(); addPrepStmt("addCache" , "INSERT INTO cache (id) VALUES (?) ON DUPLICATE KEY UPDATE timestamp = NOW()"); addPrepStmt("addThumb" , "INSERT INTO thumbs (url, filename, thumb) VALUES(?,?,?)"); addPrepStmt("getThumb" , "SELECT thumb FROM thumbs WHERE url = ? ORDER BY filename ASC"); addPrepStmt("pending" , "SELECT count(*) FROM filter WHERE status = 1"); addPrepStmt("isCached" , "SELECT timestamp FROM `cache` WHERE `id` = ?"); addPrepStmt("isArchive" , "SELECT * FROM `archive` WHERE `id` = ?"); addPrepStmt("isDnw" , "SELECT * FROM `dnw` WHERE `id` = ?"); addPrepStmt("prune" , "DELETE FROM `cache` WHERE `timestamp` < ?"); addPrepStmt("isHashed" , "SELECT id FROM `index` WHERE `id` = ?"); addPrepStmt("addIndex" , "INSERT INTO `index` (id, dir, filename, size, location) VALUES (?,?,?,?,(SELECT tag_id FROM location_tags WHERE location = ?)) "); addPrepStmt("deleteIndex" , "DELETE FROM index WHERE id = ?"); addPrepStmt("deleteFilter" , "DELETE FROM filter WHERE id = ?"); addPrepStmt("deleteDnw" , "DELETE FROM dnw WHERE id = ?"); addPrepStmt("deleteBlock" , "DELETE FROM block WHERE id = ?"); addPrepStmt("deleteArchive" , "DELETE FROM archive WHERE id = ?"); addPrepStmt("isBlacklisted" , "SELECT * FROM `block` WHERE `id` = ?"); addPrepStmt("getDirectory" , "SELECT id FROM dirlist WHERE dirpath = ?"); addPrepStmt("getFilename" , "SELECT id FROM filelist WHERE filename = ?"); addPrepStmt("getSetting" , "SELECT param FROM settings WHERE name = ?"); addPrepStmt("getPath" , "SELECT CONCAT(dirlist.dirpath,filelist.filename) FROM (select dir, filename FROM index WHERE id =?) AS a JOIN filelist ON a.filename=filelist.id Join dirlist on a.dir=dirlist.id"); addPrepStmt("hlUpdateBlock" , "INSERT IGNORE INTO block (id) VALUES (?)"); addPrepStmt("hlUpdateDnw" , "INSERT IGNORE INTO dnw (id) VALUES (?)"); addPrepStmt("addFilter" , "INSERT IGNORE INTO filter (id, board, reason, status) VALUES (?,?,?,?)"); addPrepStmt("updateFilter" , "UPDATE filter SET status = ? WHERE id = ?"); addPrepStmt("filterState" , "SELECT status FROM filter WHERE id = ?"); addPrepStmt("pendingFilter" , "SELECT board, reason, id FROM filter WHERE status = 1 ORDER BY board, reason ASC"); addPrepStmt("filterTime" , "UPDATE filter SET timestamp = ? WHERE id = ?"); addPrepStmt("oldestFilter" , "SELECT id FROM filter ORDER BY timestamp ASC LIMIT 1"); addPrepStmt("compareBlacklisted", "SELECT a.id, CONCAT(dirlist.dirpath,filelist.filename) FROM (select index.id,dir, filename FROM block join index on block.id = index.id) AS a JOIN filelist ON a.filename=filelist.id Join dirlist ON a.dir=dirlist.id"); addPrepStmt("isValidTag" , "SELECT tag_id FROM location_tags WHERE location = ?"); }
diff --git a/src/main/java/me/cmastudios/plugins/WarhubModChat/WarhubModChat.java b/src/main/java/me/cmastudios/plugins/WarhubModChat/WarhubModChat.java index 8f4d68e..1f9bbd4 100644 --- a/src/main/java/me/cmastudios/plugins/WarhubModChat/WarhubModChat.java +++ b/src/main/java/me/cmastudios/plugins/WarhubModChat/WarhubModChat.java @@ -1,224 +1,226 @@ package me.cmastudios.plugins.WarhubModChat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import me.cmastudios.plugins.WarhubModChat.util.*; public class WarhubModChat extends JavaPlugin { Permission permissions = new Permission(); Message messageUtil = new Message(); String version; Logger log = Logger.getLogger("Minecraft"); private final plrLstnr playerListener = new plrLstnr(this); public HashMap<Player, String> channels = new HashMap<Player, String>(); public HashMap<Player, String> ignores = new HashMap<Player, String>(); @Override public void onDisable() { channels.clear(); log.info("[WarhubModChat] Disabled!"); } @Override public void onEnable() { permissions.setupPermissions(); Config.setup(); PluginManager pm = this.getServer().getPluginManager(); pm.registerEvent(Event.Type.PLAYER_CHAT, this.playerListener, Event.Priority.Highest, this); pm.registerEvent(Event.Type.PLAYER_JOIN, this.playerListener, Event.Priority.Low, this); PluginDescriptionFile pdffile = this.getDescription(); version = pdffile.getVersion(); log.info("[WarhubModChat] Version " + version + " by cmastudios enabled!"); } @SuppressWarnings("static-access") public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (cmd.getName().equalsIgnoreCase("modchat")) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } if (args.length < 1) { if (player == null) {log.info("You can't use channels from the console, use '/modchat <message>' to chat.");return true;} channels.put(player, "mod"); player.sendMessage(ChatColor.YELLOW + "Chat switched to mod."); } else { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; if (player==null) { List<Player> sendto = new ArrayList<Player>(); for (Player p : Bukkit.getServer().getOnlinePlayers()) { if (permissions.has(p, "warhub.moderator")) { sendto.add(p); } } for (Player p : sendto) { p.sendMessage(messageUtil.colorizeText(Config.read("modchat-format").replace("%player", "tommytony").replace("%message", message))); } log.info("[MODCHAT] tommytony: "+message); sendto.clear(); return true; } if (channels.containsKey(player)) { String channel = channels.remove(player); player.chat(message); channels.put(player, channel); channel = null; } else { channels.put(player, "mod"); player.chat(message); channels.remove(player); } } return true; } if (cmd.getName().equalsIgnoreCase("alert")) { if (player == null) {log.info("You can't use alert from the console, use '/say <message>' to chat.");return true;} if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } if (args.length < 1) { channels.put(player, "alert"); player.sendMessage(ChatColor.YELLOW + "Chat switched to alert."); } else { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; if (channels.containsKey(player)) { String channel = channels.remove(player); player.chat(message); channels.put(player, channel); channel = null; } else { channels.put(player, "alert"); player.chat(message); channels.remove(player); } } return true; } if (cmd.getName().equalsIgnoreCase("global")) { if (player == null) {log.info("You can't use global from the console, use '/say <message>' to chat.");return true;} if (args.length < 1) { channels.remove(player); player.sendMessage(ChatColor.YELLOW + "Chat switched to global."); } else { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; if (channels.containsKey(player)) { String channel = channels.remove(player); player.chat(message); channels.put(player, channel); channel = null; } else { player.chat(message); } } return true; } if (cmd.getName().equalsIgnoreCase("channel")) { if (player == null) {log.info("You can't use channels from the console, use '/<say/modchat> <message>' to chat.");return true;} if (args.length < 1) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You're not a mod, and cannot change channels."); return true; } else { player.sendMessage(ChatColor.RED + "Use '/ch <mod/alert/global>' to change your channel."); } return true; } if (args[0].equalsIgnoreCase("mod") || args[0].equalsIgnoreCase("modchat") || args[0].equalsIgnoreCase("m")) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } channels.put(player, "mod"); player.sendMessage(ChatColor.YELLOW + "Chat switched to mod."); return true; } if (args[0].equalsIgnoreCase("a") || args[0].equalsIgnoreCase("alert")) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } channels.put(player, "alert"); player.sendMessage(ChatColor.YELLOW + "Chat switched to alert."); return true; } if (args[0].equalsIgnoreCase("g") || args[0].equalsIgnoreCase("global")) { channels.remove(player); player.sendMessage(ChatColor.YELLOW + "Chat switched to global."); return true; } if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You're not a mod, and cannot change channels."); return true; } else { player.sendMessage(ChatColor.RED + "Use '/ch <mod/alert/global>' to change your channel."); } return true; } if (cmd.getName().equalsIgnoreCase("say")) { if (player != null) if (!player.isOp()) {player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true;} if (args.length == 0) return false; String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; this.getServer().broadcastMessage(messageUtil.colorizeText(Config.read("say-format")).replace("%message", message)); return true; } if (cmd.getName().equalsIgnoreCase("deaf")) { if (ignores.containsKey(player)) { ignores.remove(player); player.sendMessage(ChatColor.YELLOW + "Un-deafened."); } else { ignores.put(player, ""); player.sendMessage(ChatColor.YELLOW + "Deafened."); } + return true; } if (cmd.getName().equalsIgnoreCase("me")) { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message == "") return false; if (message == " ") return false; for (Player p : Bukkit.getServer().getOnlinePlayers()) { if (!ignores.containsKey(p)) p.sendMessage( "* " + player.getDisplayName() + " " + message); } + return true; } return false; } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (cmd.getName().equalsIgnoreCase("modchat")) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } if (args.length < 1) { if (player == null) {log.info("You can't use channels from the console, use '/modchat <message>' to chat.");return true;} channels.put(player, "mod"); player.sendMessage(ChatColor.YELLOW + "Chat switched to mod."); } else { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; if (player==null) { List<Player> sendto = new ArrayList<Player>(); for (Player p : Bukkit.getServer().getOnlinePlayers()) { if (permissions.has(p, "warhub.moderator")) { sendto.add(p); } } for (Player p : sendto) { p.sendMessage(messageUtil.colorizeText(Config.read("modchat-format").replace("%player", "tommytony").replace("%message", message))); } log.info("[MODCHAT] tommytony: "+message); sendto.clear(); return true; } if (channels.containsKey(player)) { String channel = channels.remove(player); player.chat(message); channels.put(player, channel); channel = null; } else { channels.put(player, "mod"); player.chat(message); channels.remove(player); } } return true; } if (cmd.getName().equalsIgnoreCase("alert")) { if (player == null) {log.info("You can't use alert from the console, use '/say <message>' to chat.");return true;} if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } if (args.length < 1) { channels.put(player, "alert"); player.sendMessage(ChatColor.YELLOW + "Chat switched to alert."); } else { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; if (channels.containsKey(player)) { String channel = channels.remove(player); player.chat(message); channels.put(player, channel); channel = null; } else { channels.put(player, "alert"); player.chat(message); channels.remove(player); } } return true; } if (cmd.getName().equalsIgnoreCase("global")) { if (player == null) {log.info("You can't use global from the console, use '/say <message>' to chat.");return true;} if (args.length < 1) { channels.remove(player); player.sendMessage(ChatColor.YELLOW + "Chat switched to global."); } else { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; if (channels.containsKey(player)) { String channel = channels.remove(player); player.chat(message); channels.put(player, channel); channel = null; } else { player.chat(message); } } return true; } if (cmd.getName().equalsIgnoreCase("channel")) { if (player == null) {log.info("You can't use channels from the console, use '/<say/modchat> <message>' to chat.");return true;} if (args.length < 1) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You're not a mod, and cannot change channels."); return true; } else { player.sendMessage(ChatColor.RED + "Use '/ch <mod/alert/global>' to change your channel."); } return true; } if (args[0].equalsIgnoreCase("mod") || args[0].equalsIgnoreCase("modchat") || args[0].equalsIgnoreCase("m")) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } channels.put(player, "mod"); player.sendMessage(ChatColor.YELLOW + "Chat switched to mod."); return true; } if (args[0].equalsIgnoreCase("a") || args[0].equalsIgnoreCase("alert")) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } channels.put(player, "alert"); player.sendMessage(ChatColor.YELLOW + "Chat switched to alert."); return true; } if (args[0].equalsIgnoreCase("g") || args[0].equalsIgnoreCase("global")) { channels.remove(player); player.sendMessage(ChatColor.YELLOW + "Chat switched to global."); return true; } if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You're not a mod, and cannot change channels."); return true; } else { player.sendMessage(ChatColor.RED + "Use '/ch <mod/alert/global>' to change your channel."); } return true; } if (cmd.getName().equalsIgnoreCase("say")) { if (player != null) if (!player.isOp()) {player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true;} if (args.length == 0) return false; String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; this.getServer().broadcastMessage(messageUtil.colorizeText(Config.read("say-format")).replace("%message", message)); return true; } if (cmd.getName().equalsIgnoreCase("deaf")) { if (ignores.containsKey(player)) { ignores.remove(player); player.sendMessage(ChatColor.YELLOW + "Un-deafened."); } else { ignores.put(player, ""); player.sendMessage(ChatColor.YELLOW + "Deafened."); } } if (cmd.getName().equalsIgnoreCase("me")) { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message == "") return false; if (message == " ") return false; for (Player p : Bukkit.getServer().getOnlinePlayers()) { if (!ignores.containsKey(p)) p.sendMessage( "* " + player.getDisplayName() + " " + message); } } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (cmd.getName().equalsIgnoreCase("modchat")) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } if (args.length < 1) { if (player == null) {log.info("You can't use channels from the console, use '/modchat <message>' to chat.");return true;} channels.put(player, "mod"); player.sendMessage(ChatColor.YELLOW + "Chat switched to mod."); } else { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; if (player==null) { List<Player> sendto = new ArrayList<Player>(); for (Player p : Bukkit.getServer().getOnlinePlayers()) { if (permissions.has(p, "warhub.moderator")) { sendto.add(p); } } for (Player p : sendto) { p.sendMessage(messageUtil.colorizeText(Config.read("modchat-format").replace("%player", "tommytony").replace("%message", message))); } log.info("[MODCHAT] tommytony: "+message); sendto.clear(); return true; } if (channels.containsKey(player)) { String channel = channels.remove(player); player.chat(message); channels.put(player, channel); channel = null; } else { channels.put(player, "mod"); player.chat(message); channels.remove(player); } } return true; } if (cmd.getName().equalsIgnoreCase("alert")) { if (player == null) {log.info("You can't use alert from the console, use '/say <message>' to chat.");return true;} if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } if (args.length < 1) { channels.put(player, "alert"); player.sendMessage(ChatColor.YELLOW + "Chat switched to alert."); } else { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; if (channels.containsKey(player)) { String channel = channels.remove(player); player.chat(message); channels.put(player, channel); channel = null; } else { channels.put(player, "alert"); player.chat(message); channels.remove(player); } } return true; } if (cmd.getName().equalsIgnoreCase("global")) { if (player == null) {log.info("You can't use global from the console, use '/say <message>' to chat.");return true;} if (args.length < 1) { channels.remove(player); player.sendMessage(ChatColor.YELLOW + "Chat switched to global."); } else { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; if (channels.containsKey(player)) { String channel = channels.remove(player); player.chat(message); channels.put(player, channel); channel = null; } else { player.chat(message); } } return true; } if (cmd.getName().equalsIgnoreCase("channel")) { if (player == null) {log.info("You can't use channels from the console, use '/<say/modchat> <message>' to chat.");return true;} if (args.length < 1) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You're not a mod, and cannot change channels."); return true; } else { player.sendMessage(ChatColor.RED + "Use '/ch <mod/alert/global>' to change your channel."); } return true; } if (args[0].equalsIgnoreCase("mod") || args[0].equalsIgnoreCase("modchat") || args[0].equalsIgnoreCase("m")) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } channels.put(player, "mod"); player.sendMessage(ChatColor.YELLOW + "Chat switched to mod."); return true; } if (args[0].equalsIgnoreCase("a") || args[0].equalsIgnoreCase("alert")) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } channels.put(player, "alert"); player.sendMessage(ChatColor.YELLOW + "Chat switched to alert."); return true; } if (args[0].equalsIgnoreCase("g") || args[0].equalsIgnoreCase("global")) { channels.remove(player); player.sendMessage(ChatColor.YELLOW + "Chat switched to global."); return true; } if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You're not a mod, and cannot change channels."); return true; } else { player.sendMessage(ChatColor.RED + "Use '/ch <mod/alert/global>' to change your channel."); } return true; } if (cmd.getName().equalsIgnoreCase("say")) { if (player != null) if (!player.isOp()) {player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true;} if (args.length == 0) return false; String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; this.getServer().broadcastMessage(messageUtil.colorizeText(Config.read("say-format")).replace("%message", message)); return true; } if (cmd.getName().equalsIgnoreCase("deaf")) { if (ignores.containsKey(player)) { ignores.remove(player); player.sendMessage(ChatColor.YELLOW + "Un-deafened."); } else { ignores.put(player, ""); player.sendMessage(ChatColor.YELLOW + "Deafened."); } return true; } if (cmd.getName().equalsIgnoreCase("me")) { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message == "") return false; if (message == " ") return false; for (Player p : Bukkit.getServer().getOnlinePlayers()) { if (!ignores.containsKey(p)) p.sendMessage( "* " + player.getDisplayName() + " " + message); } return true; } return false; }
diff --git a/maven-scm-providers/maven-scm-provider-hg/src/main/java/org/apache/maven/scm/provider/hg/command/tag/HgTagCommand.java b/maven-scm-providers/maven-scm-provider-hg/src/main/java/org/apache/maven/scm/provider/hg/command/tag/HgTagCommand.java index 79c7de96..6bd1b0b7 100644 --- a/maven-scm-providers/maven-scm-provider-hg/src/main/java/org/apache/maven/scm/provider/hg/command/tag/HgTagCommand.java +++ b/maven-scm-providers/maven-scm-provider-hg/src/main/java/org/apache/maven/scm/provider/hg/command/tag/HgTagCommand.java @@ -1,157 +1,157 @@ package org.apache.maven.scm.provider.hg.command.tag; /* * 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. */ import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.maven.scm.ScmException; import org.apache.maven.scm.ScmFile; import org.apache.maven.scm.ScmFileSet; import org.apache.maven.scm.ScmFileStatus; import org.apache.maven.scm.ScmResult; import org.apache.maven.scm.ScmTagParameters; import org.apache.maven.scm.command.Command; import org.apache.maven.scm.command.tag.AbstractTagCommand; import org.apache.maven.scm.command.tag.TagScmResult; import org.apache.maven.scm.provider.ScmProviderRepository; import org.apache.maven.scm.provider.hg.HgUtils; import org.apache.maven.scm.provider.hg.command.HgCommandConstants; import org.apache.maven.scm.provider.hg.command.HgConsumer; import org.apache.maven.scm.provider.hg.command.inventory.HgListConsumer; import org.apache.maven.scm.provider.hg.repository.HgScmProviderRepository; import org.codehaus.plexus.util.StringUtils; /** * Tag * * @author <a href="mailto:[email protected]">ryan daum</a> * @author Olivier Lamy * @version $Id$ */ public class HgTagCommand extends AbstractTagCommand implements Command { protected ScmResult executeTagCommand( ScmProviderRepository scmProviderRepository, ScmFileSet fileSet, String tag, String message ) throws ScmException { return executeTagCommand( scmProviderRepository, fileSet, tag, new ScmTagParameters( message ) ); } /** * {@inheritDoc} */ protected ScmResult executeTagCommand( ScmProviderRepository scmProviderRepository, ScmFileSet fileSet, String tag, ScmTagParameters scmTagParameters ) throws ScmException { if ( tag == null || StringUtils.isEmpty( tag.trim() ) ) { throw new ScmException( "tag must be specified" ); } - if ( fileSet.getFileList().isEmpty() ) + if ( !fileSet.getFileList().isEmpty() ) { throw new ScmException( "This provider doesn't support tagging subsets of a directory : " + fileSet.getFileList() ); } File workingDir = fileSet.getBasedir(); // build the command String[] tagCmd = new String[]{ HgCommandConstants.TAG_CMD, HgCommandConstants.MESSAGE_OPTION, scmTagParameters.getMessage(), tag }; // keep the command about in string form for reporting StringBuffer cmd = joinCmd( tagCmd ); HgTagConsumer consumer = new HgTagConsumer( getLogger() ); ScmResult result = HgUtils.execute( consumer, getLogger(), workingDir, tagCmd ); HgScmProviderRepository repository = (HgScmProviderRepository) scmProviderRepository; if ( result.isSuccess() ) { // now push // Push to parent branch if any if ( repository.isPushChanges() ) { if ( !repository.getURI().equals( fileSet.getBasedir().getAbsolutePath() ) ) { String branchName = HgUtils.getCurrentBranchName( getLogger(), workingDir ); boolean differentOutgoingBranch = HgUtils.differentOutgoingBranchFound( getLogger(), workingDir, branchName ); String[] pushCmd = new String[]{ HgCommandConstants.PUSH_CMD, differentOutgoingBranch ? HgCommandConstants.REVISION_OPTION + branchName : null, repository.getURI() }; result = HgUtils.execute( new HgConsumer( getLogger() ), getLogger(), fileSet.getBasedir(), pushCmd ); } } } else { throw new ScmException( "Error while executing command " + cmd.toString() ); } // do an inventory to return the files tagged (all of them) String[] listCmd = new String[]{ HgCommandConstants.INVENTORY_CMD }; HgListConsumer listconsumer = new HgListConsumer( getLogger() ); result = HgUtils.execute( listconsumer, getLogger(), fileSet.getBasedir(), listCmd ); if ( result.isSuccess() ) { List<ScmFile> files = listconsumer.getFiles(); List<ScmFile> fileList = new ArrayList<ScmFile>(); for ( ScmFile f : files ) { if ( !f.getPath().endsWith( ".hgtags" ) ) { fileList.add( new ScmFile( f.getPath(), ScmFileStatus.TAGGED ) ); } } return new TagScmResult( fileList, result ); } else { throw new ScmException( "Error while executing command " + cmd.toString() ); } } private StringBuffer joinCmd( String[] cmd ) { StringBuffer result = new StringBuffer(); for ( int i = 0; i < cmd.length; i++ ) { String s = cmd[i]; result.append( s ); if ( i < cmd.length - 1 ) { result.append( " " ); } } return result; } }
true
true
protected ScmResult executeTagCommand( ScmProviderRepository scmProviderRepository, ScmFileSet fileSet, String tag, ScmTagParameters scmTagParameters ) throws ScmException { if ( tag == null || StringUtils.isEmpty( tag.trim() ) ) { throw new ScmException( "tag must be specified" ); } if ( fileSet.getFileList().isEmpty() ) { throw new ScmException( "This provider doesn't support tagging subsets of a directory : " + fileSet.getFileList() ); } File workingDir = fileSet.getBasedir(); // build the command String[] tagCmd = new String[]{ HgCommandConstants.TAG_CMD, HgCommandConstants.MESSAGE_OPTION, scmTagParameters.getMessage(), tag }; // keep the command about in string form for reporting StringBuffer cmd = joinCmd( tagCmd ); HgTagConsumer consumer = new HgTagConsumer( getLogger() ); ScmResult result = HgUtils.execute( consumer, getLogger(), workingDir, tagCmd ); HgScmProviderRepository repository = (HgScmProviderRepository) scmProviderRepository; if ( result.isSuccess() ) { // now push // Push to parent branch if any if ( repository.isPushChanges() ) { if ( !repository.getURI().equals( fileSet.getBasedir().getAbsolutePath() ) ) { String branchName = HgUtils.getCurrentBranchName( getLogger(), workingDir ); boolean differentOutgoingBranch = HgUtils.differentOutgoingBranchFound( getLogger(), workingDir, branchName ); String[] pushCmd = new String[]{ HgCommandConstants.PUSH_CMD, differentOutgoingBranch ? HgCommandConstants.REVISION_OPTION + branchName : null, repository.getURI() }; result = HgUtils.execute( new HgConsumer( getLogger() ), getLogger(), fileSet.getBasedir(), pushCmd ); } } } else { throw new ScmException( "Error while executing command " + cmd.toString() ); } // do an inventory to return the files tagged (all of them) String[] listCmd = new String[]{ HgCommandConstants.INVENTORY_CMD }; HgListConsumer listconsumer = new HgListConsumer( getLogger() ); result = HgUtils.execute( listconsumer, getLogger(), fileSet.getBasedir(), listCmd ); if ( result.isSuccess() ) { List<ScmFile> files = listconsumer.getFiles(); List<ScmFile> fileList = new ArrayList<ScmFile>(); for ( ScmFile f : files ) { if ( !f.getPath().endsWith( ".hgtags" ) ) { fileList.add( new ScmFile( f.getPath(), ScmFileStatus.TAGGED ) ); } } return new TagScmResult( fileList, result ); } else { throw new ScmException( "Error while executing command " + cmd.toString() ); } }
protected ScmResult executeTagCommand( ScmProviderRepository scmProviderRepository, ScmFileSet fileSet, String tag, ScmTagParameters scmTagParameters ) throws ScmException { if ( tag == null || StringUtils.isEmpty( tag.trim() ) ) { throw new ScmException( "tag must be specified" ); } if ( !fileSet.getFileList().isEmpty() ) { throw new ScmException( "This provider doesn't support tagging subsets of a directory : " + fileSet.getFileList() ); } File workingDir = fileSet.getBasedir(); // build the command String[] tagCmd = new String[]{ HgCommandConstants.TAG_CMD, HgCommandConstants.MESSAGE_OPTION, scmTagParameters.getMessage(), tag }; // keep the command about in string form for reporting StringBuffer cmd = joinCmd( tagCmd ); HgTagConsumer consumer = new HgTagConsumer( getLogger() ); ScmResult result = HgUtils.execute( consumer, getLogger(), workingDir, tagCmd ); HgScmProviderRepository repository = (HgScmProviderRepository) scmProviderRepository; if ( result.isSuccess() ) { // now push // Push to parent branch if any if ( repository.isPushChanges() ) { if ( !repository.getURI().equals( fileSet.getBasedir().getAbsolutePath() ) ) { String branchName = HgUtils.getCurrentBranchName( getLogger(), workingDir ); boolean differentOutgoingBranch = HgUtils.differentOutgoingBranchFound( getLogger(), workingDir, branchName ); String[] pushCmd = new String[]{ HgCommandConstants.PUSH_CMD, differentOutgoingBranch ? HgCommandConstants.REVISION_OPTION + branchName : null, repository.getURI() }; result = HgUtils.execute( new HgConsumer( getLogger() ), getLogger(), fileSet.getBasedir(), pushCmd ); } } } else { throw new ScmException( "Error while executing command " + cmd.toString() ); } // do an inventory to return the files tagged (all of them) String[] listCmd = new String[]{ HgCommandConstants.INVENTORY_CMD }; HgListConsumer listconsumer = new HgListConsumer( getLogger() ); result = HgUtils.execute( listconsumer, getLogger(), fileSet.getBasedir(), listCmd ); if ( result.isSuccess() ) { List<ScmFile> files = listconsumer.getFiles(); List<ScmFile> fileList = new ArrayList<ScmFile>(); for ( ScmFile f : files ) { if ( !f.getPath().endsWith( ".hgtags" ) ) { fileList.add( new ScmFile( f.getPath(), ScmFileStatus.TAGGED ) ); } } return new TagScmResult( fileList, result ); } else { throw new ScmException( "Error while executing command " + cmd.toString() ); } }
diff --git a/src/de/blau/android/services/TrackerService.java b/src/de/blau/android/services/TrackerService.java index 96c9834..b7f9272 100644 --- a/src/de/blau/android/services/TrackerService.java +++ b/src/de/blau/android/services/TrackerService.java @@ -1,225 +1,225 @@ package de.blau.android.services; import java.io.OutputStream; import java.util.List; import android.app.PendingIntent; import android.app.Service; import android.content.ComponentName; import android.content.Intent; import android.content.res.Resources; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.widget.Toast; import de.blau.android.Application; import de.blau.android.Main; import de.blau.android.R; import de.blau.android.osm.Track; import de.blau.android.osm.Track.TrackPoint; import de.blau.android.prefs.Preferences; import de.blau.android.util.SavingHelper.Exportable; public class TrackerService extends Service implements LocationListener, Exportable { private static final float TRACK_LOCATION_MIN_ACCURACY = 200f; private static final String TAG = "TrackerService"; private final TrackerBinder mBinder = new TrackerBinder(); private LocationManager locationManager = null; private boolean tracking = false; private Track track; private TrackerLocationListener externalListener = null; private boolean listenerNeedsGPS = false; private Location lastLocation = null; private boolean gpsEnabled = false; @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate"); track = new Track(this); locationManager = (LocationManager)getSystemService(LOCATION_SERVICE); } @Override public void onDestroy() { stopTracking(false); track.close(); super.onDestroy(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { startTrackingInternal(); return START_STICKY; } /** * Starts the tracker service (which invokes {@link #onStartCommand(Intent, int, int)}, * which invokes {@link #startTrackingInternal()}, which does the actual work. * To start tracking, bind the service, then call this. */ public void startTracking() { startService(new Intent(this, TrackerService.class)); } /** * Actually starts tracking. * Gets called by {@link #onStartCommand(Intent, int, int)} when the service is started. * See {@link #startTracking()} for the public method to call when tracking should be started. */ private void startTrackingInternal() { if (tracking) return; NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this); Resources res = getResources(); Intent appStartIntent = new Intent(); appStartIntent .setAction(Intent.ACTION_MAIN) .addCategory(Intent.CATEGORY_LAUNCHER) .setComponent(new ComponentName(Main.class.getPackage().getName(), Main.class.getName())) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingAppIntent = PendingIntent.getActivity(this, 0, appStartIntent, 0); notificationBuilder .setContentTitle(res.getString(R.string.tracking_active_title)) .setContentText(res.getString(R.string.tracking_active_text)) .setSmallIcon(R.drawable.osm_logo) .setOngoing(true) - .setUsesChronometer(true) .setContentIntent(pendingAppIntent); - startForeground(R.id.notification_tracker, notificationBuilder.build()); + //notificationBuilder.setUsesChronometer(true); + startForeground(R.id.notification_tracker, notificationBuilder.getNotification()); tracking = true; track.markNewSegment(); try { Application.mainActivity.invalidateOptionsMenu(); } catch (Exception e) {} // ignore updateGPSState(); } /** * Stops tracking * @param deleteTrack true if the track should be deleted, false if it should be kept */ public void stopTracking(boolean deleteTrack) { if (!tracking) { if (deleteTrack) track.reset(); return; } if (deleteTrack) { track.reset(); } else { track.save(); } tracking = false; updateGPSState(); stopForeground(true); stopSelf(); } public boolean isTracking() { return tracking; } public List<TrackPoint> getTrackPoints() { return track.getTrackPoints(); } /** * Exports the GPX data */ public void export(OutputStream outputStream) throws Exception { track.exportToGPX(outputStream); } public String exportExtension() { return "gpx"; } @Override public IBinder onBind(Intent arg0) { return mBinder; } public class TrackerBinder extends Binder { public TrackerService getService() { return TrackerService.this; } } @Override public void onLocationChanged(Location location) { //Log.v(TAG, "Location received"); if (tracking && (!location.hasAccuracy() || location.getAccuracy() <= TRACK_LOCATION_MIN_ACCURACY)) { track.addTrackPoint(location); } if (externalListener != null) externalListener.onLocationChanged(location); lastLocation = location; } @Override public void onProviderDisabled(String provider) { Log.d(TAG, "Provider disabled: " + provider); gpsEnabled = false; locationManager.removeUpdates(this); } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) {} public interface TrackerLocationListener { public void onLocationChanged(Location location); } private void updateGPSState() { boolean needed = listenerNeedsGPS || tracking; if (needed && !gpsEnabled) { Log.d(TAG, "Enabling GPS updates"); Preferences prefs = new Preferences(this); try { Location last = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (last != null) onLocationChanged(last); } catch (Exception e) {} // Ignore try { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, prefs.getGpsInterval(), prefs.getGpsDistance(), this); } catch (Exception e) { Log.e(TAG, "Failed to enable GPS", e); Toast.makeText(this, R.string.gps_failure, Toast.LENGTH_SHORT).show(); } gpsEnabled = true; } else if (!needed && gpsEnabled) { Log.d(TAG, "Disabling GPS updates"); locationManager.removeUpdates(this); gpsEnabled = false; } } public void setListenerNeedsGPS(boolean listenerNeedsGPS) { this.listenerNeedsGPS = listenerNeedsGPS; updateGPSState(); if (listenerNeedsGPS && externalListener != null && lastLocation != null) externalListener.onLocationChanged(lastLocation); } public void setListener(TrackerLocationListener listener) { if (listener == null) setListenerNeedsGPS(false); externalListener = listener; } }
false
true
private void startTrackingInternal() { if (tracking) return; NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this); Resources res = getResources(); Intent appStartIntent = new Intent(); appStartIntent .setAction(Intent.ACTION_MAIN) .addCategory(Intent.CATEGORY_LAUNCHER) .setComponent(new ComponentName(Main.class.getPackage().getName(), Main.class.getName())) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingAppIntent = PendingIntent.getActivity(this, 0, appStartIntent, 0); notificationBuilder .setContentTitle(res.getString(R.string.tracking_active_title)) .setContentText(res.getString(R.string.tracking_active_text)) .setSmallIcon(R.drawable.osm_logo) .setOngoing(true) .setUsesChronometer(true) .setContentIntent(pendingAppIntent); startForeground(R.id.notification_tracker, notificationBuilder.build()); tracking = true; track.markNewSegment(); try { Application.mainActivity.invalidateOptionsMenu(); } catch (Exception e) {} // ignore updateGPSState(); }
private void startTrackingInternal() { if (tracking) return; NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this); Resources res = getResources(); Intent appStartIntent = new Intent(); appStartIntent .setAction(Intent.ACTION_MAIN) .addCategory(Intent.CATEGORY_LAUNCHER) .setComponent(new ComponentName(Main.class.getPackage().getName(), Main.class.getName())) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingAppIntent = PendingIntent.getActivity(this, 0, appStartIntent, 0); notificationBuilder .setContentTitle(res.getString(R.string.tracking_active_title)) .setContentText(res.getString(R.string.tracking_active_text)) .setSmallIcon(R.drawable.osm_logo) .setOngoing(true) .setContentIntent(pendingAppIntent); //notificationBuilder.setUsesChronometer(true); startForeground(R.id.notification_tracker, notificationBuilder.getNotification()); tracking = true; track.markNewSegment(); try { Application.mainActivity.invalidateOptionsMenu(); } catch (Exception e) {} // ignore updateGPSState(); }
diff --git a/module-api/src/test/java/org/xbrlapi/cache/tests/CacheImplTestCase.java b/module-api/src/test/java/org/xbrlapi/cache/tests/CacheImplTestCase.java index 45b48e37..2e4722da 100644 --- a/module-api/src/test/java/org/xbrlapi/cache/tests/CacheImplTestCase.java +++ b/module-api/src/test/java/org/xbrlapi/cache/tests/CacheImplTestCase.java @@ -1,65 +1,65 @@ package org.xbrlapi.cache.tests; /** * @author Geoffrey Shuetrim ([email protected]) */ import java.io.File; import java.net.URL; import org.xbrlapi.cache.CacheImpl; import org.xbrlapi.utilities.BaseTestCase; public class CacheImplTestCase extends BaseTestCase { private String cacheRoot; protected void setUp() throws Exception { super.setUp(); cacheRoot = configuration.getProperty("local.cache"); } protected void tearDown() throws Exception { super.tearDown(); } /** * @param arg0 */ public CacheImplTestCase(String arg0) { super(arg0); } /** * Test operations on a simple URL */ public final void testSimpleURL() { try { this.examineURL(new URL("http://www.xbrl.org/2003/xbrl-instance-2003-12-31.xsd")); } catch (Exception e) { fail("Unexpected exception. " + e.getMessage()); } } public final void examineURL(URL originalURL) { try { CacheImpl cache = new CacheImpl(new File(cacheRoot)); assertFalse(cache.isCacheURL(originalURL)); File cacheFile = cache.getCacheFile(originalURL); URL cacheURL = cache.getCacheURL(originalURL); assertTrue(cache.isCacheURL(cacheURL)); URL newURL = cache.getOriginalURL(cacheURL); - assertEquals(originalURL.toString(), newURL.toString()); + assertEquals(originalURL, newURL); } catch (Exception e) { e.printStackTrace(); fail("Unexpected exception was thrown. " + e.getMessage()); } } }
true
true
public final void examineURL(URL originalURL) { try { CacheImpl cache = new CacheImpl(new File(cacheRoot)); assertFalse(cache.isCacheURL(originalURL)); File cacheFile = cache.getCacheFile(originalURL); URL cacheURL = cache.getCacheURL(originalURL); assertTrue(cache.isCacheURL(cacheURL)); URL newURL = cache.getOriginalURL(cacheURL); assertEquals(originalURL.toString(), newURL.toString()); } catch (Exception e) { e.printStackTrace(); fail("Unexpected exception was thrown. " + e.getMessage()); } }
public final void examineURL(URL originalURL) { try { CacheImpl cache = new CacheImpl(new File(cacheRoot)); assertFalse(cache.isCacheURL(originalURL)); File cacheFile = cache.getCacheFile(originalURL); URL cacheURL = cache.getCacheURL(originalURL); assertTrue(cache.isCacheURL(cacheURL)); URL newURL = cache.getOriginalURL(cacheURL); assertEquals(originalURL, newURL); } catch (Exception e) { e.printStackTrace(); fail("Unexpected exception was thrown. " + e.getMessage()); } }
diff --git a/java/src/steamcondenser/steam/community/GameStats.java b/java/src/steamcondenser/steam/community/GameStats.java index 7cb00ce..cc41fec 100644 --- a/java/src/steamcondenser/steam/community/GameStats.java +++ b/java/src/steamcondenser/steam/community/GameStats.java @@ -1,185 +1,185 @@ /** * This code is free software; you can redistribute it and/or modify it under * the terms of the new BSD License. * * Copyright (c) 2008-2010, Sebastian Staudt */ package steamcondenser.steam.community; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import steamcondenser.SteamCondenserException; import steamcondenser.steam.community.css.CSSStats; import steamcondenser.steam.community.defense_grid.DefenseGridStats; import steamcondenser.steam.community.dods.DoDSStats; import steamcondenser.steam.community.l4d.L4DStats; import steamcondenser.steam.community.l4d.L4D2Stats; import steamcondenser.steam.community.tf2.TF2Stats; /** * The GameStats class represents the game statistics for a single user and a * specific game * * @author Sebastian Staudt */ public class GameStats { protected ArrayList<GameAchievement> achievements; protected int achievementsDone; protected int appId; protected String customUrl; protected String gameFriendlyName; protected String gameName; protected String hoursPlayed; protected String privacyState; protected Long steamId64; protected Element xmlData; public static GameStats createGameStats(Object steamId, String gameName) throws SteamCondenserException { if(gameName.equals("cs:s")) { return new CSSStats(steamId); } else if(gameName.equals("defensegrid:awakening")) { return new DefenseGridStats(steamId); } else if(gameName.equals("dod:s")) { return new DoDSStats(steamId); } else if(gameName.equals("l4d")) { return new L4DStats(steamId); } else if(gameName.equals("l4d2")) { return new L4D2Stats(steamId); } else if(gameName.equals("tf2")) { return new TF2Stats(steamId); } else { return new GameStats(steamId, gameName); } } protected GameStats(Object steamId, String gameName) throws SteamCondenserException { if(steamId instanceof String) { this.customUrl = (String) steamId; } else if(steamId instanceof Long) { this.steamId64 = (Long) steamId; } this.gameName = gameName; this.fetch(); } protected void fetch() throws SteamCondenserException { String url; try { if(this.customUrl == null) { url = "http://steamcommunity.com/profile/" + this.steamId64 + "/stats/" + this.gameName; } else { url = "http://steamcommunity.com/id/" + this.customUrl + "/stats/" + this.gameName; } url += "?xml=all"; DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); this.xmlData = parser.parse(url).getDocumentElement(); this.privacyState = this.xmlData.getElementsByTagName("privacyState").item(0).getTextContent(); if(this.isPublic()) { this.appId = Integer.parseInt(((Element) this.xmlData.getElementsByTagName("game").item(0)).getElementsByTagName("gameLink").item(0).getTextContent().replace("http://store.steampowered.com/app/", "")); this.gameFriendlyName = ((Element) this.xmlData.getElementsByTagName("game").item(0)).getElementsByTagName("gameFriendlyName").item(0).getTextContent(); this.gameName = ((Element) this.xmlData.getElementsByTagName("game").item(0)).getElementsByTagName("gameName").item(0).getTextContent(); Node hoursPlayedNode = ((Element) this.xmlData.getElementsByTagName("stats").item(0)).getElementsByTagName("hoursPlayed").item(0); if(hoursPlayedNode != null) { this.hoursPlayed = hoursPlayedNode.getTextContent(); } if(this.customUrl == null) { this.customUrl = ((Element) this.xmlData.getElementsByTagName("player").item(0)).getElementsByTagName("customURL").item(0).getTextContent(); } if(this.steamId64 == null) { - this.steamId64 = Long.parseLong(((Element) this.xmlData.getElementsByTagName("player").item(0)).getElementsByTagName("steamID64").item(0).getTextContent()); + this.steamId64 = Long.parseLong(((Element) this.xmlData.getElementsByTagName("player").item(0)).getElementsByTagName("steamID64").item(0).getTextContent().trim()); } } } catch(Exception e) { throw new SteamCondenserException("XML data could not be parsed."); } } /** * @return Returns the achievements for this stats' user and game. If the * achievements haven't been parsed already, parsing is done now. */ public ArrayList<GameAchievement> getAchievements() { if(this.achievements == null) { this.achievements = new ArrayList<GameAchievement>(); this.achievementsDone = 0; NodeList achievementsList = ((Element) this.xmlData.getElementsByTagName("achievements").item(0)).getElementsByTagName("achievement"); for(int i = 0; i < achievementsList.getLength(); i++) { Element achievementData = (Element) achievementsList.item(i); GameAchievement achievement = new GameAchievement(this.steamId64, this.appId, achievementData); if(achievement.isUnlocked()) { this.achievementsDone += 1; } this.achievements.add(achievement); } } return achievements; } /** * Returns the count of achievements done by this player. If achievements * haven't been parsed yet, parsing is done now. * * @return The number of unlocked achievements */ public int getAchievementsDone() { if(this.achievements == null) { this.getAchievements(); } return this.achievementsDone; } /** * Returns a float value representing the percentage of achievements done by * this player. If achievements haven't been parsed yet, parsing is done * now. * * @return The percentage of unlocked achievements */ public float getAchievementsPercentage() { return (float) this.getAchievementsDone() / this.achievements.size(); } public String getGameFriendlyName() { return this.gameFriendlyName; } public String getGameName() { return this.gameName; } public String getHoursPlayed() { return this.hoursPlayed; } protected boolean isPublic() { return this.privacyState.equals("public"); } }
true
true
protected void fetch() throws SteamCondenserException { String url; try { if(this.customUrl == null) { url = "http://steamcommunity.com/profile/" + this.steamId64 + "/stats/" + this.gameName; } else { url = "http://steamcommunity.com/id/" + this.customUrl + "/stats/" + this.gameName; } url += "?xml=all"; DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); this.xmlData = parser.parse(url).getDocumentElement(); this.privacyState = this.xmlData.getElementsByTagName("privacyState").item(0).getTextContent(); if(this.isPublic()) { this.appId = Integer.parseInt(((Element) this.xmlData.getElementsByTagName("game").item(0)).getElementsByTagName("gameLink").item(0).getTextContent().replace("http://store.steampowered.com/app/", "")); this.gameFriendlyName = ((Element) this.xmlData.getElementsByTagName("game").item(0)).getElementsByTagName("gameFriendlyName").item(0).getTextContent(); this.gameName = ((Element) this.xmlData.getElementsByTagName("game").item(0)).getElementsByTagName("gameName").item(0).getTextContent(); Node hoursPlayedNode = ((Element) this.xmlData.getElementsByTagName("stats").item(0)).getElementsByTagName("hoursPlayed").item(0); if(hoursPlayedNode != null) { this.hoursPlayed = hoursPlayedNode.getTextContent(); } if(this.customUrl == null) { this.customUrl = ((Element) this.xmlData.getElementsByTagName("player").item(0)).getElementsByTagName("customURL").item(0).getTextContent(); } if(this.steamId64 == null) { this.steamId64 = Long.parseLong(((Element) this.xmlData.getElementsByTagName("player").item(0)).getElementsByTagName("steamID64").item(0).getTextContent()); } } } catch(Exception e) { throw new SteamCondenserException("XML data could not be parsed."); } }
protected void fetch() throws SteamCondenserException { String url; try { if(this.customUrl == null) { url = "http://steamcommunity.com/profile/" + this.steamId64 + "/stats/" + this.gameName; } else { url = "http://steamcommunity.com/id/" + this.customUrl + "/stats/" + this.gameName; } url += "?xml=all"; DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); this.xmlData = parser.parse(url).getDocumentElement(); this.privacyState = this.xmlData.getElementsByTagName("privacyState").item(0).getTextContent(); if(this.isPublic()) { this.appId = Integer.parseInt(((Element) this.xmlData.getElementsByTagName("game").item(0)).getElementsByTagName("gameLink").item(0).getTextContent().replace("http://store.steampowered.com/app/", "")); this.gameFriendlyName = ((Element) this.xmlData.getElementsByTagName("game").item(0)).getElementsByTagName("gameFriendlyName").item(0).getTextContent(); this.gameName = ((Element) this.xmlData.getElementsByTagName("game").item(0)).getElementsByTagName("gameName").item(0).getTextContent(); Node hoursPlayedNode = ((Element) this.xmlData.getElementsByTagName("stats").item(0)).getElementsByTagName("hoursPlayed").item(0); if(hoursPlayedNode != null) { this.hoursPlayed = hoursPlayedNode.getTextContent(); } if(this.customUrl == null) { this.customUrl = ((Element) this.xmlData.getElementsByTagName("player").item(0)).getElementsByTagName("customURL").item(0).getTextContent(); } if(this.steamId64 == null) { this.steamId64 = Long.parseLong(((Element) this.xmlData.getElementsByTagName("player").item(0)).getElementsByTagName("steamID64").item(0).getTextContent().trim()); } } } catch(Exception e) { throw new SteamCondenserException("XML data could not be parsed."); } }