diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/com/android/settings/paranoid/Pie.java b/src/com/android/settings/paranoid/Pie.java index c6111be38..158d12694 100644 --- a/src/com/android/settings/paranoid/Pie.java +++ b/src/com/android/settings/paranoid/Pie.java @@ -1,263 +1,263 @@ /* * Copyright (C) 2012 ParanoidAndroid 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.settings.paranoid; import android.app.AlertDialog; import android.content.Context; import android.content.ContentResolver; import android.database.ContentObserver; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnMultiChoiceClickListener; import android.os.Bundle; import android.os.Handler; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceCategory; import android.preference.PreferenceScreen; import android.preference.Preference.OnPreferenceClickListener; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import com.android.settings.R; import com.android.settings.SettingsPreferenceFragment; import com.android.settings.Utils; import com.android.settings.util.Helpers; import net.margaritov.preference.colorpicker.ColorPickerPreference; public class Pie extends SettingsPreferenceFragment implements Preference.OnPreferenceChangeListener { private static final String PIE_CONTROLS = "pie_controls"; private static final String PIE_GRAVITY = "pie_gravity"; private static final String PIE_MODE = "pie_mode"; private static final String PIE_SIZE = "pie_size"; private static final String PIE_TRIGGER = "pie_trigger"; private static final String PIE_ANGLE = "pie_angle"; private static final String PIE_GAP = "pie_gap"; private static final String PIE_CENTER = "pie_center"; private static final String PIE_STICK = "pie_stick"; private static final String PIE_NOTIFICATIONS = "pie_notifications"; private static final String PIE_LASTAPP = "pie_lastapp"; private static final String PIE_MENU = "pie_menu"; private static final String PIE_SEARCH = "pie_search"; private static final String PIE_RESTART = "pie_restart_launcher"; private ListPreference mPieMode; private ListPreference mPieSize; private ListPreference mPieGravity; private ListPreference mPieTrigger; private ListPreference mPieAngle; private ListPreference mPieGap; private CheckBoxPreference mPieCenter; private CheckBoxPreference mPieNotifi; private CheckBoxPreference mPieControls; private CheckBoxPreference mPieLastApp; private CheckBoxPreference mPieMenu; private CheckBoxPreference mPieSearch; private CheckBoxPreference mPieStick; private CheckBoxPreference mPieRestart; private Context mContext; private int mAllowedLocations; protected Handler mHandler; private SettingsObserver mSettingsObserver; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pie_settings); PreferenceScreen prefSet = getPreferenceScreen(); mContext = getActivity().getApplicationContext(); ContentResolver resolver = mContext.getContentResolver(); mPieRestart = (CheckBoxPreference) prefSet.findPreference(PIE_RESTART); mPieRestart.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.EXPANDED_DESKTOP_RESTART_LAUNCHER, 1) == 1); mSettingsObserver = new SettingsObserver(new Handler()); mPieControls = (CheckBoxPreference) findPreference(PIE_CONTROLS); mPieControls.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_CONTROLS, 0) == 1); mPieGravity = (ListPreference) prefSet.findPreference(PIE_GRAVITY); int pieGravity = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_GRAVITY, 3); mPieGravity.setValue(String.valueOf(pieGravity)); mPieGravity.setOnPreferenceChangeListener(this); mPieMode = (ListPreference) prefSet.findPreference(PIE_MODE); int pieMode = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_MODE, 2); mPieMode.setValue(String.valueOf(pieMode)); mPieMode.setOnPreferenceChangeListener(this); mPieSize = (ListPreference) prefSet.findPreference(PIE_SIZE); mPieTrigger = (ListPreference) prefSet.findPreference(PIE_TRIGGER); try { float pieSize = Settings.System.getFloat(mContext.getContentResolver(), - Settings.System.PIE_SIZE, 0.9f); + Settings.System.PIE_SIZE, 1.0f); mPieSize.setValue(String.valueOf(pieSize)); float pieTrigger = Settings.System.getFloat(mContext.getContentResolver(), Settings.System.PIE_TRIGGER); mPieTrigger.setValue(String.valueOf(pieTrigger)); } catch(Settings.SettingNotFoundException ex) { // So what } mPieSize.setOnPreferenceChangeListener(this); mPieTrigger.setOnPreferenceChangeListener(this); mPieCenter = (CheckBoxPreference) prefSet.findPreference(PIE_CENTER); mPieCenter.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_CENTER, 1) == 1); mPieStick = (CheckBoxPreference) prefSet.findPreference(PIE_STICK); mPieStick.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_STICK, 1) == 1); mPieGap = (ListPreference) prefSet.findPreference(PIE_GAP); int pieGap = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_GAP, 3); mPieGap.setValue(String.valueOf(pieGap)); mPieGap.setOnPreferenceChangeListener(this); mPieNotifi = (CheckBoxPreference) prefSet.findPreference(PIE_NOTIFICATIONS); mPieNotifi.setChecked((Settings.System.getInt(getContentResolver(), Settings.System.PIE_NOTIFICATIONS, 0) == 1)); mPieAngle = (ListPreference) prefSet.findPreference(PIE_ANGLE); int pieAngle = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_ANGLE, 12); mPieAngle.setValue(String.valueOf(pieAngle)); mPieAngle.setOnPreferenceChangeListener(this); mPieLastApp = (CheckBoxPreference) prefSet.findPreference(PIE_LASTAPP); mPieLastApp.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_LAST_APP, 1) == 1); mPieMenu = (CheckBoxPreference) prefSet.findPreference(PIE_MENU); mPieMenu.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_MENU, 1) == 1); mPieSearch = (CheckBoxPreference) prefSet.findPreference(PIE_SEARCH); mPieSearch.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_SEARCH, 1) == 1); checkControls(); } private void checkControls() { boolean pieCheck = mPieControls.isChecked(); mPieGravity.setEnabled(pieCheck); mPieMode.setEnabled(pieCheck); mPieSize.setEnabled(pieCheck); mPieTrigger.setEnabled(pieCheck); mPieGap.setEnabled(pieCheck); mPieNotifi.setEnabled(pieCheck); } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (preference == mPieControls) { Settings.System.putInt(mContext.getContentResolver(), Settings.System.PIE_CONTROLS, mPieControls.isChecked() ? 1 : 0); checkControls(); } else if (preference == mPieNotifi) { Settings.System.putInt(mContext.getContentResolver(), Settings.System.PIE_NOTIFICATIONS, mPieNotifi.isChecked() ? 1 : 0); } else if (preference == mPieLastApp) { Settings.System.putInt(getActivity().getApplicationContext().getContentResolver(), Settings.System.PIE_LAST_APP, mPieLastApp.isChecked() ? 1 : 0); } else if (preference == mPieMenu) { Settings.System.putInt(getActivity().getApplicationContext().getContentResolver(), Settings.System.PIE_MENU, mPieMenu.isChecked() ? 1 : 0); } else if (preference == mPieSearch) { Settings.System.putInt(getActivity().getApplicationContext().getContentResolver(), Settings.System.PIE_SEARCH, mPieSearch.isChecked() ? 1 : 0); } else if (preference == mPieCenter) { Settings.System.putInt(getActivity().getApplicationContext().getContentResolver(), Settings.System.PIE_CENTER, mPieCenter.isChecked() ? 1 : 0); } else if (preference == mPieStick) { Settings.System.putInt(getActivity().getApplicationContext().getContentResolver(), Settings.System.PIE_STICK, mPieStick.isChecked() ? 1 : 0); } else if (preference == mPieRestart) { Settings.System.putInt(getActivity().getApplicationContext().getContentResolver(), Settings.System.EXPANDED_DESKTOP_RESTART_LAUNCHER, mPieRestart.isChecked() ? 1 : 0); } return super.onPreferenceTreeClick(preferenceScreen, preference); } public boolean onPreferenceChange(Preference preference, Object newValue) { if (preference == mPieMode) { int pieMode = Integer.valueOf((String) newValue); Settings.System.putInt(getActivity().getContentResolver(), Settings.System.PIE_MODE, pieMode); return true; } else if (preference == mPieSize) { float pieSize = Float.valueOf((String) newValue); Settings.System.putFloat(getActivity().getContentResolver(), Settings.System.PIE_SIZE, pieSize); return true; } else if (preference == mPieGravity) { int pieGravity = Integer.valueOf((String) newValue); Settings.System.putInt(getActivity().getContentResolver(), Settings.System.PIE_GRAVITY, pieGravity); return true; } else if (preference == mPieAngle) { int pieAngle = Integer.valueOf((String) newValue); Settings.System.putInt(getActivity().getContentResolver(), Settings.System.PIE_ANGLE, pieAngle); return true; } else if (preference == mPieGap) { int pieGap = Integer.valueOf((String) newValue); Settings.System.putInt(getActivity().getContentResolver(), Settings.System.PIE_GAP, pieGap); return true; } else if (preference == mPieTrigger) { float pieTrigger = Float.valueOf((String) newValue); Settings.System.putFloat(getActivity().getContentResolver(), Settings.System.PIE_TRIGGER, pieTrigger); return true; } return false; } class SettingsObserver extends ContentObserver { SettingsObserver(Handler handler) { super(handler); observe(); } void observe() { ContentResolver resolver = mContext.getContentResolver(); resolver.registerContentObserver( Settings.System.getUriFor(Settings.System.PIE_CONTROLS), false, this); } @Override public void onChange(boolean selfChange) { Helpers.restartSystemUI(); } } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pie_settings); PreferenceScreen prefSet = getPreferenceScreen(); mContext = getActivity().getApplicationContext(); ContentResolver resolver = mContext.getContentResolver(); mPieRestart = (CheckBoxPreference) prefSet.findPreference(PIE_RESTART); mPieRestart.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.EXPANDED_DESKTOP_RESTART_LAUNCHER, 1) == 1); mSettingsObserver = new SettingsObserver(new Handler()); mPieControls = (CheckBoxPreference) findPreference(PIE_CONTROLS); mPieControls.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_CONTROLS, 0) == 1); mPieGravity = (ListPreference) prefSet.findPreference(PIE_GRAVITY); int pieGravity = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_GRAVITY, 3); mPieGravity.setValue(String.valueOf(pieGravity)); mPieGravity.setOnPreferenceChangeListener(this); mPieMode = (ListPreference) prefSet.findPreference(PIE_MODE); int pieMode = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_MODE, 2); mPieMode.setValue(String.valueOf(pieMode)); mPieMode.setOnPreferenceChangeListener(this); mPieSize = (ListPreference) prefSet.findPreference(PIE_SIZE); mPieTrigger = (ListPreference) prefSet.findPreference(PIE_TRIGGER); try { float pieSize = Settings.System.getFloat(mContext.getContentResolver(), Settings.System.PIE_SIZE, 0.9f); mPieSize.setValue(String.valueOf(pieSize)); float pieTrigger = Settings.System.getFloat(mContext.getContentResolver(), Settings.System.PIE_TRIGGER); mPieTrigger.setValue(String.valueOf(pieTrigger)); } catch(Settings.SettingNotFoundException ex) { // So what } mPieSize.setOnPreferenceChangeListener(this); mPieTrigger.setOnPreferenceChangeListener(this); mPieCenter = (CheckBoxPreference) prefSet.findPreference(PIE_CENTER); mPieCenter.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_CENTER, 1) == 1); mPieStick = (CheckBoxPreference) prefSet.findPreference(PIE_STICK); mPieStick.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_STICK, 1) == 1); mPieGap = (ListPreference) prefSet.findPreference(PIE_GAP); int pieGap = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_GAP, 3); mPieGap.setValue(String.valueOf(pieGap)); mPieGap.setOnPreferenceChangeListener(this); mPieNotifi = (CheckBoxPreference) prefSet.findPreference(PIE_NOTIFICATIONS); mPieNotifi.setChecked((Settings.System.getInt(getContentResolver(), Settings.System.PIE_NOTIFICATIONS, 0) == 1)); mPieAngle = (ListPreference) prefSet.findPreference(PIE_ANGLE); int pieAngle = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_ANGLE, 12); mPieAngle.setValue(String.valueOf(pieAngle)); mPieAngle.setOnPreferenceChangeListener(this); mPieLastApp = (CheckBoxPreference) prefSet.findPreference(PIE_LASTAPP); mPieLastApp.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_LAST_APP, 1) == 1); mPieMenu = (CheckBoxPreference) prefSet.findPreference(PIE_MENU); mPieMenu.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_MENU, 1) == 1); mPieSearch = (CheckBoxPreference) prefSet.findPreference(PIE_SEARCH); mPieSearch.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_SEARCH, 1) == 1); checkControls(); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pie_settings); PreferenceScreen prefSet = getPreferenceScreen(); mContext = getActivity().getApplicationContext(); ContentResolver resolver = mContext.getContentResolver(); mPieRestart = (CheckBoxPreference) prefSet.findPreference(PIE_RESTART); mPieRestart.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.EXPANDED_DESKTOP_RESTART_LAUNCHER, 1) == 1); mSettingsObserver = new SettingsObserver(new Handler()); mPieControls = (CheckBoxPreference) findPreference(PIE_CONTROLS); mPieControls.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_CONTROLS, 0) == 1); mPieGravity = (ListPreference) prefSet.findPreference(PIE_GRAVITY); int pieGravity = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_GRAVITY, 3); mPieGravity.setValue(String.valueOf(pieGravity)); mPieGravity.setOnPreferenceChangeListener(this); mPieMode = (ListPreference) prefSet.findPreference(PIE_MODE); int pieMode = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_MODE, 2); mPieMode.setValue(String.valueOf(pieMode)); mPieMode.setOnPreferenceChangeListener(this); mPieSize = (ListPreference) prefSet.findPreference(PIE_SIZE); mPieTrigger = (ListPreference) prefSet.findPreference(PIE_TRIGGER); try { float pieSize = Settings.System.getFloat(mContext.getContentResolver(), Settings.System.PIE_SIZE, 1.0f); mPieSize.setValue(String.valueOf(pieSize)); float pieTrigger = Settings.System.getFloat(mContext.getContentResolver(), Settings.System.PIE_TRIGGER); mPieTrigger.setValue(String.valueOf(pieTrigger)); } catch(Settings.SettingNotFoundException ex) { // So what } mPieSize.setOnPreferenceChangeListener(this); mPieTrigger.setOnPreferenceChangeListener(this); mPieCenter = (CheckBoxPreference) prefSet.findPreference(PIE_CENTER); mPieCenter.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_CENTER, 1) == 1); mPieStick = (CheckBoxPreference) prefSet.findPreference(PIE_STICK); mPieStick.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_STICK, 1) == 1); mPieGap = (ListPreference) prefSet.findPreference(PIE_GAP); int pieGap = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_GAP, 3); mPieGap.setValue(String.valueOf(pieGap)); mPieGap.setOnPreferenceChangeListener(this); mPieNotifi = (CheckBoxPreference) prefSet.findPreference(PIE_NOTIFICATIONS); mPieNotifi.setChecked((Settings.System.getInt(getContentResolver(), Settings.System.PIE_NOTIFICATIONS, 0) == 1)); mPieAngle = (ListPreference) prefSet.findPreference(PIE_ANGLE); int pieAngle = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_ANGLE, 12); mPieAngle.setValue(String.valueOf(pieAngle)); mPieAngle.setOnPreferenceChangeListener(this); mPieLastApp = (CheckBoxPreference) prefSet.findPreference(PIE_LASTAPP); mPieLastApp.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_LAST_APP, 1) == 1); mPieMenu = (CheckBoxPreference) prefSet.findPreference(PIE_MENU); mPieMenu.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_MENU, 1) == 1); mPieSearch = (CheckBoxPreference) prefSet.findPreference(PIE_SEARCH); mPieSearch.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_SEARCH, 1) == 1); checkControls(); }
diff --git a/nuxeo-drive-server/nuxeo-drive-hierarchy-permission/src/main/java/org/nuxeo/drive/hierarchy/permission/adapter/PermissionTopLevelFolderItem.java b/nuxeo-drive-server/nuxeo-drive-hierarchy-permission/src/main/java/org/nuxeo/drive/hierarchy/permission/adapter/PermissionTopLevelFolderItem.java index 67d54377..d3838d7a 100644 --- a/nuxeo-drive-server/nuxeo-drive-hierarchy-permission/src/main/java/org/nuxeo/drive/hierarchy/permission/adapter/PermissionTopLevelFolderItem.java +++ b/nuxeo-drive-server/nuxeo-drive-hierarchy-permission/src/main/java/org/nuxeo/drive/hierarchy/permission/adapter/PermissionTopLevelFolderItem.java @@ -1,79 +1,81 @@ /* * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Antoine Taillefer <[email protected]> */ package org.nuxeo.drive.hierarchy.permission.adapter; import java.security.Principal; import java.util.ArrayList; import java.util.List; import org.nuxeo.drive.adapter.FileSystemItem; import org.nuxeo.drive.adapter.FolderItem; import org.nuxeo.drive.adapter.impl.AbstractVirtualFolderItem; import org.nuxeo.drive.service.VirtualFolderItemFactory; import org.nuxeo.ecm.core.api.ClientException; /** * User workspace and permission based implementation of the top level * {@link FolderItem}. * <p> * Implements the following tree: * * <pre> * Nuxeo Drive * |-- My Documents (= user workspace if synchronized else user synchronization roots) * | |-- Folder 1 * | |-- Folder 2 * | |-- ... * |-- Other Documents (= user's shared synchronized roots with ReadWrite permission) * | |-- Other folder 1 * | |-- Other folder 2 * | |-- ... * </pre> * * @author Antoine Taillefer */ public class PermissionTopLevelFolderItem extends AbstractVirtualFolderItem { private static final long serialVersionUID = 5179858544427598560L; protected List<String> childrenFactoryNames; public PermissionTopLevelFolderItem(String factoryName, Principal principal, String folderName, List<String> childrenFactoryNames) throws ClientException { super(factoryName, principal, null, null, folderName); this.childrenFactoryNames = childrenFactoryNames; } protected PermissionTopLevelFolderItem() { // Needed for JSON deserialization } @Override public List<FileSystemItem> getChildren() throws ClientException { List<FileSystemItem> children = new ArrayList<FileSystemItem>(); for (String childFactoryName : childrenFactoryNames) { VirtualFolderItemFactory factory = getFileSystemItemAdapterService().getVirtualFolderItemFactory( childFactoryName); FileSystemItem child = factory.getVirtualFolderItem(principal); - children.add(child); + if (child != null) { + children.add(child); + } } return children; } }
true
true
public List<FileSystemItem> getChildren() throws ClientException { List<FileSystemItem> children = new ArrayList<FileSystemItem>(); for (String childFactoryName : childrenFactoryNames) { VirtualFolderItemFactory factory = getFileSystemItemAdapterService().getVirtualFolderItemFactory( childFactoryName); FileSystemItem child = factory.getVirtualFolderItem(principal); children.add(child); } return children; }
public List<FileSystemItem> getChildren() throws ClientException { List<FileSystemItem> children = new ArrayList<FileSystemItem>(); for (String childFactoryName : childrenFactoryNames) { VirtualFolderItemFactory factory = getFileSystemItemAdapterService().getVirtualFolderItemFactory( childFactoryName); FileSystemItem child = factory.getVirtualFolderItem(principal); if (child != null) { children.add(child); } } return children; }
diff --git a/src/main/java/example/suspendable/SuspendResumeActor.java b/src/main/java/example/suspendable/SuspendResumeActor.java index b04046d..821e311 100644 --- a/src/main/java/example/suspendable/SuspendResumeActor.java +++ b/src/main/java/example/suspendable/SuspendResumeActor.java @@ -1,54 +1,54 @@ package example.suspendable; import java.io.Serializable; import monterey.actor.Actor; import monterey.actor.ActorContext; import monterey.actor.MessageContext; import monterey.actor.trait.Suspendable; /** * A very simple example of implementing a suspendable Actor. * * This shows how an actor can preserve its state when being suspended and resumed * (including when being moved to a different location in between). Any subscriptions * done in start() will be automatically re-subscribed. * * On resume, it will be a different instance of the actor so its fields must be * set on resume. * * In this class, the state is a simple counter of the number of messages received. */ public class SuspendResumeActor implements Actor, Suspendable { private ActorContext context; private long count; @Override public void init(ActorContext context) { this.context = context; } @Override public void onMessage(Object payload, MessageContext messageContext) { count++; - // Publish the latest count (primarily for purpose of testing this actor) + // Publish the latest count (primarily for the purpose of testing this actor). context.publish("count", count); } @Override public void start(Object state) { count = 0; context.subscribe("topic1"); } @Override public Serializable suspend() { return count; } @Override public void resume(Object state) { count = (Long) state; } }
true
true
public void onMessage(Object payload, MessageContext messageContext) { count++; // Publish the latest count (primarily for purpose of testing this actor) context.publish("count", count); }
public void onMessage(Object payload, MessageContext messageContext) { count++; // Publish the latest count (primarily for the purpose of testing this actor). context.publish("count", count); }
diff --git a/src/de/tum/in/tumcampus/Debug.java b/src/de/tum/in/tumcampus/Debug.java index bfb3f38..0617784 100644 --- a/src/de/tum/in/tumcampus/Debug.java +++ b/src/de/tum/in/tumcampus/Debug.java @@ -1,93 +1,93 @@ package de.tum.in.tumcampus; import android.app.Activity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.text.method.ScrollingMovementMethod; import android.view.View; import android.widget.Button; import android.widget.TextView; public class Debug extends Activity implements View.OnClickListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.debug); Button b = (Button) findViewById(R.id.debugCafeterias); b.setOnClickListener(this); b = (Button) findViewById(R.id.debugCafeteriasMenus); b.setOnClickListener(this); b = (Button) findViewById(R.id.debugFeeds); b.setOnClickListener(this); b = (Button) findViewById(R.id.debugFeedsItems); b.setOnClickListener(this); b = (Button) findViewById(R.id.debugLinks); b.setOnClickListener(this); b = (Button) findViewById(R.id.debugEvents); b.setOnClickListener(this); } public void DebugReset() { TextView tv = (TextView) findViewById(R.id.debug); tv.setText(""); } public void DebugStr(String s) { TextView tv = (TextView) findViewById(R.id.debug); tv.setMovementMethod(new ScrollingMovementMethod()); tv.append(s + "\n"); } public void DebugSQL(String query) { DebugReset(); SQLiteDatabase db = SQLiteDatabase.openDatabase( this.getDatabasePath("database.db").toString(), null, SQLiteDatabase.OPEN_READONLY); Cursor c = db.rawQuery(query, null); while (c.moveToNext()) { for (int i = 0; i < c.getColumnCount(); i++) { DebugStr(c.getColumnName(i) + ": " + c.getString(i)); } DebugStr(""); } c.close(); db.close(); } @Override public void onClick(View v) { if (v.getId() == R.id.debugCafeterias) { DebugSQL("SELECT * FROM cafeterias ORDER BY id"); } if (v.getId() == R.id.debugCafeteriasMenus) { DebugSQL("SELECT * FROM cafeterias_menus ORDER BY id"); } if (v.getId() == R.id.debugFeeds) { DebugSQL("SELECT * FROM feeds ORDER BY id"); } if (v.getId() == R.id.debugFeedsItems) { - DebugSQL("SELECT * FROM feeds ORDER BY feedId"); + DebugSQL("SELECT * FROM feeds_items ORDER BY feedId"); } if (v.getId() == R.id.debugLinks) { DebugSQL("SELECT * FROM links ORDER BY id"); } if (v.getId() == R.id.debugEvents) { DebugSQL("SELECT * FROM events ORDER BY id"); } } }
true
true
public void onClick(View v) { if (v.getId() == R.id.debugCafeterias) { DebugSQL("SELECT * FROM cafeterias ORDER BY id"); } if (v.getId() == R.id.debugCafeteriasMenus) { DebugSQL("SELECT * FROM cafeterias_menus ORDER BY id"); } if (v.getId() == R.id.debugFeeds) { DebugSQL("SELECT * FROM feeds ORDER BY id"); } if (v.getId() == R.id.debugFeedsItems) { DebugSQL("SELECT * FROM feeds ORDER BY feedId"); } if (v.getId() == R.id.debugLinks) { DebugSQL("SELECT * FROM links ORDER BY id"); } if (v.getId() == R.id.debugEvents) { DebugSQL("SELECT * FROM events ORDER BY id"); } }
public void onClick(View v) { if (v.getId() == R.id.debugCafeterias) { DebugSQL("SELECT * FROM cafeterias ORDER BY id"); } if (v.getId() == R.id.debugCafeteriasMenus) { DebugSQL("SELECT * FROM cafeterias_menus ORDER BY id"); } if (v.getId() == R.id.debugFeeds) { DebugSQL("SELECT * FROM feeds ORDER BY id"); } if (v.getId() == R.id.debugFeedsItems) { DebugSQL("SELECT * FROM feeds_items ORDER BY feedId"); } if (v.getId() == R.id.debugLinks) { DebugSQL("SELECT * FROM links ORDER BY id"); } if (v.getId() == R.id.debugEvents) { DebugSQL("SELECT * FROM events ORDER BY id"); } }
diff --git a/onebusaway-transit-data-federation/src/test/java/org/onebusaway/transit_data_federation/impl/realtime/BlockLocationServiceImplTest.java b/onebusaway-transit-data-federation/src/test/java/org/onebusaway/transit_data_federation/impl/realtime/BlockLocationServiceImplTest.java index 9a4357d1..bde5a78b 100644 --- a/onebusaway-transit-data-federation/src/test/java/org/onebusaway/transit_data_federation/impl/realtime/BlockLocationServiceImplTest.java +++ b/onebusaway-transit-data-federation/src/test/java/org/onebusaway/transit_data_federation/impl/realtime/BlockLocationServiceImplTest.java @@ -1,144 +1,133 @@ package org.onebusaway.transit_data_federation.impl.realtime; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.onebusaway.transit_data_federation.testing.UnitTestingSupport.block; import static org.onebusaway.transit_data_federation.testing.UnitTestingSupport.linkBlockTrips; import static org.onebusaway.transit_data_federation.testing.UnitTestingSupport.stop; import static org.onebusaway.transit_data_federation.testing.UnitTestingSupport.stopTime; import static org.onebusaway.transit_data_federation.testing.UnitTestingSupport.trip; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.onebusaway.geospatial.model.CoordinatePoint; import org.onebusaway.transit_data_federation.impl.transit_graph.BlockEntryImpl; import org.onebusaway.transit_data_federation.impl.transit_graph.StopEntryImpl; import org.onebusaway.transit_data_federation.impl.transit_graph.TripEntryImpl; import org.onebusaway.transit_data_federation.services.blocks.BlockCalendarService; import org.onebusaway.transit_data_federation.services.blocks.BlockInstance; import org.onebusaway.transit_data_federation.services.blocks.ScheduledBlockLocation; import org.onebusaway.transit_data_federation.services.blocks.ScheduledBlockLocationService; import org.onebusaway.transit_data_federation.services.realtime.BlockLocation; import org.onebusaway.transit_data_federation.services.transit_graph.BlockConfigurationEntry; import org.onebusaway.transit_data_federation.services.transit_graph.TransitGraphDao; public class BlockLocationServiceImplTest { private BlockLocationServiceImpl _service; private TransitGraphDao _transitGraphDao; private ScheduledBlockLocationService _blockLocationService; private BlockCalendarService _blockCalendarService; @Before public void setup() { _service = new BlockLocationServiceImpl(); _transitGraphDao = Mockito.mock(TransitGraphDao.class); _service.setTransitGraphDao(_transitGraphDao); _blockLocationService = Mockito.mock(ScheduledBlockLocationService.class); _service.setScheduledBlockLocationService(_blockLocationService); _service.setVehicleLocationRecordCache(new VehicleLocationRecordCacheImpl()); _blockCalendarService = Mockito.mock(BlockCalendarService.class); _service.setBlockCalendarService(_blockCalendarService); } @Test public void testApplyRealtimeData() { } @Test public void testWithShapeInfo() { StopEntryImpl stopA = stop("a", 47.5, -122.5); StopEntryImpl stopB = stop("b", 47.6, -122.4); StopEntryImpl stopC = stop("c", 47.5, -122.3); BlockEntryImpl block = block("block"); TripEntryImpl tripA = trip("tripA", "serviceId"); TripEntryImpl tripB = trip("tripB", "serviceId"); stopTime(0, stopA, tripA, 30, 90, 0); stopTime(1, stopB, tripA, 120, 120, 100); stopTime(2, stopC, tripA, 180, 210, 200); stopTime(3, stopC, tripB, 240, 240, 300); stopTime(4, stopB, tripB, 270, 270, 400); stopTime(5, stopA, tripB, 300, 300, 500); BlockConfigurationEntry blockConfig = linkBlockTrips(block, tripA, tripB); long serviceDate = 1000 * 1000; double epsilon = 0.001; BlockInstance blockInstance = new BlockInstance(blockConfig, serviceDate); BlockLocation location = _service.getLocationForBlockInstance( blockInstance, t(serviceDate, 0, 0)); - assertFalse(location.isInService()); - assertNull(location.getClosestStop()); - assertEquals(0, location.getClosestStopTimeOffset()); - assertFalse(location.isScheduleDeviationSet()); - assertTrue(Double.isNaN(location.getScheduleDeviation())); - assertFalse(location.isDistanceAlongBlockSet()); - assertTrue(Double.isNaN(location.getDistanceAlongBlock())); - assertNull(location.getLocation()); - assertEquals(blockInstance, location.getBlockInstance()); - assertEquals(0, location.getLastUpdateTime()); - assertNull(location.getActiveTrip()); - assertNull(location.getVehicleId()); + assertNull(location); ScheduledBlockLocation p = new ScheduledBlockLocation(); p.setActiveTrip(blockConfig.getTrips().get(0)); p.setClosestStop(blockConfig.getStopTimes().get(0)); p.setClosestStopTimeOffset(0); p.setDistanceAlongBlock(0); p.setLocation(new CoordinatePoint(stopA.getStopLat(), stopA.getStopLon())); p.setInService(true); Mockito.when( _blockLocationService.getScheduledBlockLocationFromScheduledTime( blockConfig, 1800)).thenReturn(p); location = _service.getLocationForBlockInstance(blockInstance, t(serviceDate, 0, 30)); assertTrue(location.isInService()); assertEquals(blockConfig.getStopTimes().get(0), location.getClosestStop()); assertEquals(0, location.getClosestStopTimeOffset()); assertEquals(stopA.getStopLocation(), location.getLocation()); assertFalse(location.isScheduleDeviationSet()); assertTrue(Double.isNaN(location.getScheduleDeviation())); assertFalse(location.isDistanceAlongBlockSet()); assertTrue(Double.isNaN(location.getDistanceAlongBlock())); assertEquals(blockInstance, location.getBlockInstance()); assertEquals(0, location.getLastUpdateTime()); assertEquals(blockConfig.getTrips().get(0), location.getActiveTrip()); assertNull(location.getVehicleId()); assertEquals(47.5, location.getLocation().getLat(), epsilon); assertEquals(-122.5, location.getLocation().getLon(), epsilon); assertEquals(blockConfig.getStopTimes().get(0), location.getClosestStop()); assertEquals(0, location.getClosestStopTimeOffset()); } private long t(long serviceDate, int hours, double minutes) { return (long) (serviceDate + (((hours * 60) + minutes) * 60) * 1000); } }
true
true
public void testWithShapeInfo() { StopEntryImpl stopA = stop("a", 47.5, -122.5); StopEntryImpl stopB = stop("b", 47.6, -122.4); StopEntryImpl stopC = stop("c", 47.5, -122.3); BlockEntryImpl block = block("block"); TripEntryImpl tripA = trip("tripA", "serviceId"); TripEntryImpl tripB = trip("tripB", "serviceId"); stopTime(0, stopA, tripA, 30, 90, 0); stopTime(1, stopB, tripA, 120, 120, 100); stopTime(2, stopC, tripA, 180, 210, 200); stopTime(3, stopC, tripB, 240, 240, 300); stopTime(4, stopB, tripB, 270, 270, 400); stopTime(5, stopA, tripB, 300, 300, 500); BlockConfigurationEntry blockConfig = linkBlockTrips(block, tripA, tripB); long serviceDate = 1000 * 1000; double epsilon = 0.001; BlockInstance blockInstance = new BlockInstance(blockConfig, serviceDate); BlockLocation location = _service.getLocationForBlockInstance( blockInstance, t(serviceDate, 0, 0)); assertFalse(location.isInService()); assertNull(location.getClosestStop()); assertEquals(0, location.getClosestStopTimeOffset()); assertFalse(location.isScheduleDeviationSet()); assertTrue(Double.isNaN(location.getScheduleDeviation())); assertFalse(location.isDistanceAlongBlockSet()); assertTrue(Double.isNaN(location.getDistanceAlongBlock())); assertNull(location.getLocation()); assertEquals(blockInstance, location.getBlockInstance()); assertEquals(0, location.getLastUpdateTime()); assertNull(location.getActiveTrip()); assertNull(location.getVehicleId()); ScheduledBlockLocation p = new ScheduledBlockLocation(); p.setActiveTrip(blockConfig.getTrips().get(0)); p.setClosestStop(blockConfig.getStopTimes().get(0)); p.setClosestStopTimeOffset(0); p.setDistanceAlongBlock(0); p.setLocation(new CoordinatePoint(stopA.getStopLat(), stopA.getStopLon())); p.setInService(true); Mockito.when( _blockLocationService.getScheduledBlockLocationFromScheduledTime( blockConfig, 1800)).thenReturn(p); location = _service.getLocationForBlockInstance(blockInstance, t(serviceDate, 0, 30)); assertTrue(location.isInService()); assertEquals(blockConfig.getStopTimes().get(0), location.getClosestStop()); assertEquals(0, location.getClosestStopTimeOffset()); assertEquals(stopA.getStopLocation(), location.getLocation()); assertFalse(location.isScheduleDeviationSet()); assertTrue(Double.isNaN(location.getScheduleDeviation())); assertFalse(location.isDistanceAlongBlockSet()); assertTrue(Double.isNaN(location.getDistanceAlongBlock())); assertEquals(blockInstance, location.getBlockInstance()); assertEquals(0, location.getLastUpdateTime()); assertEquals(blockConfig.getTrips().get(0), location.getActiveTrip()); assertNull(location.getVehicleId()); assertEquals(47.5, location.getLocation().getLat(), epsilon); assertEquals(-122.5, location.getLocation().getLon(), epsilon); assertEquals(blockConfig.getStopTimes().get(0), location.getClosestStop()); assertEquals(0, location.getClosestStopTimeOffset()); }
public void testWithShapeInfo() { StopEntryImpl stopA = stop("a", 47.5, -122.5); StopEntryImpl stopB = stop("b", 47.6, -122.4); StopEntryImpl stopC = stop("c", 47.5, -122.3); BlockEntryImpl block = block("block"); TripEntryImpl tripA = trip("tripA", "serviceId"); TripEntryImpl tripB = trip("tripB", "serviceId"); stopTime(0, stopA, tripA, 30, 90, 0); stopTime(1, stopB, tripA, 120, 120, 100); stopTime(2, stopC, tripA, 180, 210, 200); stopTime(3, stopC, tripB, 240, 240, 300); stopTime(4, stopB, tripB, 270, 270, 400); stopTime(5, stopA, tripB, 300, 300, 500); BlockConfigurationEntry blockConfig = linkBlockTrips(block, tripA, tripB); long serviceDate = 1000 * 1000; double epsilon = 0.001; BlockInstance blockInstance = new BlockInstance(blockConfig, serviceDate); BlockLocation location = _service.getLocationForBlockInstance( blockInstance, t(serviceDate, 0, 0)); assertNull(location); ScheduledBlockLocation p = new ScheduledBlockLocation(); p.setActiveTrip(blockConfig.getTrips().get(0)); p.setClosestStop(blockConfig.getStopTimes().get(0)); p.setClosestStopTimeOffset(0); p.setDistanceAlongBlock(0); p.setLocation(new CoordinatePoint(stopA.getStopLat(), stopA.getStopLon())); p.setInService(true); Mockito.when( _blockLocationService.getScheduledBlockLocationFromScheduledTime( blockConfig, 1800)).thenReturn(p); location = _service.getLocationForBlockInstance(blockInstance, t(serviceDate, 0, 30)); assertTrue(location.isInService()); assertEquals(blockConfig.getStopTimes().get(0), location.getClosestStop()); assertEquals(0, location.getClosestStopTimeOffset()); assertEquals(stopA.getStopLocation(), location.getLocation()); assertFalse(location.isScheduleDeviationSet()); assertTrue(Double.isNaN(location.getScheduleDeviation())); assertFalse(location.isDistanceAlongBlockSet()); assertTrue(Double.isNaN(location.getDistanceAlongBlock())); assertEquals(blockInstance, location.getBlockInstance()); assertEquals(0, location.getLastUpdateTime()); assertEquals(blockConfig.getTrips().get(0), location.getActiveTrip()); assertNull(location.getVehicleId()); assertEquals(47.5, location.getLocation().getLat(), epsilon); assertEquals(-122.5, location.getLocation().getLon(), epsilon); assertEquals(blockConfig.getStopTimes().get(0), location.getClosestStop()); assertEquals(0, location.getClosestStopTimeOffset()); }
diff --git a/AlkitabYes2/src/yuku/alkitab/yes2/io/MemoryRandomOutputStream.java b/AlkitabYes2/src/yuku/alkitab/yes2/io/MemoryRandomOutputStream.java index b8d8a0e1..81681dd7 100644 --- a/AlkitabYes2/src/yuku/alkitab/yes2/io/MemoryRandomOutputStream.java +++ b/AlkitabYes2/src/yuku/alkitab/yes2/io/MemoryRandomOutputStream.java @@ -1,73 +1,73 @@ package yuku.alkitab.yes2.io; import java.io.IOException; public class MemoryRandomOutputStream extends RandomOutputStream { public static final String TAG = MemoryRandomOutputStream.class.getSimpleName(); private int length = 0; private int pos = 0; private byte[] buf = new byte[16]; void expandBufTo(int newLen) { if (buf.length < newLen) { byte[] buf2 = new byte[newLen]; System.arraycopy(buf, 0, buf2, 0, buf.length); this.buf = buf2; } } @Override public void write(int oneByte) throws IOException { - if (pos >= length) { + if (pos >= buf.length) { expandBufTo((int) (length * 1.5) + 1); } this.buf[this.pos++] = (byte) oneByte; if (pos >= length) { length = pos; } } @Override public void write(byte[] buffer, int byteOffset, int byteCount) throws IOException { for (int i = byteOffset, to = byteOffset + byteCount; i < to; i++) { write(buffer[i]); } } @Override public void write(byte[] buffer) throws IOException { write(buffer, 0, buffer.length); } @Override public long getFilePointer() throws IOException { return pos; } @Override public void seek(long offset) throws IOException { pos = (int) offset; } @Override public void close() throws IOException { return; } @Override protected void finalize() throws Throwable { return; } /** * This may return a buffer with length larger than the actual size of this "memory file". * Call {@link #getBufferLength()} to find out the actual length of the buffer data. */ public byte[] getBuffer() { return this.buf; } public int getBufferOffset() { return 0; } public int getBufferLength() { return length; } }
true
true
@Override public void write(int oneByte) throws IOException { if (pos >= length) { expandBufTo((int) (length * 1.5) + 1); } this.buf[this.pos++] = (byte) oneByte; if (pos >= length) { length = pos; } }
@Override public void write(int oneByte) throws IOException { if (pos >= buf.length) { expandBufTo((int) (length * 1.5) + 1); } this.buf[this.pos++] = (byte) oneByte; if (pos >= length) { length = pos; } }
diff --git a/genomix/genomix-pregelix/src/main/java/edu/uci/ics/genomix/pregelix/operator/removelowcoverage/ShiftLowCoverageReadSetVertex.java b/genomix/genomix-pregelix/src/main/java/edu/uci/ics/genomix/pregelix/operator/removelowcoverage/ShiftLowCoverageReadSetVertex.java index 2129f5351..68ce2b183 100644 --- a/genomix/genomix-pregelix/src/main/java/edu/uci/ics/genomix/pregelix/operator/removelowcoverage/ShiftLowCoverageReadSetVertex.java +++ b/genomix/genomix-pregelix/src/main/java/edu/uci/ics/genomix/pregelix/operator/removelowcoverage/ShiftLowCoverageReadSetVertex.java @@ -1,142 +1,145 @@ package edu.uci.ics.genomix.pregelix.operator.removelowcoverage; import java.util.Iterator; import edu.uci.ics.genomix.data.config.GenomixJobConf; import edu.uci.ics.genomix.data.types.Kmer; import edu.uci.ics.genomix.data.types.KmerFactory; import edu.uci.ics.genomix.data.types.ReadHeadInfo; import edu.uci.ics.genomix.data.types.ReadHeadSet; import edu.uci.ics.genomix.data.types.VKmer; import edu.uci.ics.genomix.pregelix.base.DeBruijnGraphCleanVertex; import edu.uci.ics.genomix.pregelix.base.VertexValueWritable; public class ShiftLowCoverageReadSetVertex extends DeBruijnGraphCleanVertex<VertexValueWritable, ShiftedReadSetMessage> { protected static float minAverageCoverage = -1; /** * initiate kmerSize, length */ @Override public void initVertex() { super.initVertex(); if (minAverageCoverage < 0) minAverageCoverage = Float.parseFloat(getContext().getConfiguration().get( GenomixJobConf.REMOVE_LOW_COVERAGE_MAX_COVERAGE)); if (outgoingMsg == null) outgoingMsg = new ShiftedReadSetMessage(); ReadHeadSet.forceWriteEntireBody(true); } private boolean isLowCoverageVertex() { VertexValueWritable vertex = getVertexValue(); return vertex.getAverageCoverage() <= minAverageCoverage; } private boolean hasReadSet() { VertexValueWritable vertex = getVertexValue(); return vertex.hasUnflippedOrFlippedReadIds(); } @Override public void compute(Iterator<ShiftedReadSetMessage> msgIterator) throws Exception { if (super.getSuperstep() > 1) { acceptNewReadSet(msgIterator); } if (isLowCoverageVertex() && hasReadSet()) { LOG.info("Here is one head: " + getVertexId()); shiftReadSetToNeighors(); clearupMyReadSet(); } super.voteToHalt(); } private void clearupMyReadSet() { getVertexValue().getUnflippedReadIds().reset(); getVertexValue().getFlippedReadIds().reset(); } private void shiftReadSetToNeighors() { ReadHeadSet unflippedSet = getVertexValue().getUnflippedReadIds(); KmerFactory kmerFactory = new KmerFactory(Kmer.getKmerLength()); for (ReadHeadInfo info : unflippedSet) { if (info.getOffset() > 0) { throw new IllegalStateException("the info's offset should be negative, now:" + info.getOffset()); } VKmer destForward = kmerFactory.getSubKmerFromChain(-info.getOffset() + 1, Kmer.getKmerLength(), info.getThisReadSequence()); if (destForward == null) { continue; } VKmer destReverse = destForward.reverse(); boolean flipped = destForward.compareTo(destReverse) > 0; if (flipped) { // --> if this is 0 // <-- then neighbor should be 3 // -----> info.resetOffset(-info.getOffset() + destReverse.getKmerLetterLength()); sendReadInfo(destReverse, flipped, info); } else { // --> if this is 0 // --> then neighbor should be -1 // ------> info.resetOffset(info.getOffset() - 1); sendReadInfo(destForward, flipped, info); } } ReadHeadSet flippedSet = getVertexValue().getFlippedReadIds(); for (ReadHeadInfo info : flippedSet) { if (info.getOffset() < Kmer.getKmerLength() - 1) { throw new IllegalStateException("the info's offset should be >= than the kmerlength-1, now:" + info.getOffset()); } // <-- // -----> VKmer destForward = kmerFactory.getSubKmerFromChain(info.getOffset() - (Kmer.getKmerLength() - 1) + 1, Kmer.getKmerLength(), info.getThisReadSequence()); + if (destForward == null) { + continue; + } VKmer destReverse = destForward.reverse(); boolean flipped = destForward.compareTo(destReverse) > 0; if (flipped) { // <-- if this is 2 // <-- then the next neighbor should be 3 // ------> info.resetOffset(info.getOffset() + 1); sendReadInfo(destReverse, flipped, info); } else { // <-- if this is 3 // --> then the next neighbor should be -2 // -------> info.resetOffset(-(info.getOffset() + 1 - Kmer.getKmerLength() + 1)); sendReadInfo(destForward, flipped, info); } } } private void sendReadInfo(VKmer dest, boolean flipped, ReadHeadInfo info) { outFlag = (short) (flipped ? 1 : 0); outgoingMsg.reset(); outgoingMsg.setFlag(outFlag); outgoingMsg.setSourceVertexId(getVertexId()); outgoingMsg.setReadInfo(info); sendMsg(dest, outgoingMsg); } private void acceptNewReadSet(Iterator<ShiftedReadSetMessage> msgIterator) { VertexValueWritable vertex = getVertexValue(); while (msgIterator.hasNext()) { ShiftedReadSetMessage msg = msgIterator.next(); if (msg.getFlag() > 0) { // flipped vertex.getFlippedReadIds().add(msg.getReadInfo()); } else { vertex.getUnflippedReadIds().add(msg.getReadInfo()); } } } }
true
true
private void shiftReadSetToNeighors() { ReadHeadSet unflippedSet = getVertexValue().getUnflippedReadIds(); KmerFactory kmerFactory = new KmerFactory(Kmer.getKmerLength()); for (ReadHeadInfo info : unflippedSet) { if (info.getOffset() > 0) { throw new IllegalStateException("the info's offset should be negative, now:" + info.getOffset()); } VKmer destForward = kmerFactory.getSubKmerFromChain(-info.getOffset() + 1, Kmer.getKmerLength(), info.getThisReadSequence()); if (destForward == null) { continue; } VKmer destReverse = destForward.reverse(); boolean flipped = destForward.compareTo(destReverse) > 0; if (flipped) { // --> if this is 0 // <-- then neighbor should be 3 // -----> info.resetOffset(-info.getOffset() + destReverse.getKmerLetterLength()); sendReadInfo(destReverse, flipped, info); } else { // --> if this is 0 // --> then neighbor should be -1 // ------> info.resetOffset(info.getOffset() - 1); sendReadInfo(destForward, flipped, info); } } ReadHeadSet flippedSet = getVertexValue().getFlippedReadIds(); for (ReadHeadInfo info : flippedSet) { if (info.getOffset() < Kmer.getKmerLength() - 1) { throw new IllegalStateException("the info's offset should be >= than the kmerlength-1, now:" + info.getOffset()); } // <-- // -----> VKmer destForward = kmerFactory.getSubKmerFromChain(info.getOffset() - (Kmer.getKmerLength() - 1) + 1, Kmer.getKmerLength(), info.getThisReadSequence()); VKmer destReverse = destForward.reverse(); boolean flipped = destForward.compareTo(destReverse) > 0; if (flipped) { // <-- if this is 2 // <-- then the next neighbor should be 3 // ------> info.resetOffset(info.getOffset() + 1); sendReadInfo(destReverse, flipped, info); } else { // <-- if this is 3 // --> then the next neighbor should be -2 // -------> info.resetOffset(-(info.getOffset() + 1 - Kmer.getKmerLength() + 1)); sendReadInfo(destForward, flipped, info); } } }
private void shiftReadSetToNeighors() { ReadHeadSet unflippedSet = getVertexValue().getUnflippedReadIds(); KmerFactory kmerFactory = new KmerFactory(Kmer.getKmerLength()); for (ReadHeadInfo info : unflippedSet) { if (info.getOffset() > 0) { throw new IllegalStateException("the info's offset should be negative, now:" + info.getOffset()); } VKmer destForward = kmerFactory.getSubKmerFromChain(-info.getOffset() + 1, Kmer.getKmerLength(), info.getThisReadSequence()); if (destForward == null) { continue; } VKmer destReverse = destForward.reverse(); boolean flipped = destForward.compareTo(destReverse) > 0; if (flipped) { // --> if this is 0 // <-- then neighbor should be 3 // -----> info.resetOffset(-info.getOffset() + destReverse.getKmerLetterLength()); sendReadInfo(destReverse, flipped, info); } else { // --> if this is 0 // --> then neighbor should be -1 // ------> info.resetOffset(info.getOffset() - 1); sendReadInfo(destForward, flipped, info); } } ReadHeadSet flippedSet = getVertexValue().getFlippedReadIds(); for (ReadHeadInfo info : flippedSet) { if (info.getOffset() < Kmer.getKmerLength() - 1) { throw new IllegalStateException("the info's offset should be >= than the kmerlength-1, now:" + info.getOffset()); } // <-- // -----> VKmer destForward = kmerFactory.getSubKmerFromChain(info.getOffset() - (Kmer.getKmerLength() - 1) + 1, Kmer.getKmerLength(), info.getThisReadSequence()); if (destForward == null) { continue; } VKmer destReverse = destForward.reverse(); boolean flipped = destForward.compareTo(destReverse) > 0; if (flipped) { // <-- if this is 2 // <-- then the next neighbor should be 3 // ------> info.resetOffset(info.getOffset() + 1); sendReadInfo(destReverse, flipped, info); } else { // <-- if this is 3 // --> then the next neighbor should be -2 // -------> info.resetOffset(-(info.getOffset() + 1 - Kmer.getKmerLength() + 1)); sendReadInfo(destForward, flipped, info); } } }
diff --git a/gearman-common/src/main/java/org/gearman/common/packets/request/SubmitJob.java b/gearman-common/src/main/java/org/gearman/common/packets/request/SubmitJob.java index 27915b3..9079fcf 100644 --- a/gearman-common/src/main/java/org/gearman/common/packets/request/SubmitJob.java +++ b/gearman-common/src/main/java/org/gearman/common/packets/request/SubmitJob.java @@ -1,155 +1,155 @@ package org.gearman.common.packets.request; import org.gearman.constants.JobPriority; import org.gearman.constants.PacketType; import java.util.Arrays; import java.util.Date; import java.util.concurrent.atomic.AtomicReference; /** * Created with IntelliJ IDEA. * User: jewart * Date: 11/30/12 * Time: 9:37 AM * To change this template use File | Settings | File Templates. */ public class SubmitJob extends RequestPacket { private AtomicReference<String> taskName, uniqueId, epochString; private byte[] data; private boolean background; private int size; public SubmitJob() { } public SubmitJob(byte[] pktdata) { super(pktdata); taskName = new AtomicReference<String>(); uniqueId = new AtomicReference<String>(); epochString = new AtomicReference<String>(); int pOff = 0; pOff = parseString(pOff, taskName); pOff = parseString(pOff, uniqueId); if (this.type == PacketType.SUBMIT_JOB_EPOCH) { pOff = parseString(pOff, epochString); } if (this.type == PacketType.SUBMIT_JOB_HIGH_BG || this.type == PacketType.SUBMIT_JOB_LOW_BG || this.type == PacketType.SUBMIT_JOB_BG || this.type == PacketType.SUBMIT_JOB_EPOCH) { this.background = true; } - data = Arrays.copyOfRange(pktdata, pOff, pktdata.length); + data = Arrays.copyOfRange(rawdata, pOff, rawdata.length); } public SubmitJob(String function, String unique_id, byte[] data, boolean background) { this.taskName = new AtomicReference<String>(function); this.uniqueId = new AtomicReference<String>(unique_id); this.data = data.clone(); if(background) { this.type = PacketType.SUBMIT_JOB_BG; } else { this.type = PacketType.SUBMIT_JOB; } this.size = function.length() + 1 + unique_id.length() + 1 + data.length; } public SubmitJob(String function, String unique_id, byte[] data, boolean background, JobPriority priority) { this(function, unique_id, data, background); switch (priority) { case HIGH: this.type = background ? PacketType.SUBMIT_JOB_HIGH_BG : PacketType.SUBMIT_JOB_HIGH; break; case NORMAL: this.type = background ? PacketType.SUBMIT_JOB_BG : PacketType.SUBMIT_JOB; break; case LOW: this.type = background ? PacketType.SUBMIT_JOB_LOW_BG : PacketType.SUBMIT_JOB_LOW; break; default: break; } } public Date getWhen() { return new Date(Long.parseLong(epochString.get())); } public JobPriority getPriority() { switch(this.type) { case SUBMIT_JOB: case SUBMIT_JOB_BG: case SUBMIT_JOB_EPOCH: case SUBMIT_JOB_SCHED: return JobPriority.NORMAL; case SUBMIT_JOB_HIGH: case SUBMIT_JOB_HIGH_BG: return JobPriority.HIGH; case SUBMIT_JOB_LOW: case SUBMIT_JOB_LOW_BG: return JobPriority.LOW; } return null; } public String getFunctionName() { return this.taskName.get(); } public String getUniqueId() { return uniqueId.get(); } public boolean isBackground() { return background; } public byte[] getData() { return data; } public long getEpoch() { return Long.parseLong(epochString.get()); } @Override public byte[] toByteArray() { byte[] metadata = stringsToTerminatedByteArray(taskName.get(), uniqueId.get()); byte[] result = concatByteArrays(getHeader(), metadata, data); return result; } @Override public int getPayloadSize() { return size; } }
true
true
public SubmitJob(byte[] pktdata) { super(pktdata); taskName = new AtomicReference<String>(); uniqueId = new AtomicReference<String>(); epochString = new AtomicReference<String>(); int pOff = 0; pOff = parseString(pOff, taskName); pOff = parseString(pOff, uniqueId); if (this.type == PacketType.SUBMIT_JOB_EPOCH) { pOff = parseString(pOff, epochString); } if (this.type == PacketType.SUBMIT_JOB_HIGH_BG || this.type == PacketType.SUBMIT_JOB_LOW_BG || this.type == PacketType.SUBMIT_JOB_BG || this.type == PacketType.SUBMIT_JOB_EPOCH) { this.background = true; } data = Arrays.copyOfRange(pktdata, pOff, pktdata.length); }
public SubmitJob(byte[] pktdata) { super(pktdata); taskName = new AtomicReference<String>(); uniqueId = new AtomicReference<String>(); epochString = new AtomicReference<String>(); int pOff = 0; pOff = parseString(pOff, taskName); pOff = parseString(pOff, uniqueId); if (this.type == PacketType.SUBMIT_JOB_EPOCH) { pOff = parseString(pOff, epochString); } if (this.type == PacketType.SUBMIT_JOB_HIGH_BG || this.type == PacketType.SUBMIT_JOB_LOW_BG || this.type == PacketType.SUBMIT_JOB_BG || this.type == PacketType.SUBMIT_JOB_EPOCH) { this.background = true; } data = Arrays.copyOfRange(rawdata, pOff, rawdata.length); }
diff --git a/src/com/android/exchange/PartRequest.java b/src/com/android/exchange/PartRequest.java index 2cc322d..23b4add 100644 --- a/src/com/android/exchange/PartRequest.java +++ b/src/com/android/exchange/PartRequest.java @@ -1,51 +1,51 @@ /* * Copyright (C) 2008-2009 Marc Blank * Licensed to 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.exchange; import com.android.emailcommon.provider.EmailContent.Attachment; /** * PartRequest is the EAS wrapper for attachment loading requests. In addition to information about * the attachment to be loaded, it also contains the callback to be used for status/progress * updates to the UI. */ public class PartRequest extends Request { public final Attachment mAttachment; public final String mDestination; public final String mContentUriString; public final String mLocation; public PartRequest(Attachment _att, String _destination, String _contentUriString) { - super(_att.mId); + super(_att.mMessageKey); mAttachment = _att; mLocation = mAttachment.mLocation; mDestination = _destination; mContentUriString = _contentUriString; } // PartRequests are unique by their attachment id (i.e. multiple attachments might be queued // for a particular message, but any individual attachment can only be loaded once) public boolean equals(Object o) { if (!(o instanceof PartRequest)) return false; return ((PartRequest)o).mAttachment.mId == mAttachment.mId; } public int hashCode() { return (int)mAttachment.mId; } }
true
true
public PartRequest(Attachment _att, String _destination, String _contentUriString) { super(_att.mId); mAttachment = _att; mLocation = mAttachment.mLocation; mDestination = _destination; mContentUriString = _contentUriString; }
public PartRequest(Attachment _att, String _destination, String _contentUriString) { super(_att.mMessageKey); mAttachment = _att; mLocation = mAttachment.mLocation; mDestination = _destination; mContentUriString = _contentUriString; }
diff --git a/corelib-solr/src/main/java/eu/europeana/corelib/solr/server/importer/util/AgentFieldInput.java b/corelib-solr/src/main/java/eu/europeana/corelib/solr/server/importer/util/AgentFieldInput.java index 26978750..861dc26d 100644 --- a/corelib-solr/src/main/java/eu/europeana/corelib/solr/server/importer/util/AgentFieldInput.java +++ b/corelib-solr/src/main/java/eu/europeana/corelib/solr/server/importer/util/AgentFieldInput.java @@ -1,423 +1,423 @@ /* * Copyright 2007-2012 The Europeana Foundation * * Licenced under the EUPL, Version 1.1 (the "Licence") and subsequent versions as approved * by the European Commission; * You may not use this work except in compliance with the Licence. * * You may obtain a copy of the Licence at: * http://joinup.ec.europa.eu/software/page/eupl * * Unless required by applicable law or agreed to in writing, software distributed under * the Licence is distributed on an "AS IS" basis, without warranties or conditions of * any kind, either express or implied. * See the Licence for the specific language governing permissions and limitations under * the Licence. */ package eu.europeana.corelib.solr.server.importer.util; import java.io.IOException; import java.net.MalformedURLException; import org.apache.solr.common.SolrInputDocument; import com.google.code.morphia.mapping.MappingException; import eu.europeana.corelib.definitions.jibx.AgentType; import eu.europeana.corelib.definitions.jibx.AltLabel; import eu.europeana.corelib.definitions.jibx.Date; import eu.europeana.corelib.definitions.jibx.HasMet; import eu.europeana.corelib.definitions.jibx.Identifier; import eu.europeana.corelib.definitions.jibx.IsRelatedTo; import eu.europeana.corelib.definitions.jibx.Note; import eu.europeana.corelib.definitions.jibx.PrefLabel; import eu.europeana.corelib.definitions.model.EdmLabel; import eu.europeana.corelib.solr.MongoServer; import eu.europeana.corelib.solr.entity.AgentImpl; import eu.europeana.corelib.solr.server.EdmMongoServer; import eu.europeana.corelib.solr.utils.MongoUtils; import eu.europeana.corelib.solr.utils.SolrUtils; /** * Constructor of Agent Fields. * * @author Yorgos.Mamakis@ kb.nl * */ public final class AgentFieldInput { public AgentFieldInput() { } /** * Fill in a SolrInputDocument with Agent specific fields * * @param agentType * A JiBX entity that represents an Agent * @param solrInputDocument * The SolrInputDocument to alter * @return The SolrInputDocument with Agent specific values */ public SolrInputDocument createAgentSolrFields(AgentType agentType, SolrInputDocument solrInputDocument) { solrInputDocument.addField(EdmLabel.EDM_AGENT.toString(), agentType.getAbout()); if (agentType.getAltLabelList() != null) { for (AltLabel altLabel : agentType.getAltLabelList()) { solrInputDocument = SolrUtils .addFieldFromLiteral(solrInputDocument, altLabel, EdmLabel.AG_SKOS_ALT_LABEL); } } if (agentType.getPrefLabelList() != null) { for (PrefLabel prefLabel : agentType.getPrefLabelList()) { solrInputDocument = SolrUtils.addFieldFromLiteral( solrInputDocument, prefLabel, EdmLabel.AG_SKOS_PREF_LABEL); } } if (agentType.getNoteList() != null) { for (Note note : agentType.getNoteList()) { solrInputDocument = SolrUtils.addFieldFromLiteral( solrInputDocument, note, EdmLabel.AG_SKOS_NOTE); } } if (agentType.getBegin() != null) { solrInputDocument = SolrUtils.addFieldFromLiteral( solrInputDocument, agentType.getBegin(), EdmLabel.AG_EDM_BEGIN); } if (agentType.getEnd() != null) { solrInputDocument = SolrUtils.addFieldFromLiteral( solrInputDocument, agentType.getEnd(), EdmLabel.AG_EDM_END); } if (agentType.getDateList() != null) { for (Date date : agentType.getDateList()) { solrInputDocument = SolrUtils.addFieldFromResourceOrLiteral( solrInputDocument, date, EdmLabel.AG_DC_DATE); } } if (agentType.getIdentifierList() != null) { for (Identifier identifier : agentType.getIdentifierList()) { if (identifier.getString() != null) { solrInputDocument = SolrUtils.addFieldFromLiteral( solrInputDocument, identifier, EdmLabel.AG_DC_IDENTIFIER); } } } if (agentType.getHasMetList() != null) { for (HasMet hasMet : agentType.getHasMetList()) { solrInputDocument = SolrUtils.addFieldFromLiteral( solrInputDocument, hasMet, EdmLabel.AG_EDM_HASMET); } } if (agentType.getIsRelatedToList() != null) { for (IsRelatedTo isRelatedTo : agentType.getIsRelatedToList()) { solrInputDocument = SolrUtils.addFieldFromResourceOrLiteral( solrInputDocument, isRelatedTo, EdmLabel.AG_EDM_ISRELATEDTO); } } if (agentType.getBiographicalInformation() != null) { solrInputDocument = SolrUtils.addFieldFromLiteral( solrInputDocument, agentType.getBiographicalInformation(), EdmLabel.AG_RDAGR2_BIOGRAPHICALINFORMATION); } if (agentType.getDateOfBirth() != null) { solrInputDocument = SolrUtils.addFieldFromLiteral( solrInputDocument, agentType.getDateOfBirth(), EdmLabel.AG_RDAGR2_DATEOFBIRTH); } if (agentType.getDateOfDeath() != null) { solrInputDocument = SolrUtils.addFieldFromLiteral( solrInputDocument, agentType.getDateOfDeath(), EdmLabel.AG_RDAGR2_DATEOFDEATH); } if (agentType.getDateOfEstablishment() != null) { solrInputDocument = SolrUtils.addFieldFromLiteral( solrInputDocument, agentType.getDateOfEstablishment(), EdmLabel.AG_RDAGR2_DATEOFESTABLISHMENT); } if (agentType.getDateOfTermination() != null) { solrInputDocument = SolrUtils.addFieldFromLiteral( solrInputDocument, agentType.getDateOfTermination(), EdmLabel.AG_RDAGR2_DATEOFTERMINATION); } if (agentType.getGender() != null) { solrInputDocument = SolrUtils.addFieldFromLiteral( solrInputDocument, agentType.getGender(), EdmLabel.AG_RDAGR2_GENDER); } if (agentType.getProfessionOrOccupation() != null) { solrInputDocument = SolrUtils.addFieldFromResourceOrLiteral( solrInputDocument, agentType.getProfessionOrOccupation(), EdmLabel.AG_RDAGR2_PROFESSIONOROCCUPATION); } return solrInputDocument; } /** * Create or Update a Mongo Entity of type Agent from the JiBX AgentType * object * * Mapping from the JibXBinding Fields to the MongoDB Entity Fields The * fields mapped are the rdf:about (String -> String) skos:note(List<Note> * -> String[]) skos:prefLabel(List<PrefLabel> -> * HashMap<String,String>(lang,description)) skos:altLabel(List<AltLabel> -> * HashMap<String,String>(lang,description)) edm:begin (String -> Date) * edm:end (String -> Date) * * @param agentType * - JiBX representation of an Agent EDM entity * @param mongoServer * - The mongoServer to save the entity * @return The created Agent * @throws IOException * @throws MalformedURLException * @throws IllegalAccessException * @throws InstantiationException * @throws MappingException */ public AgentImpl createAgentMongoEntity(AgentType agentType, MongoServer mongoServer) throws MalformedURLException, IOException { AgentImpl agent = ((EdmMongoServer) mongoServer).getDatastore() .find(AgentImpl.class) .filter("about", agentType.getAbout()).get(); // if it does not exist if (agent == null) { agent = createNewAgent(agentType); try { mongoServer.getDatastore().save(agent); } catch (Exception e ){ AgentImpl agentSec = ((EdmMongoServer) mongoServer).getDatastore() .find(AgentImpl.class) .filter("about", agentType.getAbout()).get(); agent = updateMongoAgent(agentSec, agentType, mongoServer); } } else { agent = updateMongoAgent(agent, agentType, mongoServer); } return agent; } /** * Update an already stored Agent Mongo Entity * * @param agent * The agent to update * @param agentType * The JiBX Agent Entity * @param mongoServer * The MongoDB Server to save the Agent to * @return The new Agent MongoDB Entity * @throws IllegalAccessException * @throws InstantiationException */ private AgentImpl updateMongoAgent(AgentImpl agent, AgentType agentType, MongoServer mongoServer) { if (agentType.getBegin() != null) { MongoUtils .update(AgentImpl.class, agent.getAbout(), mongoServer, "begin", MongoUtils .createLiteralMapFromString(agentType .getBegin())); } if (agentType.getDateList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "dcDate", MongoUtils .createResourceOrLiteralMapFromList(agentType .getDateList())); } if (agentType.getIdentifierList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "dcIdentifier", MongoUtils .createLiteralMapFromList(agentType .getIdentifierList())); } if (agentType.getBiographicalInformation() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, - "biographicalInformation", MongoUtils + "rdaGr2BiographicalInformation", MongoUtils .createLiteralMapFromString(agentType .getBiographicalInformation())); } if (agentType.getDateOfBirth() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, - "dateOfBirth", MongoUtils + "rdaGr2DateOfBirth", MongoUtils .createLiteralMapFromString(agentType .getDateOfBirth())); } if (agentType.getDateOfDeath() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, - "dateOfDeath", MongoUtils + "rdaGr2DateOfDeath", MongoUtils .createLiteralMapFromString(agentType .getDateOfDeath())); } if (agentType.getDateOfEstablishment() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, - "dateOfEstablishment", MongoUtils + "rdaGr2DateOfEstablishment", MongoUtils .createLiteralMapFromString(agentType .getDateOfEstablishment())); } if (agentType.getDateOfTermination() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, - "dateOfTermination", MongoUtils + "rdaGr2DateOfTermination", MongoUtils .createLiteralMapFromString(agentType .getDateOfTermination())); } if (agentType.getGender() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, - "gender", MongoUtils.createLiteralMapFromString(agentType + "rdaGr2Gender", MongoUtils.createLiteralMapFromString(agentType .getGender())); } if (agentType.getHasMetList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, - "hasMet", MongoUtils.createLiteralMapFromList(agentType + "edmHasMet", MongoUtils.createLiteralMapFromList(agentType .getHasMetList())); } if (agentType.getIsRelatedToList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, - "isRelatedTo", MongoUtils + "edmIsRelatedTo", MongoUtils .createResourceOrLiteralMapFromList(agentType .getIsRelatedToList())); } if (agentType.getNameList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, - "name", MongoUtils.createLiteralMapFromList(agentType + "foafName", MongoUtils.createLiteralMapFromList(agentType .getNameList())); } if (agentType.getSameAList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, - "sameAs", + "owlSameAs", SolrUtils.resourceListToArray(agentType.getSameAList())); } if (agentType.getProfessionOrOccupation() != null) { if (agentType.getHasMetList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), - mongoServer, "professionOrOccupation", MongoUtils + mongoServer, "rdaGr2ProfessionOrOccupation", MongoUtils .createResourceOrLiteralMapFromString(agentType .getProfessionOrOccupation())); } } if (agentType.getEnd() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "end", MongoUtils.createLiteralMapFromString(agentType.getEnd())); } if (agentType.getNoteList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "note", MongoUtils.createLiteralMapFromList(agentType .getNoteList())); } if (agentType.getAltLabelList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "altLabel", MongoUtils.createLiteralMapFromList(agentType .getAltLabelList())); } if (agentType.getPrefLabelList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "prefLabel", MongoUtils.createLiteralMapFromList(agentType .getPrefLabelList())); } return ((EdmMongoServer) mongoServer).getDatastore() .find(AgentImpl.class) .filter("about", agentType.getAbout()).get(); } /** * Create new Agent MongoDB Entity from JiBX Agent Entity * * @param agentType * @return * @throws IOException * @throws MalformedURLException */ private AgentImpl createNewAgent(AgentType agentType) throws MalformedURLException, IOException { AgentImpl agent = new AgentImpl(); // agent.setId(new ObjectId()); agent.setAbout(agentType.getAbout()); agent.setDcDate(MongoUtils.createResourceOrLiteralMapFromList(agentType .getDateList())); agent.setDcIdentifier(MongoUtils.createLiteralMapFromList(agentType .getIdentifierList())); agent.setEdmHasMet(MongoUtils.createLiteralMapFromList(agentType .getHasMetList())); agent.setEdmIsRelatedTo(MongoUtils .createResourceOrLiteralMapFromList(agentType .getIsRelatedToList())); agent.setFoafName(MongoUtils.createLiteralMapFromList(agentType .getNameList())); agent.setRdaGr2BiographicalInformation(MongoUtils .createLiteralMapFromString(agentType .getBiographicalInformation())); agent.setRdaGr2DateOfBirth(MongoUtils .createLiteralMapFromString(agentType.getDateOfBirth())); agent.setRdaGr2DateOfDeath(MongoUtils .createLiteralMapFromString(agentType.getDateOfDeath())); agent.setRdaGr2DateOfEstablishment(MongoUtils .createLiteralMapFromString(agentType.getDateOfEstablishment())); agent.setRdaGr2DateOfTermination(MongoUtils .createLiteralMapFromString(agentType.getDateOfTermination())); agent.setRdaGr2Gender(MongoUtils.createLiteralMapFromString(agentType .getGender())); agent.setRdaGr2ProfessionOrOccupation(MongoUtils .createResourceOrLiteralMapFromString(agentType .getProfessionOrOccupation())); agent.setNote(MongoUtils.createLiteralMapFromList(agentType .getNoteList())); agent.setPrefLabel(MongoUtils.createLiteralMapFromList(agentType .getPrefLabelList())); agent.setAltLabel(MongoUtils.createLiteralMapFromList(agentType .getAltLabelList())); agent.setBegin(MongoUtils.createLiteralMapFromString(agentType .getBegin())); agent.setEnd(MongoUtils.createLiteralMapFromString(agentType.getEnd())); agent.setOwlSameAs(SolrUtils.resourceListToArray(agentType .getSameAList())); return agent; } }
false
true
private AgentImpl updateMongoAgent(AgentImpl agent, AgentType agentType, MongoServer mongoServer) { if (agentType.getBegin() != null) { MongoUtils .update(AgentImpl.class, agent.getAbout(), mongoServer, "begin", MongoUtils .createLiteralMapFromString(agentType .getBegin())); } if (agentType.getDateList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "dcDate", MongoUtils .createResourceOrLiteralMapFromList(agentType .getDateList())); } if (agentType.getIdentifierList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "dcIdentifier", MongoUtils .createLiteralMapFromList(agentType .getIdentifierList())); } if (agentType.getBiographicalInformation() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "biographicalInformation", MongoUtils .createLiteralMapFromString(agentType .getBiographicalInformation())); } if (agentType.getDateOfBirth() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "dateOfBirth", MongoUtils .createLiteralMapFromString(agentType .getDateOfBirth())); } if (agentType.getDateOfDeath() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "dateOfDeath", MongoUtils .createLiteralMapFromString(agentType .getDateOfDeath())); } if (agentType.getDateOfEstablishment() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "dateOfEstablishment", MongoUtils .createLiteralMapFromString(agentType .getDateOfEstablishment())); } if (agentType.getDateOfTermination() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "dateOfTermination", MongoUtils .createLiteralMapFromString(agentType .getDateOfTermination())); } if (agentType.getGender() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "gender", MongoUtils.createLiteralMapFromString(agentType .getGender())); } if (agentType.getHasMetList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "hasMet", MongoUtils.createLiteralMapFromList(agentType .getHasMetList())); } if (agentType.getIsRelatedToList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "isRelatedTo", MongoUtils .createResourceOrLiteralMapFromList(agentType .getIsRelatedToList())); } if (agentType.getNameList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "name", MongoUtils.createLiteralMapFromList(agentType .getNameList())); } if (agentType.getSameAList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "sameAs", SolrUtils.resourceListToArray(agentType.getSameAList())); } if (agentType.getProfessionOrOccupation() != null) { if (agentType.getHasMetList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "professionOrOccupation", MongoUtils .createResourceOrLiteralMapFromString(agentType .getProfessionOrOccupation())); } } if (agentType.getEnd() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "end", MongoUtils.createLiteralMapFromString(agentType.getEnd())); } if (agentType.getNoteList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "note", MongoUtils.createLiteralMapFromList(agentType .getNoteList())); } if (agentType.getAltLabelList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "altLabel", MongoUtils.createLiteralMapFromList(agentType .getAltLabelList())); } if (agentType.getPrefLabelList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "prefLabel", MongoUtils.createLiteralMapFromList(agentType .getPrefLabelList())); } return ((EdmMongoServer) mongoServer).getDatastore() .find(AgentImpl.class) .filter("about", agentType.getAbout()).get(); }
private AgentImpl updateMongoAgent(AgentImpl agent, AgentType agentType, MongoServer mongoServer) { if (agentType.getBegin() != null) { MongoUtils .update(AgentImpl.class, agent.getAbout(), mongoServer, "begin", MongoUtils .createLiteralMapFromString(agentType .getBegin())); } if (agentType.getDateList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "dcDate", MongoUtils .createResourceOrLiteralMapFromList(agentType .getDateList())); } if (agentType.getIdentifierList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "dcIdentifier", MongoUtils .createLiteralMapFromList(agentType .getIdentifierList())); } if (agentType.getBiographicalInformation() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "rdaGr2BiographicalInformation", MongoUtils .createLiteralMapFromString(agentType .getBiographicalInformation())); } if (agentType.getDateOfBirth() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "rdaGr2DateOfBirth", MongoUtils .createLiteralMapFromString(agentType .getDateOfBirth())); } if (agentType.getDateOfDeath() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "rdaGr2DateOfDeath", MongoUtils .createLiteralMapFromString(agentType .getDateOfDeath())); } if (agentType.getDateOfEstablishment() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "rdaGr2DateOfEstablishment", MongoUtils .createLiteralMapFromString(agentType .getDateOfEstablishment())); } if (agentType.getDateOfTermination() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "rdaGr2DateOfTermination", MongoUtils .createLiteralMapFromString(agentType .getDateOfTermination())); } if (agentType.getGender() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "rdaGr2Gender", MongoUtils.createLiteralMapFromString(agentType .getGender())); } if (agentType.getHasMetList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "edmHasMet", MongoUtils.createLiteralMapFromList(agentType .getHasMetList())); } if (agentType.getIsRelatedToList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "edmIsRelatedTo", MongoUtils .createResourceOrLiteralMapFromList(agentType .getIsRelatedToList())); } if (agentType.getNameList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "foafName", MongoUtils.createLiteralMapFromList(agentType .getNameList())); } if (agentType.getSameAList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "owlSameAs", SolrUtils.resourceListToArray(agentType.getSameAList())); } if (agentType.getProfessionOrOccupation() != null) { if (agentType.getHasMetList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "rdaGr2ProfessionOrOccupation", MongoUtils .createResourceOrLiteralMapFromString(agentType .getProfessionOrOccupation())); } } if (agentType.getEnd() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "end", MongoUtils.createLiteralMapFromString(agentType.getEnd())); } if (agentType.getNoteList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "note", MongoUtils.createLiteralMapFromList(agentType .getNoteList())); } if (agentType.getAltLabelList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "altLabel", MongoUtils.createLiteralMapFromList(agentType .getAltLabelList())); } if (agentType.getPrefLabelList() != null) { MongoUtils.update(AgentImpl.class, agent.getAbout(), mongoServer, "prefLabel", MongoUtils.createLiteralMapFromList(agentType .getPrefLabelList())); } return ((EdmMongoServer) mongoServer).getDatastore() .find(AgentImpl.class) .filter("about", agentType.getAbout()).get(); }
diff --git a/wro4j/src/test/java/org/fao/geonet/wro4j/GeonetWroModelFactoryTest.java b/wro4j/src/test/java/org/fao/geonet/wro4j/GeonetWroModelFactoryTest.java index d0f461823c..46b08937ec 100644 --- a/wro4j/src/test/java/org/fao/geonet/wro4j/GeonetWroModelFactoryTest.java +++ b/wro4j/src/test/java/org/fao/geonet/wro4j/GeonetWroModelFactoryTest.java @@ -1,387 +1,390 @@ package org.fao.geonet.wro4j; import com.google.common.base.Optional; import com.google.common.collect.Sets; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import ro.isdc.wro.config.ReadOnlyContext; import ro.isdc.wro.model.WroModel; import ro.isdc.wro.model.group.Group; import ro.isdc.wro.model.resource.Resource; import ro.isdc.wro.model.resource.locator.UriLocator; import ro.isdc.wro.model.resource.locator.factory.UriLocatorFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.*; import static org.fao.geonet.wro4j.ClosureDependencyUriLocator.PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE; import static org.fao.geonet.wro4j.GeonetWroModelFactory.*; import static org.junit.Assert.*; /** * Test GeonetWroModelFactory. * <p/> * User: Jesse * Date: 11/22/13 * Time: 1:03 PM */ public class GeonetWroModelFactoryTest { private static final String PATH_TO_ROOT_OF_TEST_RESOURCES = "wro4j/src/test/resources/org/fao/geonet/wro4j"; @Test public void testCreateUsingRequire() throws Exception { String sourcesXml = "<sources><" + REQUIRE_EL + "><" + JS_SOURCE_EL + " " + WEBAPP_ATT + "=\"\" " + PATH_ON_DISK_ATT + "=\"" + PATH_TO_ROOT_OF_TEST_RESOURCES + "\"/>" + "<" + CSS_SOURCE_EL + " " + WEBAPP_ATT + "=\"\" " + PATH_ON_DISK_ATT + "=\"" + PATH_TO_ROOT_OF_TEST_RESOURCES + "\"/>" + "</" + REQUIRE_EL + "></sources>"; final WroModel wroModel = createRequireModel(sourcesXml); assertRequireModel(wroModel, false); } @Test public void testCreateUsingRequireAndGroupHasPathOnDisk() throws Exception { String sourcesXml = createSourcesXmlWithPathOnGroup(); final WroModel wroModel = createRequireModel(sourcesXml); assertRequireModel(wroModel); } @Test public void testPathOnDiskIsFullPath() throws Exception { String sourcesXml = createSourcesXmlWithPathOnGroup(ClosureRequireDependencyManagerTest.getJsTestBaseDir().getAbsolutePath()); final WroModel wroModel = createRequireModel(sourcesXml); assertRequireModel(wroModel); } @Test public void testClosureJsGroup() throws Exception { final String jsTestBaseDir = ClosureRequireDependencyManagerTest.getJsTestBaseDir().getAbsolutePath(); String sourcesXml = createSourcesXmlWithPathOnGroup(jsTestBaseDir); final WroModel wroModel = createRequireModel(sourcesXml); final Collection<Group> groups = wroModel.getGroups(); Group depsGroup = null; for (Group group : groups) { if (group.getName().equals(GeonetWroModelFactory.GROUP_NAME_CLOSURE_DEPS)) { assertNull("There should only be one deps group but found at least 2", depsGroup); depsGroup = group; } } assertNotNull(depsGroup); final List<Resource> resources = depsGroup.getResources(); String jsTestBaseDirAsPath = jsTestBaseDir.replace('\\', '/'); + if (jsTestBaseDirAsPath.charAt(0) == '/') { + jsTestBaseDirAsPath = jsTestBaseDirAsPath.substring(1); + } assertEquals(7, resources.size()); for (Resource resource : resources) { final UriLocatorFactory uriLocatorFactory = new GeonetworkMavenWrojManagerFactory().newUriLocatorFactory(); final UriLocator instance = uriLocatorFactory.getInstance(resource.getUri()); final String deps = IOUtils.toString(instance.locate(resource.getUri()), "UTF-8"); if (resource.getUri().contains("sampleFile1a.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/sampleFile1a.js', ['1a'], ['2a']);\n", deps); } else if (resource.getUri().contains("sampleFile1b.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/sampleFile1b.js', ['1b'], ['3c','1a','2a']);\n", deps); } else if (resource.getUri().contains("sampleFile2a.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/jslvl2/sampleFile2a.js', ['2a'], ['3a','2b'," + "'3c','3b']);\n", deps); } else if (resource.getUri().contains("sampleFile2b.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/jslvl2/sampleFile2b.js', ['2b'], []);\n", deps); } else if (resource.getUri().contains("sampleFile3a.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/jslvl2/jslvl3/sampleFile3a.js', ['3a'], []);\n", deps); } else if (resource.getUri().contains("sampleFile3b.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/jslvl2/jslvl3/sampleFile3b.js', ['3b'], []);\n", deps); } else if (resource.getUri().contains("sampleFile3c.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/jslvl2/jslvl3/sampleFile3c.js', ['3c'], []);\n", deps); } } } @Test public void testRelativePathInclude() throws Exception { String includeSourcesXML = createSourcesXmlWithPathOnGroup(); final String prefix = "wro-includes"; final File wroInclude = File.createTempFile(prefix, ".xml"); FileUtils.write(wroInclude, includeSourcesXML); String mainSourcesXml = "<sources><" + INCLUDE_EL + " file=\"" + wroInclude.getName() + "\"/></sources>"; File mainSourcesFile = File.createTempFile("wro-sources", ".xml", wroInclude.getParentFile()); final WroModel wroModel = createRequireModel(mainSourcesXml, Optional.of(mainSourcesFile)); assertRequireModel(wroModel); } @Test public void testAbsolutePathInclude() throws Exception { String includeSourcesXML = createSourcesXmlWithPathOnGroup(); final String prefix = "wro-includes"; final File wroInclude = File.createTempFile(prefix, ".xml"); FileUtils.write(wroInclude, includeSourcesXML); String mainSourcesXml = "<sources><" + INCLUDE_EL + " file=\"" + wroInclude.getAbsolutePath() + "\"/></sources>"; final WroModel wroModel = createRequireModel(mainSourcesXml); assertRequireModel(wroModel); } @Test public void testURIPathInclude() throws Exception { String includeSourcesXML = createSourcesXmlWithPathOnGroup(); final String prefix = "wro-includes"; final File wroInclude = File.createTempFile(prefix, ".xml"); FileUtils.write(wroInclude, includeSourcesXML); String mainSourcesXml = "<sources><" + INCLUDE_EL + " file=\"" + wroInclude.getAbsoluteFile().toURI() + "\"/></sources>"; final WroModel wroModel = createRequireModel(mainSourcesXml); assertRequireModel(wroModel); } @Test public void testClasspathPathInclude() throws Exception { String mainSourcesXml = "<sources><" + INCLUDE_EL + " file=\"" + CLASSPATH_PREFIX + "included-wro-sources.xml\"/></sources>"; final WroModel wroModel = createRequireModel(mainSourcesXml); assertRequireModel(wroModel); } @Test public void testCreateDeclaredGroups() throws IOException { String sourcesXml = "<sources>\n" + " <declarative name=\"groupName\" pathOnDisk=\"wro4j/src/test/resources/org/fao/geonet/wro4j\">\n" + " <jsSource webappPath=\"sampleFile1a.js\" pathOnDisk=\"" + PATH_TO_ROOT_OF_TEST_RESOURCES + "\"/>\n" + " <jsSource webappPath=\"jslvl2/sampleFile2a.js\" minimize=\"false\"/>\n" + " <cssSource webappPath=\"1a.css\" minimize=\"false\"/>\n" + " <cssSource webappPath=\"anotherCss.less\" pathOnDisk=\"" + PATH_TO_ROOT_OF_TEST_RESOURCES + "\"/>\n" + " </declarative>\n" + "</sources>"; final WroModel wroModel = createRequireModel(sourcesXml); assertEquals(1, wroModel.getGroups().size()); final Group group = wroModel.getGroups().iterator().next(); assertEquals("groupName", group.getName()); List<Resource> resources = group.getResources(); assertEquals(4, resources.size()); List<String> resourceNames = new ArrayList<String>(resources.size()); final UriLocatorFactory uriLocatorFactory = new GeonetworkMavenWrojManagerFactory().newUriLocatorFactory(); for (Resource resource : resources) { resourceNames.add(resource.getUri()); assertCanLoadResource(uriLocatorFactory, resource); resourceNames.add(resource.getUri().split(PATH_TO_ROOT_OF_TEST_RESOURCES)[1]); if (resource.getUri().endsWith("jslvl2/sampleFile2a.js") || resource.getUri().endsWith("1a.css")) { assertFalse(resource.isMinimize()); } else { assertTrue(resource.isMinimize()); } } assertTrue(resourceNames.contains(("/sampleFile1a.js").replace('\\', '/'))); assertTrue(resourceNames.contains(("/jslvl2/sampleFile2a.js").replace('\\', '/'))); assertTrue(resourceNames.contains(("/1a.css").replace('\\', '/'))); assertTrue(resourceNames.contains(("/anotherCss.less").replace('\\', '/'))); } private WroModel createRequireModel(String sourcesXml) throws IOException { return createRequireModel(sourcesXml, Optional.<File>absent()); } private WroModel createRequireModel(String sourcesXml, Optional<File> sourcesFileOption) throws IOException { final File wroSources; if (sourcesFileOption.isPresent()) { wroSources = sourcesFileOption.get(); } else { wroSources = File.createTempFile("wro-sources", ".xml"); } FileUtils.write(wroSources, sourcesXml); final File configFile = File.createTempFile("wro", ".properties"); FileUtils.write(configFile, "wroSources=" + wroSources.getAbsolutePath().replace(File.separatorChar, '/')); final GeonetworkMavenWrojManagerFactory managerFactory = new GeonetworkMavenWrojManagerFactory(); managerFactory.setExtraConfigFile(configFile); final GeonetWroModelFactory wroModelFactory = (GeonetWroModelFactory) managerFactory.newModelFactory(); final ReadOnlyContext context = (ReadOnlyContext) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{ReadOnlyContext.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return null; } }); wroModelFactory.setContext(context); wroModelFactory.setGeonetworkRootDirectory(getGeonetworkRootDirectory()); return wroModelFactory.create(); } private void assertCssFileExists(String cssFileName, List<Resource> resources) { boolean exists = false; for (Resource resource : resources) { if (resource.getUri().endsWith('/' + cssFileName)) { exists = true; break; } } assertTrue(exists); } private void assertCanLoadResource(UriLocatorFactory uriLocatorFactory, Resource resource) throws IOException { final UriLocator instance = uriLocatorFactory.getInstance(resource.getUri()); final InputStream locate = instance.locate(resource.getUri()); try { assertNotNull(locate); final int read = locate.read(); assertTrue(-1 != read); } finally { if (locate != null) { locate.close(); } } } @Rule public TemporaryFolder tmpDir = new TemporaryFolder(); @Test(expected = IllegalArgumentException.class) public void testTwoCssSameName() throws Exception { FileUtils.write(new File(tmpDir.getRoot(), "cssA.css"), "// cssA.css"); File subdir = new File(tmpDir.getRoot(), "subdir"); FileUtils.write(new File(subdir, "cssA.css"), "// cssA2.css"); String sourcesXml = "<sources><" + REQUIRE_EL + "><" + CSS_SOURCE_EL + " " + WEBAPP_ATT + "=\"\" " + PATH_ON_DISK_ATT + "=\"" + tmpDir.getRoot().getAbsolutePath() + "\"/>" + "</" + REQUIRE_EL + "></sources>"; createRequireModel(sourcesXml); } private void assertRequireModel(WroModel wroModel) throws IOException { assertRequireModel(wroModel, true); } private void assertRequireModel(WroModel wroModel, boolean testMinimized) throws IOException { Set<String> groupNames = new HashSet<String>(); final UriLocatorFactory uriLocatorFactory = new GeonetworkMavenWrojManagerFactory().newUriLocatorFactory(); Set<String> nonMinifiedFiles = Sets.newHashSet("1a.css", "sampleFile2a.js", "sampleFile1b.js"); for (Group group : wroModel.getGroups()) { groupNames.add(group.getName()); final List<Resource> resources = group.getResources(); if (group.getName().equals("1a")) { assertCssFileExists("1a.css", resources); } boolean hasSelfJsFile = false; for (Resource resource : resources) { final String uri = resource.getUri(); if (uri.endsWith(group.getName() + ".js")) { hasSelfJsFile = true; } assertCanLoadResource(uriLocatorFactory, resource); if (testMinimized) { if (group.getName().equals(GROUP_NAME_CLOSURE_DEPS) || nonMinifiedFiles.contains(uri.substring(uri.lastIndexOf("/") + 1))) { assertFalse(resource.getUri() + " was minimized but should not be", resource.isMinimize()); } else { assertTrue(resource.getUri() + " was not minimized but should be", resource.isMinimize()); } } } // closureDeps group is fully tested in a dedicated tests so can ignore it here if (!group.getName().equals(GROUP_NAME_CLOSURE_DEPS)) { if (!group.getName().equals("anotherCss")) { assertTrue("Group: '" + group.getName() + "' does not have its js file only its dependencies", hasSelfJsFile); } else { assertEquals(1, resources.size()); assertTrue(resources.get(0).getUri().endsWith("anotherCss.less")); } } } assertTrue(groupNames.contains("1a")); assertTrue(groupNames.contains("1b")); assertTrue(groupNames.contains("2a")); assertTrue(groupNames.contains("2b")); assertTrue(groupNames.contains("3a")); assertTrue(groupNames.contains("3b")); assertTrue(groupNames.contains("3c")); assertTrue(groupNames.contains(GROUP_NAME_CLOSURE_DEPS)); } private String createSourcesXmlWithPathOnGroup() { return createSourcesXmlWithPathOnGroup(PATH_TO_ROOT_OF_TEST_RESOURCES); } private String createSourcesXmlWithPathOnGroup(String pathOnDisk) { return "<sources xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xsi:noNamespaceSchemaLocation=\"../../../../web/src/main/webResources/WEB-INF/wro-sources.xsd\">\n" + " <require pathOnDisk=\"" + pathOnDisk + "\">\n" + " <jsSource webappPath=\"\">\n" + " <notMinimized>\n" + " <file>sampleFile1b.js</file>\n" + " <file>jslvl2/sampleFile2a.js</file>\n" + " </notMinimized>\n" + " </jsSource>\n" + " <cssSource webappPath=\"\">\n" + " <notMinimized>\n" + " <file>1a.css</file>\n" + " </notMinimized>\n" + " </cssSource>\n" + " </require>\n" + "</sources>"; } public String getGeonetworkRootDirectory() { final File jsTestBaseDir = ClosureRequireDependencyManagerTest.getJsTestBaseDir(); return GeonetWroModelFactory.findGeonetworkRootDirectory(jsTestBaseDir.getAbsolutePath()); } }
true
true
public void testClosureJsGroup() throws Exception { final String jsTestBaseDir = ClosureRequireDependencyManagerTest.getJsTestBaseDir().getAbsolutePath(); String sourcesXml = createSourcesXmlWithPathOnGroup(jsTestBaseDir); final WroModel wroModel = createRequireModel(sourcesXml); final Collection<Group> groups = wroModel.getGroups(); Group depsGroup = null; for (Group group : groups) { if (group.getName().equals(GeonetWroModelFactory.GROUP_NAME_CLOSURE_DEPS)) { assertNull("There should only be one deps group but found at least 2", depsGroup); depsGroup = group; } } assertNotNull(depsGroup); final List<Resource> resources = depsGroup.getResources(); String jsTestBaseDirAsPath = jsTestBaseDir.replace('\\', '/'); assertEquals(7, resources.size()); for (Resource resource : resources) { final UriLocatorFactory uriLocatorFactory = new GeonetworkMavenWrojManagerFactory().newUriLocatorFactory(); final UriLocator instance = uriLocatorFactory.getInstance(resource.getUri()); final String deps = IOUtils.toString(instance.locate(resource.getUri()), "UTF-8"); if (resource.getUri().contains("sampleFile1a.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/sampleFile1a.js', ['1a'], ['2a']);\n", deps); } else if (resource.getUri().contains("sampleFile1b.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/sampleFile1b.js', ['1b'], ['3c','1a','2a']);\n", deps); } else if (resource.getUri().contains("sampleFile2a.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/jslvl2/sampleFile2a.js', ['2a'], ['3a','2b'," + "'3c','3b']);\n", deps); } else if (resource.getUri().contains("sampleFile2b.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/jslvl2/sampleFile2b.js', ['2b'], []);\n", deps); } else if (resource.getUri().contains("sampleFile3a.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/jslvl2/jslvl3/sampleFile3a.js', ['3a'], []);\n", deps); } else if (resource.getUri().contains("sampleFile3b.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/jslvl2/jslvl3/sampleFile3b.js', ['3b'], []);\n", deps); } else if (resource.getUri().contains("sampleFile3c.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/jslvl2/jslvl3/sampleFile3c.js', ['3c'], []);\n", deps); } } }
public void testClosureJsGroup() throws Exception { final String jsTestBaseDir = ClosureRequireDependencyManagerTest.getJsTestBaseDir().getAbsolutePath(); String sourcesXml = createSourcesXmlWithPathOnGroup(jsTestBaseDir); final WroModel wroModel = createRequireModel(sourcesXml); final Collection<Group> groups = wroModel.getGroups(); Group depsGroup = null; for (Group group : groups) { if (group.getName().equals(GeonetWroModelFactory.GROUP_NAME_CLOSURE_DEPS)) { assertNull("There should only be one deps group but found at least 2", depsGroup); depsGroup = group; } } assertNotNull(depsGroup); final List<Resource> resources = depsGroup.getResources(); String jsTestBaseDirAsPath = jsTestBaseDir.replace('\\', '/'); if (jsTestBaseDirAsPath.charAt(0) == '/') { jsTestBaseDirAsPath = jsTestBaseDirAsPath.substring(1); } assertEquals(7, resources.size()); for (Resource resource : resources) { final UriLocatorFactory uriLocatorFactory = new GeonetworkMavenWrojManagerFactory().newUriLocatorFactory(); final UriLocator instance = uriLocatorFactory.getInstance(resource.getUri()); final String deps = IOUtils.toString(instance.locate(resource.getUri()), "UTF-8"); if (resource.getUri().contains("sampleFile1a.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/sampleFile1a.js', ['1a'], ['2a']);\n", deps); } else if (resource.getUri().contains("sampleFile1b.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/sampleFile1b.js', ['1b'], ['3c','1a','2a']);\n", deps); } else if (resource.getUri().contains("sampleFile2a.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/jslvl2/sampleFile2a.js', ['2a'], ['3a','2b'," + "'3c','3b']);\n", deps); } else if (resource.getUri().contains("sampleFile2b.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/jslvl2/sampleFile2b.js', ['2b'], []);\n", deps); } else if (resource.getUri().contains("sampleFile3a.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/jslvl2/jslvl3/sampleFile3a.js', ['3a'], []);\n", deps); } else if (resource.getUri().contains("sampleFile3b.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/jslvl2/jslvl3/sampleFile3b.js', ['3b'], []);\n", deps); } else if (resource.getUri().contains("sampleFile3c.js")) { assertEquals("goog.addDependency('" + PATH_TO_WEBAPP_BASE_FROM_CLOSURE_BASE_JS_FILE + "/" + jsTestBaseDirAsPath + "/jslvl2/jslvl3/sampleFile3c.js', ['3c'], []);\n", deps); } } }
diff --git a/src/main/java/com/jadventure/game/CommandParser.java b/src/main/java/com/jadventure/game/CommandParser.java index 5514aef..d5a1ff3 100644 --- a/src/main/java/com/jadventure/game/CommandParser.java +++ b/src/main/java/com/jadventure/game/CommandParser.java @@ -1,102 +1,103 @@ package com.jadventure.game; import com.jadventure.game.entities.Player; import com.jadventure.game.menus.DebugMenu; import com.jadventure.game.navigation.Direction; import com.jadventure.game.navigation.ILocation; import com.jadventure.game.monsters.MonsterFactory; import com.jadventure.game.monsters.Monster; import java.util.Map; import java.util.ArrayList; import java.util.HashMap; public class CommandParser { private String helpText = "\nstats: Prints your statistics.\n" + "backpack: Prints out the contents of your backpack.\n" + "save: Save your progress.\n" + "goto: Go in a direction.\n" + "exit: Exit the game and return to the main menu.\n"; public boolean parse(Player player, String command, boolean continuePrompt) { if (command.equals("st")) { player.getStats(); } else if (command.equals("help")) { System.out.print(helpText); } else if (command.equals("b")) { player.printBackPack(); } else if (command.equals("s")) { player.save(); } else if (command.startsWith("g")) { String message = command.substring(1); HashMap<String, String> directionLinks = new HashMap<String,String>() {{ put("n", "north"); put("s", "south"); put("e", "east"); put("w", "west"); }}; ILocation location = player.getLocation(); try { message = directionLinks.get(message); Direction direction = Direction.valueOf(message.toUpperCase()); Map<Direction, ILocation> exits = location.getExits(); if (exits.containsKey(direction)) { ILocation newLocation = exits.get(Direction.valueOf(message.toUpperCase())); player.setLocation(newLocation); player.getLocation().print(); MonsterFactory monsterFactory = new MonsterFactory(); Monster monster = monsterFactory.generateMonster(player); player.getLocation().setMonsters(monster); } else { System.out.println("The is no exit that way."); } } catch (IllegalArgumentException ex) { System.out.println("That direction doesn't exist"); } catch (NullPointerException ex) { System.out.println("That direction doesn't exist"); } } else if (command.startsWith("p")) { String itemName = command.substring(1); player.pickUpItem(itemName); } else if (command.startsWith("m")){ ArrayList<Monster> monsterList = player.getLocation().getMonsters(); if (monsterList.size() > 0) { System.out.println("Monsters around you:"); System.out.println("----------------------------"); for (Monster monster : monsterList) { System.out.println(monster.monsterType); } System.out.println("----------------------------"); } else { System.out.println("There are no monsters around you"); } } else if (command.startsWith("d")){ String itemName = command.substring(1); player.dropItem(itemName); } + else if (command.equals("exit")) { + continuePrompt = false; + } else if (command.startsWith("e")) { String itemName = command.substring(1); player.equipItem(itemName); } else if (command.startsWith("de")) { String itemName = command.substring(2); player.dequipItem(itemName); } else if (command.equals("debug")) { new DebugMenu(player); - } else if (command.equals("exit")) { - continuePrompt = false; } return continuePrompt; } }
false
true
public boolean parse(Player player, String command, boolean continuePrompt) { if (command.equals("st")) { player.getStats(); } else if (command.equals("help")) { System.out.print(helpText); } else if (command.equals("b")) { player.printBackPack(); } else if (command.equals("s")) { player.save(); } else if (command.startsWith("g")) { String message = command.substring(1); HashMap<String, String> directionLinks = new HashMap<String,String>() {{ put("n", "north"); put("s", "south"); put("e", "east"); put("w", "west"); }}; ILocation location = player.getLocation(); try { message = directionLinks.get(message); Direction direction = Direction.valueOf(message.toUpperCase()); Map<Direction, ILocation> exits = location.getExits(); if (exits.containsKey(direction)) { ILocation newLocation = exits.get(Direction.valueOf(message.toUpperCase())); player.setLocation(newLocation); player.getLocation().print(); MonsterFactory monsterFactory = new MonsterFactory(); Monster monster = monsterFactory.generateMonster(player); player.getLocation().setMonsters(monster); } else { System.out.println("The is no exit that way."); } } catch (IllegalArgumentException ex) { System.out.println("That direction doesn't exist"); } catch (NullPointerException ex) { System.out.println("That direction doesn't exist"); } } else if (command.startsWith("p")) { String itemName = command.substring(1); player.pickUpItem(itemName); } else if (command.startsWith("m")){ ArrayList<Monster> monsterList = player.getLocation().getMonsters(); if (monsterList.size() > 0) { System.out.println("Monsters around you:"); System.out.println("----------------------------"); for (Monster monster : monsterList) { System.out.println(monster.monsterType); } System.out.println("----------------------------"); } else { System.out.println("There are no monsters around you"); } } else if (command.startsWith("d")){ String itemName = command.substring(1); player.dropItem(itemName); } else if (command.startsWith("e")) { String itemName = command.substring(1); player.equipItem(itemName); } else if (command.startsWith("de")) { String itemName = command.substring(2); player.dequipItem(itemName); } else if (command.equals("debug")) { new DebugMenu(player); } else if (command.equals("exit")) { continuePrompt = false; } return continuePrompt; }
public boolean parse(Player player, String command, boolean continuePrompt) { if (command.equals("st")) { player.getStats(); } else if (command.equals("help")) { System.out.print(helpText); } else if (command.equals("b")) { player.printBackPack(); } else if (command.equals("s")) { player.save(); } else if (command.startsWith("g")) { String message = command.substring(1); HashMap<String, String> directionLinks = new HashMap<String,String>() {{ put("n", "north"); put("s", "south"); put("e", "east"); put("w", "west"); }}; ILocation location = player.getLocation(); try { message = directionLinks.get(message); Direction direction = Direction.valueOf(message.toUpperCase()); Map<Direction, ILocation> exits = location.getExits(); if (exits.containsKey(direction)) { ILocation newLocation = exits.get(Direction.valueOf(message.toUpperCase())); player.setLocation(newLocation); player.getLocation().print(); MonsterFactory monsterFactory = new MonsterFactory(); Monster monster = monsterFactory.generateMonster(player); player.getLocation().setMonsters(monster); } else { System.out.println("The is no exit that way."); } } catch (IllegalArgumentException ex) { System.out.println("That direction doesn't exist"); } catch (NullPointerException ex) { System.out.println("That direction doesn't exist"); } } else if (command.startsWith("p")) { String itemName = command.substring(1); player.pickUpItem(itemName); } else if (command.startsWith("m")){ ArrayList<Monster> monsterList = player.getLocation().getMonsters(); if (monsterList.size() > 0) { System.out.println("Monsters around you:"); System.out.println("----------------------------"); for (Monster monster : monsterList) { System.out.println(monster.monsterType); } System.out.println("----------------------------"); } else { System.out.println("There are no monsters around you"); } } else if (command.startsWith("d")){ String itemName = command.substring(1); player.dropItem(itemName); } else if (command.equals("exit")) { continuePrompt = false; } else if (command.startsWith("e")) { String itemName = command.substring(1); player.equipItem(itemName); } else if (command.startsWith("de")) { String itemName = command.substring(2); player.dequipItem(itemName); } else if (command.equals("debug")) { new DebugMenu(player); } return continuePrompt; }
diff --git a/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/df/impl/InstanceImpl.java b/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/df/impl/InstanceImpl.java index 3777156a9..bead04868 100644 --- a/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/df/impl/InstanceImpl.java +++ b/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/df/impl/InstanceImpl.java @@ -1,392 +1,395 @@ /* * Copyright (c) 2009-2011, IETR/INSA of Rennes * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the IETR/INSA of Rennes nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package net.sf.orcc.df.impl; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import net.sf.orcc.df.Actor; import net.sf.orcc.df.Argument; import net.sf.orcc.df.Broadcast; import net.sf.orcc.df.Connection; import net.sf.orcc.df.DfPackage; import net.sf.orcc.df.Entity; import net.sf.orcc.df.Instance; import net.sf.orcc.df.Network; import net.sf.orcc.df.Port; import net.sf.orcc.df.util.DfUtil; import net.sf.orcc.graph.Graph; import net.sf.orcc.graph.impl.VertexImpl; import net.sf.orcc.moc.MoC; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * This class defines an instance. An instance has an id, a class, parameters * and attributes. The class of the instance points to an actor or a network. * * @author Matthieu Wipliez * @generated */ public class InstanceImpl extends VertexImpl implements Instance { /** * The cached value of the '{@link #getArguments() <em>Arguments</em>}' * containment reference list. <!-- begin-user-doc --> <!-- end-user-doc --> * * @see #getArguments() * @ordered */ protected EList<Argument> arguments; /** * The cached value of the '{@link #getEntity() <em>Entity</em>}' reference. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getEntity() * @generated * @ordered */ protected EObject entity; /** * The default value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ protected InstanceImpl() { super(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public EObject basicGetEntity() { return entity; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setEntity(EObject newEntity) { EObject oldEntity = entity; entity = newEntity; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, DfPackage.INSTANCE__ENTITY, oldEntity, entity)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case DfPackage.INSTANCE__ARGUMENTS: return getArguments(); case DfPackage.INSTANCE__ENTITY: if (resolve) return getEntity(); return basicGetEntity(); case DfPackage.INSTANCE__NAME: return getName(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case DfPackage.INSTANCE__ARGUMENTS: return ((InternalEList<?>) getArguments()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case DfPackage.INSTANCE__ARGUMENTS: return arguments != null && !arguments.isEmpty(); case DfPackage.INSTANCE__ENTITY: return entity != null; case DfPackage.INSTANCE__NAME: return NAME_EDEFAULT == null ? getName() != null : !NAME_EDEFAULT .equals(getName()); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case DfPackage.INSTANCE__ARGUMENTS: getArguments().clear(); getArguments().addAll((Collection<? extends Argument>) newValue); return; case DfPackage.INSTANCE__ENTITY: setEntity((EObject) newValue); return; case DfPackage.INSTANCE__NAME: setName((String) newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return DfPackage.Literals.INSTANCE; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case DfPackage.INSTANCE__ARGUMENTS: getArguments().clear(); return; case DfPackage.INSTANCE__ENTITY: setEntity((EObject) null); return; case DfPackage.INSTANCE__NAME: setName(NAME_EDEFAULT); return; } super.eUnset(featureID); } @Override public Actor getActor() { return (Actor) getEntity(); } @Override @SuppressWarnings("unchecked") public <T> T getAdapter(Class<T> type) { if (type == Entity.class) { EList<Port> inputs, outputs; - if (entity instanceof Actor) { - inputs = ((Actor) entity).getInputs(); - outputs = ((Actor) entity).getOutputs(); - } else if (entity instanceof Network) { - inputs = ((Network) entity).getInputs(); - outputs = ((Network) entity).getOutputs(); + EObject object = getEntity(); + if (object instanceof Actor) { + inputs = ((Actor) object).getInputs(); + outputs = ((Actor) object).getOutputs(); + } else if (object instanceof Network) { + inputs = ((Network) object).getInputs(); + outputs = ((Network) object).getOutputs(); } else { // cannot adapt instances of other objects to Entity return null; } return (T) new EntityImpl(this, inputs, outputs); } else if (type == Actor.class) { - if (entity instanceof Actor) { - return (T) entity; + EObject object = getEntity(); + if (object instanceof Actor) { + return (T) object; } return null; } else if (type == Network.class) { - if (entity instanceof Network) { - return (T) entity; + EObject object = getEntity(); + if (object instanceof Network) { + return (T) object; } return null; } return super.getAdapter(type); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public EList<Argument> getArguments() { if (arguments == null) { arguments = new EObjectContainmentEList<Argument>(Argument.class, this, DfPackage.INSTANCE__ARGUMENTS); } return arguments; } @Override public Broadcast getBroadcast() { return (Broadcast) getEntity(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public EObject getEntity() { if (entity != null && entity.eIsProxy()) { InternalEObject oldEntity = (InternalEObject) entity; entity = eResolveProxy(oldEntity); if (entity != oldEntity) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, DfPackage.INSTANCE__ENTITY, oldEntity, entity)); } } return entity; } @Override public List<String> getHierarchicalId() { List<String> ids = new ArrayList<String>(); for (Graph graph : getHierarchy()) { ids.add(graph.getLabel()); } ids.add(getName()); return ids; } @Override public String getHierarchicalName() { StringBuilder builder = new StringBuilder(); for (Graph graph : getHierarchy()) { builder.append(graph.getLabel()); builder.append('_'); } builder.append(getName()); return builder.toString(); } @Override public String getId() { return getName(); } @Override public Map<Port, Connection> getIncomingPortMap() { return getAdapter(Entity.class).getIncomingPortMap(); } @Override public MoC getMoC() { if (isActor()) { return getActor().getMoC(); } else if (isNetwork()) { return getNetwork().getMoC(); } else { return null; } } @Override public String getName() { return getLabel(); } @Override public Network getNetwork() { return (Network) getEntity(); } @Override public Map<Port, List<Connection>> getOutgoingPortMap() { return getAdapter(Entity.class).getOutgoingPortMap(); } @Override public String getPackage() { return DfUtil.getPackage(getName()); } @Override public String getSimpleName() { return DfUtil.getSimpleName(getName()); } @Override public boolean isActor() { return getEntity() instanceof Actor; } @Override public boolean isBroadcast() { return getEntity() instanceof Broadcast; } public boolean isInstance() { return true; } @Override public boolean isNetwork() { return getEntity() instanceof Network; } @Override public void setName(String newName) { setLabel(newName); } @Override public String toString() { return getName() + ": " + getEntity(); } }
false
true
public <T> T getAdapter(Class<T> type) { if (type == Entity.class) { EList<Port> inputs, outputs; if (entity instanceof Actor) { inputs = ((Actor) entity).getInputs(); outputs = ((Actor) entity).getOutputs(); } else if (entity instanceof Network) { inputs = ((Network) entity).getInputs(); outputs = ((Network) entity).getOutputs(); } else { // cannot adapt instances of other objects to Entity return null; } return (T) new EntityImpl(this, inputs, outputs); } else if (type == Actor.class) { if (entity instanceof Actor) { return (T) entity; } return null; } else if (type == Network.class) { if (entity instanceof Network) { return (T) entity; } return null; } return super.getAdapter(type); }
public <T> T getAdapter(Class<T> type) { if (type == Entity.class) { EList<Port> inputs, outputs; EObject object = getEntity(); if (object instanceof Actor) { inputs = ((Actor) object).getInputs(); outputs = ((Actor) object).getOutputs(); } else if (object instanceof Network) { inputs = ((Network) object).getInputs(); outputs = ((Network) object).getOutputs(); } else { // cannot adapt instances of other objects to Entity return null; } return (T) new EntityImpl(this, inputs, outputs); } else if (type == Actor.class) { EObject object = getEntity(); if (object instanceof Actor) { return (T) object; } return null; } else if (type == Network.class) { EObject object = getEntity(); if (object instanceof Network) { return (T) object; } return null; } return super.getAdapter(type); }
diff --git a/branches/v1.14/src/om/stdcomponent/IFrameComponent.java b/branches/v1.14/src/om/stdcomponent/IFrameComponent.java index e91b637..8a84c53 100644 --- a/branches/v1.14/src/om/stdcomponent/IFrameComponent.java +++ b/branches/v1.14/src/om/stdcomponent/IFrameComponent.java @@ -1,285 +1,285 @@ /* OpenMark online assessment system Copyright (C) 2007 The Open University This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package om.stdcomponent; import java.io.IOException; import java.util.HashSet; import java.util.Set; import om.*; import om.question.ActionParams; import om.stdquestion.*; import org.w3c.dom.*; import util.misc.*; import util.xml.XML; import util.xml.XMLException; /** Represents an iframe <p/> <h2>XML usage</h2> &lt;iframe id="myFrame" src="http://www.site/page.html" width="100" height="80"/&gt; <p/> or (for an html file contained in question jar): <p/> &lt;iframe id="myFrame" src="page.html" width="100" height="80" showResponse="yes"/&gt; <p/> <h2>Properties</h2> <table border="1"> <tr><th>Property</th><th>Values</th><th>Effect</th></tr> <tr><td>id</td><td>(string)</td><td>Specifies unique ID</td></tr> <tr><td>width</td><td>(int)</td><td>default displayed width in pixels (optional)</td></tr> <tr><td>height</td><td>(int)</td><td>default displayedheight in pixels (optional)</td></tr> <tr><td>src</td><td>(string)</td><td>html src contents of iframe</td></tr> </table> */ public class IFrameComponent extends QComponent { public static final String PROPERTY_ACTION="action"; private static final String PROPERTY_SRC="src"; private static final String PROPERTY_WIDTH="width"; private static final String PROPERTY_HEIGHT="height"; private static final String PROPERTY_SHOWRESPONSE="showResponse";///w private static final String BUTTON_LABEL=" Enter answer"; /** @return Tag name (introspected; this may be replaced by a 1.5 annotation) */ public static String getTagName() { return "iframe"; } /** path to image file */ private String sSrc=null; // Currently-loaded file private int iWidth = 300; private int iHeight = 300; private byte[] movieData; private String sMimeType; /** Current (most recently set) value */ private String sValue; /** Random token used to check when user goes to different window */ private String sToken; /** * Keep track of resources we added to users so we can save SOAP time by * not transferring them again. */ private Set<String> sAddedResources=new HashSet<String>(); /** True if there was whitespace before or after the &lt;flash&gt; tag */ private boolean bSpaceBefore,bSpaceAfter; /** Specifies attributes required */ @Override protected String[] getRequiredAttributes() { return new String[] {PROPERTY_SRC, PROPERTY_WIDTH,PROPERTY_HEIGHT}; } /** Specifies possible attributes */ @Override protected void defineProperties() throws OmDeveloperException { super.defineProperties(); defineString(PROPERTY_ACTION); defineString(PROPERTY_SRC); defineInteger(PROPERTY_WIDTH); defineInteger(PROPERTY_HEIGHT); defineString(PROPERTY_SHOWRESPONSE);///w } /** parses internals of tag to create java component*/ @Override protected void initChildren(Element eThis) throws OmException { Node nPrevious=eThis.getPreviousSibling(); if(nPrevious!=null && nPrevious instanceof Text) { String sText=((Text)nPrevious).getData(); if(sText.length()>0 && Character.isWhitespace(sText.charAt(sText.length()-1))) bSpaceBefore=true; } Node nAfter=eThis.getNextSibling(); if(nAfter!=null && nAfter instanceof Text) { String sText=((Text)nAfter).getData(); if(sText.length()>0 && Character.isWhitespace(sText.charAt(0))) bSpaceAfter=true; } } boolean external, showResponse;///w @Override protected void initSpecific(Element eThis) throws OmException { sToken="t"+getQuestion().getRandom().nextInt()+getID().hashCode(); showResponse=!getString(PROPERTY_SHOWRESPONSE).equalsIgnoreCase("no");///w external=getString(PROPERTY_SRC).substring(0,4).equalsIgnoreCase("http"); /* external means the page is not in the question jar, we want to keep this definition * because internal pages can send data back to OM, externals cant - SECURITY!! */ if(!external && showResponse)getQuestion().checkCallback(getString(PROPERTY_ACTION));///w } /** @return SRC of Image * @throws OmDeveloperException */ public String getSRC() throws OmDeveloperException { return getString(PROPERTY_SRC); } /** * Sets the src file path. * <p> * @param sSrc New value for src * @throws OmDeveloperException -- when? */ public void setSrc(String sSrc) throws OmDeveloperException { setString(PROPERTY_SRC, sSrc); } @Override public void produceVisibleOutput(QContent qc,boolean bInit,boolean bPlain) throws OmException { double dZoom=getQuestion().getZoom(); iWidth = getInteger("width"); iHeight = getInteger("height"); sSrc=getString(PROPERTY_SRC); // iframe tag int iActualWidth=(int)(iWidth*dZoom+0.5), iActualHeight=(int)(iHeight*dZoom+0.5); Element eInput=qc.createElement("input"); eInput.setAttribute("type","hidden"); String sInputID=QDocument.ID_PREFIX+QDocument.VALUE_PREFIX+getID(); eInput.setAttribute("name",sInputID); eInput.setAttribute("id",sInputID); qc.addInlineXHTML(eInput); /*if not external, set sup tag that contains information that is passed from user to OM. we dont do this if frame source is not in the question jar only accept input from the containing url if NOT external, this is a security feature to prevent response string being hijacked. If change this ensure other security precautions are taken * */ if(isPropertySet(PROPERTY_ACTION) && !external && showResponse)///w { eInput=qc.createElement("input"); eInput.setAttribute("type","hidden"); String sActionID=QDocument.ID_PREFIX+QDocument.ACTION_PREFIX+getID(); eInput.setAttribute("name",sActionID); eInput.setAttribute("id",sActionID); eInput.setAttribute("value","submit"); eInput.setAttribute("disabled","disabled"); // Disabled unless submitted this way qc.addInlineXHTML(eInput); } /* setting up the tag */ if(bInit && !external) { try { qc.addResource(sSrc,"html", getQuestion().loadResource(sSrc)); } catch(IllegalArgumentException e) { throw new OmException("Error loading html",e); } catch(IOException e) { throw new OmException("Error loading html",e); } } Element eEnsureSpaces=qc.createElement("iframe"); eEnsureSpaces.setAttribute("src",(external?"":"%%RESOURCES%%/")+sSrc); eEnsureSpaces.setAttribute("id","IF"+getID()); eEnsureSpaces.setAttribute("height",""+iActualHeight); eEnsureSpaces.setAttribute("width",""+iActualWidth); eEnsureSpaces.setAttribute("marginwidth","0");///w eEnsureSpaces.setAttribute("marginheight","0");///w eEnsureSpaces.setAttribute("frameborder","0"); qc.addInlineXHTML(eEnsureSpaces); - /* setting up enter answer button tag for passing information */ + /* setting up enter answer button tag for passing information if(!external && showResponse){///w qc.addTextEquivalent("<br/>"); Element okTag=qc.createElement("input"); okTag.setAttribute("type","submit"); okTag.setAttribute("id","enterB"); okTag.setAttribute("value",BUTTON_LABEL); okTag.setAttribute("onclick", "if(this.hasSubmitted) { return false; } this.hasSubmitted=true; "+ "sendResponse('" +sInputID+"','"+QDocument.ID_PREFIX+"'," +"'IF"+getID()+"'" +");" ); if(!isEnabled()) okTag.setAttribute("disabled","yes"); qc.addInlineXHTML(okTag); - } + }*/ // If there's a space before, add one here too (otherwise IE eats it) if(bSpaceBefore) XML.createText(eEnsureSpaces," "); if(bSpaceAfter) XML.createText(eEnsureSpaces," "); } public String getResponse() { return util.misc.IO.CleanString(sValue); } @Override protected void formSetValue(String newValue,ActionParams ap) throws OmException { this.sValue=newValue; } @Override protected void formCallAction(String newValue,ActionParams ap) throws OmException { getQuestion().callback(getString(PROPERTY_ACTION)); } } // end of iframe Component class
false
true
public void produceVisibleOutput(QContent qc,boolean bInit,boolean bPlain) throws OmException { double dZoom=getQuestion().getZoom(); iWidth = getInteger("width"); iHeight = getInteger("height"); sSrc=getString(PROPERTY_SRC); // iframe tag int iActualWidth=(int)(iWidth*dZoom+0.5), iActualHeight=(int)(iHeight*dZoom+0.5); Element eInput=qc.createElement("input"); eInput.setAttribute("type","hidden"); String sInputID=QDocument.ID_PREFIX+QDocument.VALUE_PREFIX+getID(); eInput.setAttribute("name",sInputID); eInput.setAttribute("id",sInputID); qc.addInlineXHTML(eInput); /*if not external, set sup tag that contains information that is passed from user to OM. we dont do this if frame source is not in the question jar only accept input from the containing url if NOT external, this is a security feature to prevent response string being hijacked. If change this ensure other security precautions are taken * */ if(isPropertySet(PROPERTY_ACTION) && !external && showResponse)///w { eInput=qc.createElement("input"); eInput.setAttribute("type","hidden"); String sActionID=QDocument.ID_PREFIX+QDocument.ACTION_PREFIX+getID(); eInput.setAttribute("name",sActionID); eInput.setAttribute("id",sActionID); eInput.setAttribute("value","submit"); eInput.setAttribute("disabled","disabled"); // Disabled unless submitted this way qc.addInlineXHTML(eInput); } /* setting up the tag */ if(bInit && !external) { try { qc.addResource(sSrc,"html", getQuestion().loadResource(sSrc)); } catch(IllegalArgumentException e) { throw new OmException("Error loading html",e); } catch(IOException e) { throw new OmException("Error loading html",e); } } Element eEnsureSpaces=qc.createElement("iframe"); eEnsureSpaces.setAttribute("src",(external?"":"%%RESOURCES%%/")+sSrc); eEnsureSpaces.setAttribute("id","IF"+getID()); eEnsureSpaces.setAttribute("height",""+iActualHeight); eEnsureSpaces.setAttribute("width",""+iActualWidth); eEnsureSpaces.setAttribute("marginwidth","0");///w eEnsureSpaces.setAttribute("marginheight","0");///w eEnsureSpaces.setAttribute("frameborder","0"); qc.addInlineXHTML(eEnsureSpaces); /* setting up enter answer button tag for passing information */ if(!external && showResponse){///w qc.addTextEquivalent("<br/>"); Element okTag=qc.createElement("input"); okTag.setAttribute("type","submit"); okTag.setAttribute("id","enterB"); okTag.setAttribute("value",BUTTON_LABEL); okTag.setAttribute("onclick", "if(this.hasSubmitted) { return false; } this.hasSubmitted=true; "+ "sendResponse('" +sInputID+"','"+QDocument.ID_PREFIX+"'," +"'IF"+getID()+"'" +");" ); if(!isEnabled()) okTag.setAttribute("disabled","yes"); qc.addInlineXHTML(okTag); } // If there's a space before, add one here too (otherwise IE eats it) if(bSpaceBefore) XML.createText(eEnsureSpaces," "); if(bSpaceAfter) XML.createText(eEnsureSpaces," "); }
public void produceVisibleOutput(QContent qc,boolean bInit,boolean bPlain) throws OmException { double dZoom=getQuestion().getZoom(); iWidth = getInteger("width"); iHeight = getInteger("height"); sSrc=getString(PROPERTY_SRC); // iframe tag int iActualWidth=(int)(iWidth*dZoom+0.5), iActualHeight=(int)(iHeight*dZoom+0.5); Element eInput=qc.createElement("input"); eInput.setAttribute("type","hidden"); String sInputID=QDocument.ID_PREFIX+QDocument.VALUE_PREFIX+getID(); eInput.setAttribute("name",sInputID); eInput.setAttribute("id",sInputID); qc.addInlineXHTML(eInput); /*if not external, set sup tag that contains information that is passed from user to OM. we dont do this if frame source is not in the question jar only accept input from the containing url if NOT external, this is a security feature to prevent response string being hijacked. If change this ensure other security precautions are taken * */ if(isPropertySet(PROPERTY_ACTION) && !external && showResponse)///w { eInput=qc.createElement("input"); eInput.setAttribute("type","hidden"); String sActionID=QDocument.ID_PREFIX+QDocument.ACTION_PREFIX+getID(); eInput.setAttribute("name",sActionID); eInput.setAttribute("id",sActionID); eInput.setAttribute("value","submit"); eInput.setAttribute("disabled","disabled"); // Disabled unless submitted this way qc.addInlineXHTML(eInput); } /* setting up the tag */ if(bInit && !external) { try { qc.addResource(sSrc,"html", getQuestion().loadResource(sSrc)); } catch(IllegalArgumentException e) { throw new OmException("Error loading html",e); } catch(IOException e) { throw new OmException("Error loading html",e); } } Element eEnsureSpaces=qc.createElement("iframe"); eEnsureSpaces.setAttribute("src",(external?"":"%%RESOURCES%%/")+sSrc); eEnsureSpaces.setAttribute("id","IF"+getID()); eEnsureSpaces.setAttribute("height",""+iActualHeight); eEnsureSpaces.setAttribute("width",""+iActualWidth); eEnsureSpaces.setAttribute("marginwidth","0");///w eEnsureSpaces.setAttribute("marginheight","0");///w eEnsureSpaces.setAttribute("frameborder","0"); qc.addInlineXHTML(eEnsureSpaces); /* setting up enter answer button tag for passing information if(!external && showResponse){///w qc.addTextEquivalent("<br/>"); Element okTag=qc.createElement("input"); okTag.setAttribute("type","submit"); okTag.setAttribute("id","enterB"); okTag.setAttribute("value",BUTTON_LABEL); okTag.setAttribute("onclick", "if(this.hasSubmitted) { return false; } this.hasSubmitted=true; "+ "sendResponse('" +sInputID+"','"+QDocument.ID_PREFIX+"'," +"'IF"+getID()+"'" +");" ); if(!isEnabled()) okTag.setAttribute("disabled","yes"); qc.addInlineXHTML(okTag); }*/ // If there's a space before, add one here too (otherwise IE eats it) if(bSpaceBefore) XML.createText(eEnsureSpaces," "); if(bSpaceAfter) XML.createText(eEnsureSpaces," "); }
diff --git a/src/org/meta_environment/uptr/TreeAdapter.java b/src/org/meta_environment/uptr/TreeAdapter.java index f2d56511a5..e032f942f8 100644 --- a/src/org/meta_environment/uptr/TreeAdapter.java +++ b/src/org/meta_environment/uptr/TreeAdapter.java @@ -1,484 +1,485 @@ package org.meta_environment.uptr; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import org.eclipse.imp.pdb.facts.IConstructor; import org.eclipse.imp.pdb.facts.IInteger; import org.eclipse.imp.pdb.facts.IList; import org.eclipse.imp.pdb.facts.IListWriter; import org.eclipse.imp.pdb.facts.ISet; import org.eclipse.imp.pdb.facts.ISetWriter; import org.eclipse.imp.pdb.facts.ISourceLocation; import org.eclipse.imp.pdb.facts.IValue; import org.eclipse.imp.pdb.facts.IValueFactory; import org.eclipse.imp.pdb.facts.exceptions.FactTypeUseException; import org.eclipse.imp.pdb.facts.visitors.VisitorException; import org.meta_environment.ValueFactoryFactory; import org.meta_environment.rascal.interpreter.asserts.ImplementationError; import org.meta_environment.rascal.parser.MappingsCache; import org.meta_environment.uptr.visitors.IdentityTreeVisitor; public class TreeAdapter{ private TreeAdapter(){ super(); } public static boolean isAppl(IConstructor tree) { return tree.getConstructorType() == Factory.Tree_Appl; } public static boolean isAmb(IConstructor tree) { return tree.getConstructorType() == Factory.Tree_Amb; } public static boolean isChar(IConstructor tree) { return tree.getConstructorType() == Factory.Tree_Char; } public static boolean isCycle(IConstructor tree) { return tree.getConstructorType() == Factory.Tree_Cycle; } public static IConstructor getProduction(IConstructor tree) { return (IConstructor) tree.get("prod"); } public static boolean hasSortName(IConstructor tree) { return ProductionAdapter.hasSortName(getProduction(tree)); } public static String getSortName(IConstructor tree) throws FactTypeUseException { return ProductionAdapter.getSortName(getProduction(tree)); } public static String getConstructorName(IConstructor tree) { return ProductionAdapter.getConstructorName(getProduction(tree)); } public static boolean isProduction(IConstructor tree, String sortName, String consName) { IConstructor prod = getProduction(tree); return ProductionAdapter.getSortName(prod).equals(sortName) && ProductionAdapter.getConstructorName(prod).equals(consName); } public static boolean isLexToCf(IConstructor tree) { return isAppl(tree) ? ProductionAdapter.isLexToCf(getProduction(tree)) : false; } public static boolean isContextFree(IConstructor tree) { return isAppl(tree) ? ProductionAdapter.isContextFree(getProduction(tree)) : false; } public static boolean isList(IConstructor tree) { return isAppl(tree) ? ProductionAdapter.isList(getProduction(tree)) : false; } public static IList getArgs(IConstructor tree) { if (isAppl(tree)) { return (IList) tree.get("args"); } throw new ImplementationError("Node has no args"); } public static boolean isLiteral(IConstructor tree) { return isAppl(tree) ? ProductionAdapter.isLiteral(getProduction(tree)) : false; } public static IList getListASTArgs(IConstructor tree) { if (!isContextFree(tree) || !isList(tree)) { throw new ImplementationError("This is not a context-free list production: " + tree); } IList children = getArgs(tree); IListWriter writer = Factory.Args.writer(ValueFactoryFactory.getValueFactory()); for (int i = 0; i < children.length(); i++) { IValue kid = children.get(i); writer.append(kid); // skip layout and/or separators i += (isSeparatedList(tree) ? 3 : 1); } return writer.done(); } public static boolean isLexical(IConstructor tree) { return isAppl(tree) ? ProductionAdapter.isLexical(getProduction(tree)) : false; } public static boolean isLayout(IConstructor tree) { return isAppl(tree) ? ProductionAdapter.isLayout(getProduction(tree)) : false; } private static boolean isSeparatedList(IConstructor tree) { return isAppl(tree) ? isList(tree) && ProductionAdapter.isSeparatedList(getProduction(tree)) : false; } public static IList getASTArgs(IConstructor tree) { if (!isContextFree(tree)) { throw new ImplementationError("This is not a context-free production: " + tree); } IList children = getArgs(tree); IListWriter writer = Factory.Args.writer(ValueFactoryFactory.getValueFactory()); for (int i = 0; i < children.length(); i++) { IConstructor kid = (IConstructor) children.get(i); if (!isLiteral(kid) && !isCILiteral(kid)) { writer.append(kid); } // skip layout i++; } return writer.done(); } public static boolean isCILiteral(IConstructor tree) { return isAppl(tree) ? ProductionAdapter.isCILiteral(getProduction(tree)) : false; } public static ISet getAlternatives(IConstructor tree) { if (isAmb(tree)) { return (ISet) tree.get("alternatives"); } throw new ImplementationError("Node has no alternatives"); } public static ISourceLocation getLocation(IConstructor tree) { return (ISourceLocation) tree.getAnnotation(Factory.Location); } public static int getCharacter(IConstructor tree) { return ((IInteger) tree.get("character")).intValue(); } protected static class PositionAnnotator{ private final IConstructor tree; private final MappingsCache<PositionNode, IConstructor> cache; private boolean inLayout = false; private boolean labelLayout = false; public PositionAnnotator(IConstructor tree){ super(); this.tree = tree; this.cache = new MappingsCache<PositionNode, IConstructor>(); } public IConstructor addPositionInformation(String filename) { Factory.getInstance(); // make sure everything is declared try { return addPosInfo(tree, filename, new Position()); } catch (MalformedURLException e) { throw new RuntimeException(e); } } private IConstructor addPosInfo(IConstructor tree, String filename, Position cur) throws MalformedURLException{ IValueFactory factory = ValueFactoryFactory.getValueFactory(); int startLine = cur.line; int startCol = cur.col; int startOffset = cur.offset; PositionNode positionNode = new PositionNode(tree, cur.offset); IConstructor result = cache.get(positionNode); if(result != null){ ISourceLocation loc = getLocation(result); cur.col = loc.getEndColumn(); cur.line = loc.getEndLine(); cur.offset += loc.getLength(); return result; } if(isChar(tree)){ cur.offset++; if(((char) getCharacter(tree)) == '\n'){ cur.col = 0; cur.line++; }else{ cur.col++; } return tree; } if(isAppl(tree)){ boolean outermostLayout = false; IList args = getArgs(tree); if(isLayout(tree)){ inLayout = true; outermostLayout = true; } IListWriter newArgs = factory.listWriter(Factory.Tree); for(IValue arg : args){ newArgs.append(addPosInfo((IConstructor) arg, filename, cur)); } tree = tree.set("args", newArgs.done()); if(!labelLayout && outermostLayout){ inLayout = false; return tree; }else if(!labelLayout && inLayout){ return tree; } }else if(isAmb(tree)){ ISet alts = getAlternatives(tree); ISetWriter newAlts = ValueFactoryFactory.getValueFactory().setWriter(Factory.Tree); Position save = cur; Position newPos = save; ISetWriter cycles = ValueFactoryFactory.getValueFactory().setWriter(Factory.Tree); for(IValue arg : alts){ cur = save.clone(); IValue newArg = addPosInfo((IConstructor) arg, filename, cur); if(cur.offset != save.offset){ newPos = cur; newAlts.insert(newArg); }else if(newPos.offset == save.offset){ cycles.insert(arg); }else{ newAlts.insert(newArg); } } cur.col = newPos.col; cur.line = newPos.line; cur.offset = newPos.offset; for(IValue arg : cycles.done()){ IValue newArg = addPosInfo((IConstructor) arg, filename, cur); newAlts.insert(newArg); } tree = tree.set("alternatives", newAlts.done()); }else if(!isCycle(tree)){ System.err.println("unhandled tree: " + tree + "\n"); } ISourceLocation loc; if (!filename.equals("-")) { + filename = filename.startsWith("/") ? filename : "./"+filename; // TODO Fix properly. loc = factory.sourceLocation(filename, startOffset, cur.offset - startOffset, startLine, cur.line, startCol, cur.col); } else { try { loc = factory.sourceLocation(new URI("console", null, "/", null), startOffset, cur.offset - startOffset, startLine, cur.line, startCol, cur.col); } catch (URISyntaxException e) { throw new ImplementationError("should always construct valid URI's", e); } } result = tree.setAnnotation(Factory.Location, loc); cache.putUnsafe(positionNode, result); return result; } private static class Position{ public int col = 0; public int line = 1; public int offset = 0; public Position clone() { Position tmp = new Position(); tmp.col = col; tmp.line = line; tmp.offset = offset; return tmp; } } private static class PositionNode{ private final IConstructor tree; private final int offset; public PositionNode(IConstructor tree, int offset){ super(); this.tree = tree; this.offset = offset; } public int hashCode(){ return ((offset << 32) ^ tree.hashCode()); } public boolean equals(Object o){ if(o.getClass() != getClass()) return false; PositionNode other = (PositionNode) o; return (offset == other.offset && tree == other.tree); // NOTE: trees are shared, so they are pointer equal. } } } private static class Unparser extends IdentityTreeVisitor { private final OutputStream fStream; public Unparser(OutputStream stream) { fStream = stream; } @Override public IConstructor visitTreeAmb(IConstructor arg) throws VisitorException { ((ISet) arg.get("alternatives")).iterator().next().accept(this); return arg; } @Override public IConstructor visitTreeChar(IConstructor arg) throws VisitorException { try { fStream.write(((IInteger) arg.get("character")).intValue()); return arg; } catch (IOException e) { throw new VisitorException(e); } } @Override public IConstructor visitTreeAppl(IConstructor arg) throws VisitorException { IList children = (IList) arg.get("args"); for (IValue child : children) { child.accept(this); } return arg; } } public static void unparse(IConstructor tree, OutputStream stream) throws IOException, FactTypeUseException { try { if (tree.getConstructorType() == Factory.ParseTree_Top) { tree.get("top").accept(new Unparser(stream)); } else if (tree.getType() == Factory.Tree) { tree.accept(new Unparser(stream)); } else { throw new ImplementationError("Can not unparse this " + tree.getType()); } } catch (VisitorException e) { Throwable cause = e.getCause(); if (cause instanceof IOException) { throw (IOException) cause; } System.err.println("Unexpected error in unparse: " + e.getMessage()); e.printStackTrace(); } } public static String yield(IConstructor tree) throws FactTypeUseException { try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); unparse(tree, stream); return stream.toString(); } catch (IOException e) { throw new ImplementationError("Method yield failed", e); } } public static boolean isContextFreeInjectionOrSingleton(IConstructor tree) { IConstructor prod = getProduction(tree); if (isAppl(tree)) { if (!ProductionAdapter.isList(prod) && ProductionAdapter.getLhs(prod).length() == 1) { IConstructor rhs = ProductionAdapter.getRhs(prod); if (SymbolAdapter.isCf(rhs)) { rhs = SymbolAdapter.getSymbol(rhs); if (SymbolAdapter.isSort(rhs)) { return true; } } } } else if (isList(tree) && SymbolAdapter.isCf(ProductionAdapter.getRhs(prod))) { if (getArgs(tree).length() == 1) { return true; } } return false; } public static boolean isAmbiguousList(IConstructor tree) { if (isAmb(tree)) { IConstructor first = (IConstructor) getAlternatives(tree).iterator().next(); if (isList(first)) { return true; } } return false; } public static boolean isNonEmptyStarList(IConstructor tree) { if (isAppl(tree)) { IConstructor prod = getProduction(tree); if (ProductionAdapter.isList(prod)) { IConstructor sym = ProductionAdapter.getRhs(prod); if (SymbolAdapter.isCf(sym) || SymbolAdapter.isLex(sym)) { sym = SymbolAdapter.getSymbol(sym); } if (SymbolAdapter.isIterStar(sym) || SymbolAdapter.isIterStarSep(sym)) { return getArgs(tree).length() > 0; } } } return false; } public static boolean isCFList(IConstructor tree) { return isAppl(tree) && isContextFree(tree) && (SymbolAdapter.isPlusList(ProductionAdapter.getRhs(getProduction(tree))) || SymbolAdapter.isStarList(ProductionAdapter.getRhs(getProduction(tree)))); } /** * @return true if the tree does not have any characters, it's just an empty derivation */ public static boolean isEpsilon(IConstructor tree) { if (isAppl(tree)) { for (IValue arg : getArgs(tree)) { boolean argResult = isEpsilon((IConstructor) arg); if (argResult == false) { return false; } } return true; } if (isAmb(tree)) { return isEpsilon((IConstructor) getAlternatives(tree).iterator().next()); } if (isCycle(tree)) { return true; } // is a character return false; } public static boolean hasPreferAttribute(IConstructor tree) { return ProductionAdapter.hasPreferAttribute(getProduction(tree)); } public static boolean hasAvoidAttribute(IConstructor tree) { return ProductionAdapter.hasAvoidAttribute(getProduction(tree)); } }
true
true
private IConstructor addPosInfo(IConstructor tree, String filename, Position cur) throws MalformedURLException{ IValueFactory factory = ValueFactoryFactory.getValueFactory(); int startLine = cur.line; int startCol = cur.col; int startOffset = cur.offset; PositionNode positionNode = new PositionNode(tree, cur.offset); IConstructor result = cache.get(positionNode); if(result != null){ ISourceLocation loc = getLocation(result); cur.col = loc.getEndColumn(); cur.line = loc.getEndLine(); cur.offset += loc.getLength(); return result; } if(isChar(tree)){ cur.offset++; if(((char) getCharacter(tree)) == '\n'){ cur.col = 0; cur.line++; }else{ cur.col++; } return tree; } if(isAppl(tree)){ boolean outermostLayout = false; IList args = getArgs(tree); if(isLayout(tree)){ inLayout = true; outermostLayout = true; } IListWriter newArgs = factory.listWriter(Factory.Tree); for(IValue arg : args){ newArgs.append(addPosInfo((IConstructor) arg, filename, cur)); } tree = tree.set("args", newArgs.done()); if(!labelLayout && outermostLayout){ inLayout = false; return tree; }else if(!labelLayout && inLayout){ return tree; } }else if(isAmb(tree)){ ISet alts = getAlternatives(tree); ISetWriter newAlts = ValueFactoryFactory.getValueFactory().setWriter(Factory.Tree); Position save = cur; Position newPos = save; ISetWriter cycles = ValueFactoryFactory.getValueFactory().setWriter(Factory.Tree); for(IValue arg : alts){ cur = save.clone(); IValue newArg = addPosInfo((IConstructor) arg, filename, cur); if(cur.offset != save.offset){ newPos = cur; newAlts.insert(newArg); }else if(newPos.offset == save.offset){ cycles.insert(arg); }else{ newAlts.insert(newArg); } } cur.col = newPos.col; cur.line = newPos.line; cur.offset = newPos.offset; for(IValue arg : cycles.done()){ IValue newArg = addPosInfo((IConstructor) arg, filename, cur); newAlts.insert(newArg); } tree = tree.set("alternatives", newAlts.done()); }else if(!isCycle(tree)){ System.err.println("unhandled tree: " + tree + "\n"); } ISourceLocation loc; if (!filename.equals("-")) { loc = factory.sourceLocation(filename, startOffset, cur.offset - startOffset, startLine, cur.line, startCol, cur.col); } else { try { loc = factory.sourceLocation(new URI("console", null, "/", null), startOffset, cur.offset - startOffset, startLine, cur.line, startCol, cur.col); } catch (URISyntaxException e) { throw new ImplementationError("should always construct valid URI's", e); } } result = tree.setAnnotation(Factory.Location, loc); cache.putUnsafe(positionNode, result); return result; }
private IConstructor addPosInfo(IConstructor tree, String filename, Position cur) throws MalformedURLException{ IValueFactory factory = ValueFactoryFactory.getValueFactory(); int startLine = cur.line; int startCol = cur.col; int startOffset = cur.offset; PositionNode positionNode = new PositionNode(tree, cur.offset); IConstructor result = cache.get(positionNode); if(result != null){ ISourceLocation loc = getLocation(result); cur.col = loc.getEndColumn(); cur.line = loc.getEndLine(); cur.offset += loc.getLength(); return result; } if(isChar(tree)){ cur.offset++; if(((char) getCharacter(tree)) == '\n'){ cur.col = 0; cur.line++; }else{ cur.col++; } return tree; } if(isAppl(tree)){ boolean outermostLayout = false; IList args = getArgs(tree); if(isLayout(tree)){ inLayout = true; outermostLayout = true; } IListWriter newArgs = factory.listWriter(Factory.Tree); for(IValue arg : args){ newArgs.append(addPosInfo((IConstructor) arg, filename, cur)); } tree = tree.set("args", newArgs.done()); if(!labelLayout && outermostLayout){ inLayout = false; return tree; }else if(!labelLayout && inLayout){ return tree; } }else if(isAmb(tree)){ ISet alts = getAlternatives(tree); ISetWriter newAlts = ValueFactoryFactory.getValueFactory().setWriter(Factory.Tree); Position save = cur; Position newPos = save; ISetWriter cycles = ValueFactoryFactory.getValueFactory().setWriter(Factory.Tree); for(IValue arg : alts){ cur = save.clone(); IValue newArg = addPosInfo((IConstructor) arg, filename, cur); if(cur.offset != save.offset){ newPos = cur; newAlts.insert(newArg); }else if(newPos.offset == save.offset){ cycles.insert(arg); }else{ newAlts.insert(newArg); } } cur.col = newPos.col; cur.line = newPos.line; cur.offset = newPos.offset; for(IValue arg : cycles.done()){ IValue newArg = addPosInfo((IConstructor) arg, filename, cur); newAlts.insert(newArg); } tree = tree.set("alternatives", newAlts.done()); }else if(!isCycle(tree)){ System.err.println("unhandled tree: " + tree + "\n"); } ISourceLocation loc; if (!filename.equals("-")) { filename = filename.startsWith("/") ? filename : "./"+filename; // TODO Fix properly. loc = factory.sourceLocation(filename, startOffset, cur.offset - startOffset, startLine, cur.line, startCol, cur.col); } else { try { loc = factory.sourceLocation(new URI("console", null, "/", null), startOffset, cur.offset - startOffset, startLine, cur.line, startCol, cur.col); } catch (URISyntaxException e) { throw new ImplementationError("should always construct valid URI's", e); } } result = tree.setAnnotation(Factory.Location, loc); cache.putUnsafe(positionNode, result); return result; }
diff --git a/isoparser/src/main/java/com/googlecode/mp4parser/authoring/builder/SyncSampleIntersectFinderImpl.java b/isoparser/src/main/java/com/googlecode/mp4parser/authoring/builder/SyncSampleIntersectFinderImpl.java index 3f3f87b..842fe8a 100644 --- a/isoparser/src/main/java/com/googlecode/mp4parser/authoring/builder/SyncSampleIntersectFinderImpl.java +++ b/isoparser/src/main/java/com/googlecode/mp4parser/authoring/builder/SyncSampleIntersectFinderImpl.java @@ -1,67 +1,63 @@ /* * Copyright 2012 Sebastian Annies, Hamburg * * 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.googlecode.mp4parser.authoring.builder; import com.googlecode.mp4parser.authoring.Movie; import com.googlecode.mp4parser.authoring.Track; import java.util.Arrays; /** * This <code>FragmentIntersectionFinder</code> cuts the input movie exactly before * the sync samples. Each fragment starts with a sync sample. */ public class SyncSampleIntersectFinderImpl implements FragmentIntersectionFinder { public int[] sampleNumbers(Track track, Movie movie) { Track syncSampleContainingTrack = null; int syncSampleContainingTrackSampleCount = 0; long[] syncSamples = null; for (Track currentTrack : movie.getTracks()) { long[] currentTrackSyncSamples = currentTrack.getSyncSamples(); if (currentTrackSyncSamples != null && currentTrackSyncSamples.length > 0) { if (syncSampleContainingTrack == null || Arrays.equals(syncSamples, currentTrackSyncSamples)) { syncSampleContainingTrack = currentTrack; syncSampleContainingTrackSampleCount = currentTrack.getSamples().size(); syncSamples = currentTrackSyncSamples; } else { throw new RuntimeException("There is more than one track containing a Sync Sample Box but the algorithm cannot deal with it. What is the most important track?"); } } } if (syncSampleContainingTrack == null) { throw new RuntimeException("There was no track containing a Sync Sample Box but the Sync Sample Box is required to determine the fragment size."); } int[] chunkSizes = new int[syncSamples.length]; - if (track.getSamples().size() == 1) { - chunkSizes[0] = 0; - for (int i = 1; i < chunkSizes.length; i++) { - chunkSizes[i] = 1; - } - } else { - long sc = track.getSamples().size(); - double stretch = (double) sc / syncSampleContainingTrackSampleCount; - for (int i = 0; i < chunkSizes.length; i++) { - int start = (int) Math.round(stretch * (syncSamples[i] - 1)); - chunkSizes[i] = start; - // The Stretch makes sure that there are as much audio and video chunks! - } + long sc = track.getSamples().size(); + double stretch = (double) sc / syncSampleContainingTrackSampleCount; + chunkSizes[0] = 0; + for (int i = 1; i < chunkSizes.length; i++) { + int start = (int) Math.ceil(stretch * (syncSamples[i] - 1)); +// int round = (int) Math.round(stretch * (syncSamples[i] - 1)); + chunkSizes[i] = start; +// chunkSizes[i] = round; + // The Stretch makes sure that there are as much audio and video chunks! } return chunkSizes; } }
true
true
public int[] sampleNumbers(Track track, Movie movie) { Track syncSampleContainingTrack = null; int syncSampleContainingTrackSampleCount = 0; long[] syncSamples = null; for (Track currentTrack : movie.getTracks()) { long[] currentTrackSyncSamples = currentTrack.getSyncSamples(); if (currentTrackSyncSamples != null && currentTrackSyncSamples.length > 0) { if (syncSampleContainingTrack == null || Arrays.equals(syncSamples, currentTrackSyncSamples)) { syncSampleContainingTrack = currentTrack; syncSampleContainingTrackSampleCount = currentTrack.getSamples().size(); syncSamples = currentTrackSyncSamples; } else { throw new RuntimeException("There is more than one track containing a Sync Sample Box but the algorithm cannot deal with it. What is the most important track?"); } } } if (syncSampleContainingTrack == null) { throw new RuntimeException("There was no track containing a Sync Sample Box but the Sync Sample Box is required to determine the fragment size."); } int[] chunkSizes = new int[syncSamples.length]; if (track.getSamples().size() == 1) { chunkSizes[0] = 0; for (int i = 1; i < chunkSizes.length; i++) { chunkSizes[i] = 1; } } else { long sc = track.getSamples().size(); double stretch = (double) sc / syncSampleContainingTrackSampleCount; for (int i = 0; i < chunkSizes.length; i++) { int start = (int) Math.round(stretch * (syncSamples[i] - 1)); chunkSizes[i] = start; // The Stretch makes sure that there are as much audio and video chunks! } } return chunkSizes; }
public int[] sampleNumbers(Track track, Movie movie) { Track syncSampleContainingTrack = null; int syncSampleContainingTrackSampleCount = 0; long[] syncSamples = null; for (Track currentTrack : movie.getTracks()) { long[] currentTrackSyncSamples = currentTrack.getSyncSamples(); if (currentTrackSyncSamples != null && currentTrackSyncSamples.length > 0) { if (syncSampleContainingTrack == null || Arrays.equals(syncSamples, currentTrackSyncSamples)) { syncSampleContainingTrack = currentTrack; syncSampleContainingTrackSampleCount = currentTrack.getSamples().size(); syncSamples = currentTrackSyncSamples; } else { throw new RuntimeException("There is more than one track containing a Sync Sample Box but the algorithm cannot deal with it. What is the most important track?"); } } } if (syncSampleContainingTrack == null) { throw new RuntimeException("There was no track containing a Sync Sample Box but the Sync Sample Box is required to determine the fragment size."); } int[] chunkSizes = new int[syncSamples.length]; long sc = track.getSamples().size(); double stretch = (double) sc / syncSampleContainingTrackSampleCount; chunkSizes[0] = 0; for (int i = 1; i < chunkSizes.length; i++) { int start = (int) Math.ceil(stretch * (syncSamples[i] - 1)); // int round = (int) Math.round(stretch * (syncSamples[i] - 1)); chunkSizes[i] = start; // chunkSizes[i] = round; // The Stretch makes sure that there are as much audio and video chunks! } return chunkSizes; }
diff --git a/src/org/harleydroid/J1850.java b/src/org/harleydroid/J1850.java index 8c377cb..c27a916 100644 --- a/src/org/harleydroid/J1850.java +++ b/src/org/harleydroid/J1850.java @@ -1,186 +1,188 @@ // // HarleyDroid: Harley Davidson J1850 Data Analyser for Android. // // Copyright (C) 2010,2011 Stelian Pop <[email protected]> // Based on various sources, especially: // minigpsd by Tom Zerucha <[email protected]> // AVR J1850 VPW Interface by Michael Wolf <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // package org.harleydroid; public class J1850 { public static final int MAXBUF = 1024; // last reading of odometer ticks private static int odolast = 0; // accumulated odometer ticks (deals with overflow at 0xffff) private static int odoaccum = 0; // last reading of fuel ticks private static int fuellast = 0; // accumulated fuel ticks (deals with overflow at 0xffff) private static int fuelaccum = 0; static byte[] bytes_to_hex(byte[] in) { byte out[] = new byte[MAXBUF]; int inidx = 0, outidx = 0; while (inidx < in.length) { int digit0, digit1; while (inidx < in.length && Character.isWhitespace((char)in[inidx])) inidx++; if (inidx >= in.length) break; digit0 = Character.digit((char)in[inidx++], 16); while (inidx < in.length && Character.isWhitespace((char)in[inidx])) inidx++; if (inidx >= in.length) break; digit1 = Character.digit((char)in[inidx++], 16); out[outidx++] = (byte) (digit0 * 16 + digit1); } byte[] ret = new byte[outidx]; System.arraycopy(out, 0, ret, 0, outidx); return ret; } public static byte crc(byte[] in) { int i, j; byte crc = (byte)0xff; for (i = 0; i < in.length; i++) { byte c = in[i]; for (j = 0; j < 8; ++j) { byte poly = 0; if ((0x80 & (crc ^ c)) != 0) poly = 0x1d; crc = (byte) (((crc << 1) & 0xff) ^ poly); c <<= 1; } } return crc; } public static void parse(byte[] buffer, HarleyData hd) throws Exception { byte[] in; int x; int y; in = bytes_to_hex(buffer); /* System.out.print("BUF: "); for (int i = 0; i < in.length; i++) System.out.print(Integer.toHexString(in[i]) + " "); System.out.println(""); */ if (crc(in) != (byte)0xc4) throw new Exception("crc"); x = y = 0; if (in.length >= 4) x = ((in[0] << 24) & 0xff000000) | ((in[1] << 16) & 0x00ff0000) | ((in[2] << 8) & 0x0000ff00) | (in[3] & 0x000000ff); if (in.length >= 6) y = ((in[4] << 8) & 0x0000ff00) | (in[5] & 0x000000ff); if (x == 0x281b1002) hd.setRPM(y * 250); else if (x == 0x48291002) hd.setSpeed(y * 5); else if (x == 0xa8491010) hd.setEngineTemp(in[4]); else if (x == 0xa83b1003) { if (in[4] != 0) { int gear = 0; while ((in[4] >>= 1) != 0) gear++; hd.setGear(gear); } else hd.setGear(-1); } else if ((x == 0x48da4039) && ((in[4] & 0xfc) == 0)) hd.setTurnSignals(in[4] & 0x03); else if ((x & 0xffffff7f) == 0xa8691006) { odolast = y - odolast; if (odolast < 0) // ...could also test for (x & 0x80) odolast += 65536; odoaccum += odolast; odolast = y; hd.setOdometer(odoaccum); } else if ((x & 0xffffff7f) == 0xa883100a) { fuellast = y - fuellast; if (fuellast < 0) // ...could also test for (x & 0x80) fuellast += 65536; fuelaccum += fuellast; fuellast = y; hd.setFuel(fuelaccum); } else if ((x == 0xa8836112) && ((in[4] & 0xd0) == 0xd0)) hd.setFull(in[4] & 0x0f); else if ((x & 0xffffff5d) == 0x483b4000) { hd.setNeutral((in[3] & 0x20) != 0); hd.setClutch((in[3] & 0x80) != 0); - } else if (x == 0x68881003 || - x == 0x68ff1003 || + } else if (x == 0x68ff1003 || x == 0x68ff4003 || x == 0x68ff6103 || x == 0xc888100e || x == 0xc8896103 || x == 0xe889610e) { /* ping */ } else if ((x & 0xffffff7f) == 0x4892402a || (x & 0xffffff7f) == 0x6893612a) { /* shutdown - lock */ - } else if (x == 0x68881083) { - hd.setCheckEngine(true); + } else if ((x & 0xffffff7f) == 0x68881003) { + if ((in[3] & 0x80) != 0) + hd.setCheckEngine(true); + else + hd.setCheckEngine(false); } else throw new Exception("unknown"); } public static void main(String[] args) { // String line = "28 1B 10 02 00 00 D5"; // String line = "C8 88 10 0E BA "; // String line = "E8 89 61 0E 18 "; String line = "28 1B 10 02 10 74 4C"; byte[] in = line.getBytes(); for (int i = 0; i < in.length; i++) System.out.println("in[" + i + "] = " + in[i]); byte[] out = bytes_to_hex(in); for (int i = 0; i < out.length; i++) System.out.println("out[" + i + "] = " + out[i]); System.out.println("crc = " + crc(out)); try { HarleyData data = new HarleyData(); parse(in, data); System.out.println(data); } catch (Exception e) { e.printStackTrace(); } } }
false
true
public static void parse(byte[] buffer, HarleyData hd) throws Exception { byte[] in; int x; int y; in = bytes_to_hex(buffer); /* System.out.print("BUF: "); for (int i = 0; i < in.length; i++) System.out.print(Integer.toHexString(in[i]) + " "); System.out.println(""); */ if (crc(in) != (byte)0xc4) throw new Exception("crc"); x = y = 0; if (in.length >= 4) x = ((in[0] << 24) & 0xff000000) | ((in[1] << 16) & 0x00ff0000) | ((in[2] << 8) & 0x0000ff00) | (in[3] & 0x000000ff); if (in.length >= 6) y = ((in[4] << 8) & 0x0000ff00) | (in[5] & 0x000000ff); if (x == 0x281b1002) hd.setRPM(y * 250); else if (x == 0x48291002) hd.setSpeed(y * 5); else if (x == 0xa8491010) hd.setEngineTemp(in[4]); else if (x == 0xa83b1003) { if (in[4] != 0) { int gear = 0; while ((in[4] >>= 1) != 0) gear++; hd.setGear(gear); } else hd.setGear(-1); } else if ((x == 0x48da4039) && ((in[4] & 0xfc) == 0)) hd.setTurnSignals(in[4] & 0x03); else if ((x & 0xffffff7f) == 0xa8691006) { odolast = y - odolast; if (odolast < 0) // ...could also test for (x & 0x80) odolast += 65536; odoaccum += odolast; odolast = y; hd.setOdometer(odoaccum); } else if ((x & 0xffffff7f) == 0xa883100a) { fuellast = y - fuellast; if (fuellast < 0) // ...could also test for (x & 0x80) fuellast += 65536; fuelaccum += fuellast; fuellast = y; hd.setFuel(fuelaccum); } else if ((x == 0xa8836112) && ((in[4] & 0xd0) == 0xd0)) hd.setFull(in[4] & 0x0f); else if ((x & 0xffffff5d) == 0x483b4000) { hd.setNeutral((in[3] & 0x20) != 0); hd.setClutch((in[3] & 0x80) != 0); } else if (x == 0x68881003 || x == 0x68ff1003 || x == 0x68ff4003 || x == 0x68ff6103 || x == 0xc888100e || x == 0xc8896103 || x == 0xe889610e) { /* ping */ } else if ((x & 0xffffff7f) == 0x4892402a || (x & 0xffffff7f) == 0x6893612a) { /* shutdown - lock */ } else if (x == 0x68881083) { hd.setCheckEngine(true); } else throw new Exception("unknown"); }
public static void parse(byte[] buffer, HarleyData hd) throws Exception { byte[] in; int x; int y; in = bytes_to_hex(buffer); /* System.out.print("BUF: "); for (int i = 0; i < in.length; i++) System.out.print(Integer.toHexString(in[i]) + " "); System.out.println(""); */ if (crc(in) != (byte)0xc4) throw new Exception("crc"); x = y = 0; if (in.length >= 4) x = ((in[0] << 24) & 0xff000000) | ((in[1] << 16) & 0x00ff0000) | ((in[2] << 8) & 0x0000ff00) | (in[3] & 0x000000ff); if (in.length >= 6) y = ((in[4] << 8) & 0x0000ff00) | (in[5] & 0x000000ff); if (x == 0x281b1002) hd.setRPM(y * 250); else if (x == 0x48291002) hd.setSpeed(y * 5); else if (x == 0xa8491010) hd.setEngineTemp(in[4]); else if (x == 0xa83b1003) { if (in[4] != 0) { int gear = 0; while ((in[4] >>= 1) != 0) gear++; hd.setGear(gear); } else hd.setGear(-1); } else if ((x == 0x48da4039) && ((in[4] & 0xfc) == 0)) hd.setTurnSignals(in[4] & 0x03); else if ((x & 0xffffff7f) == 0xa8691006) { odolast = y - odolast; if (odolast < 0) // ...could also test for (x & 0x80) odolast += 65536; odoaccum += odolast; odolast = y; hd.setOdometer(odoaccum); } else if ((x & 0xffffff7f) == 0xa883100a) { fuellast = y - fuellast; if (fuellast < 0) // ...could also test for (x & 0x80) fuellast += 65536; fuelaccum += fuellast; fuellast = y; hd.setFuel(fuelaccum); } else if ((x == 0xa8836112) && ((in[4] & 0xd0) == 0xd0)) hd.setFull(in[4] & 0x0f); else if ((x & 0xffffff5d) == 0x483b4000) { hd.setNeutral((in[3] & 0x20) != 0); hd.setClutch((in[3] & 0x80) != 0); } else if (x == 0x68ff1003 || x == 0x68ff4003 || x == 0x68ff6103 || x == 0xc888100e || x == 0xc8896103 || x == 0xe889610e) { /* ping */ } else if ((x & 0xffffff7f) == 0x4892402a || (x & 0xffffff7f) == 0x6893612a) { /* shutdown - lock */ } else if ((x & 0xffffff7f) == 0x68881003) { if ((in[3] & 0x80) != 0) hd.setCheckEngine(true); else hd.setCheckEngine(false); } else throw new Exception("unknown"); }
diff --git a/src/test/ed/net/httpserver/ReplayTest.java b/src/test/ed/net/httpserver/ReplayTest.java index 173d45f43..24d04c5e6 100644 --- a/src/test/ed/net/httpserver/ReplayTest.java +++ b/src/test/ed/net/httpserver/ReplayTest.java @@ -1,28 +1,28 @@ // ReplayTest.java package ed.net.httpserver; import org.testng.annotations.Test; import ed.*; public class ReplayTest extends TestCase { @Test(groups = {"basic"}) public void testHeaders(){ - Replay r = new Replay( null , 0 , "www.shopwiki.com" ); + Replay r = new Replay( "foo" , 0 , "www.shopwiki.com" ); - assertEquals( "GET /\nConnection: close\nHost: www.shopwiki.com\n\n" , + assertEquals( "GET /\nConnection: close\nHost: www.shopwiki.com\nX-Replay: y\n\n" , r.fixHeaders( "GET /\nConnection: asd\nHost: asdasd\n\n" ) ); - assertEquals( "GET /\nConnection: close\nHost: www.shopwiki.com\nA: B\n\n" , + assertEquals( "GET /\nConnection: close\nHost: www.shopwiki.com\nA: B\nX-Replay: y\n\n" , r.fixHeaders( "GET /\nConnection: asd\nHost: asdasd\nA: B\n\n" ) ); - assertEquals( "GET /\nConnection: close\nHost: www.shopwiki.com\n\n" , + assertEquals( "GET /\nConnection: close\nHost: www.shopwiki.com\nX-Replay: y\n\n" , r.fixHeaders( "GET /\nConnection: asd\n\n" ) ); } public static void main( String args[] ){ (new ReplayTest()).runConsole(); } }
false
true
public void testHeaders(){ Replay r = new Replay( null , 0 , "www.shopwiki.com" ); assertEquals( "GET /\nConnection: close\nHost: www.shopwiki.com\n\n" , r.fixHeaders( "GET /\nConnection: asd\nHost: asdasd\n\n" ) ); assertEquals( "GET /\nConnection: close\nHost: www.shopwiki.com\nA: B\n\n" , r.fixHeaders( "GET /\nConnection: asd\nHost: asdasd\nA: B\n\n" ) ); assertEquals( "GET /\nConnection: close\nHost: www.shopwiki.com\n\n" , r.fixHeaders( "GET /\nConnection: asd\n\n" ) ); }
public void testHeaders(){ Replay r = new Replay( "foo" , 0 , "www.shopwiki.com" ); assertEquals( "GET /\nConnection: close\nHost: www.shopwiki.com\nX-Replay: y\n\n" , r.fixHeaders( "GET /\nConnection: asd\nHost: asdasd\n\n" ) ); assertEquals( "GET /\nConnection: close\nHost: www.shopwiki.com\nA: B\nX-Replay: y\n\n" , r.fixHeaders( "GET /\nConnection: asd\nHost: asdasd\nA: B\n\n" ) ); assertEquals( "GET /\nConnection: close\nHost: www.shopwiki.com\nX-Replay: y\n\n" , r.fixHeaders( "GET /\nConnection: asd\n\n" ) ); }
diff --git a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/AnonymousServiceFactory.java b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/AnonymousServiceFactory.java index e473b0666..78c18ec95 100644 --- a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/AnonymousServiceFactory.java +++ b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/AnonymousServiceFactory.java @@ -1,213 +1,219 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.synapse.core.axis2; import org.apache.axis2.AxisFault; import org.apache.axis2.wsdl.WSDLConstants; import org.apache.axis2.description.AxisService; import org.apache.axis2.description.AxisMessage; import org.apache.axis2.description.OutOnlyAxisOperation; import org.apache.axis2.description.AxisServiceGroup; import org.apache.axis2.engine.AxisConfiguration; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.synapse.ServerManager; import org.apache.synapse.SynapseConstants; import org.apache.synapse.SynapseException; import org.apache.synapse.config.SynapseConfiguration; import javax.xml.namespace.QName; /** * Returns an anonymous service for the given QoS. If an instance does not already * exist, create one and set it to the Axis configuration */ public class AnonymousServiceFactory { private static final Log log = LogFactory.getLog(AnonymousServiceFactory.class); private static final String NONE = "__NONE__"; private static final String ADDR_ONLY = "__ADDR_ONLY__"; private static final String SEC_ONLY = "__SEC_ONLY__"; private static final String RM_AND_ADDR = "__RM_AND_ADDR__"; private static final String SEC_AND_ADDR = "__SEC_AND_ADDR__"; private static final String RM_SEC_AND_ADDR = "__RM_SEC_AND_ADDR__"; public static final String OUT_IN_OPERATION = "anonOutInOp"; public static final String OUT_ONLY_OPERATION = "anonOutonlyOp"; private static SynapseCallbackReceiver synapseCallbackReceiver = null; /** * Creates an AxisService for the requested QoS for sending out messages * Callers must guarantee that if wsRMon or wsSecOn is required, that wsAddrOn is also set * @param synCfg Synapse configuration * @param axisCfg Axis2 configuration * @param wsAddrOn whether addressing is on or not * @param wsRMOn whether RM is on ot not * @param wsSecOn whether security is on or not * @return An Axis service for the requested QoS */ public static AxisService getAnonymousService(SynapseConfiguration synCfg, AxisConfiguration axisCfg, boolean wsAddrOn, boolean wsRMOn, boolean wsSecOn) { // if non of addressing, security and rm is engaged then checkbit is 0 int checkbit = 0; // if addressing is on increase the checkbit by 1 if (wsAddrOn) { checkbit += 1; } // if security is on increase the checkbit by 2 if (wsSecOn) { checkbit += 2; } // if reliable messaging is on increase the checkbit by 4 if (wsRMOn) { checkbit += 4; } String servicekey; switch (checkbit) { case 0 : servicekey = NONE; break; case 1 : servicekey = ADDR_ONLY; break; case 2 : servicekey = SEC_ONLY; break; case 3 : servicekey = SEC_AND_ADDR; break; - case 4 & 5 : + case 4 : servicekey = RM_AND_ADDR; break; - case 6 & 7 : + case 5 : + servicekey = RM_AND_ADDR; + break; + case 6: + servicekey = RM_SEC_AND_ADDR; + break; + case 7: servicekey = RM_SEC_AND_ADDR; break; default : servicekey = NONE; break; } try { AxisService service = axisCfg.getService(servicekey); if (service == null) { synchronized (AnonymousServiceFactory.class) { // fix with double locking, issue found on performance test service = axisCfg.getService(servicekey); if (service != null) { return service; } service = createAnonymousService(synCfg, axisCfg, servicekey); if (wsAddrOn) { service.engageModule(axisCfg.getModule( SynapseConstants.ADDRESSING_MODULE_NAME), axisCfg); if (wsRMOn) { service.engageModule(axisCfg.getModule( SynapseConstants.RM_MODULE_NAME), axisCfg); } } // if WS-A is off, WS-RM should be too if (wsSecOn) { service.engageModule(axisCfg.getModule( SynapseConstants.SECURITY_MODULE_NAME), axisCfg); } } } return service; } catch (AxisFault e) { handleException("Error retrieving anonymous service for QoS : " + servicekey, e); } return null; } private static void handleException(String msg, Exception e) { log.error(msg, e); throw new SynapseException(msg, e); } /** * Create a new Anonymous Axis service for OUT-IN as default MEP * @param synCfg the Synapse Configuration * @param axisCfg the Axis2 configuration * @param serviceKey key for the service * @return an anonymous service named with the given QoS key */ private static AxisService createAnonymousService(SynapseConfiguration synCfg, AxisConfiguration axisCfg, String serviceKey) { try { DynamicAxisOperation dynamicOperation = new DynamicAxisOperation(new QName(OUT_IN_OPERATION)); dynamicOperation.setMessageReceiver(getCallbackReceiver(synCfg)); AxisMessage inMsg = new AxisMessage(); inMsg.setName("in-message"); inMsg.setParent(dynamicOperation); AxisMessage outMsg = new AxisMessage(); outMsg.setName("out-message"); outMsg.setParent(dynamicOperation); dynamicOperation.addMessage(inMsg, WSDLConstants.MESSAGE_LABEL_OUT_VALUE); dynamicOperation.addMessage(outMsg, WSDLConstants.MESSAGE_LABEL_IN_VALUE); OutOnlyAxisOperation asyncOperation = new OutOnlyAxisOperation(new QName(OUT_ONLY_OPERATION)); asyncOperation.setMessageReceiver(getCallbackReceiver(synCfg)); AxisMessage outOnlyMsg = new AxisMessage(); outOnlyMsg.setName("out-message"); outOnlyMsg.setParent(asyncOperation); asyncOperation.addMessage(outMsg, WSDLConstants.MESSAGE_LABEL_OUT_VALUE); AxisService axisAnonymousService = new AxisService(serviceKey); axisAnonymousService.addOperation(dynamicOperation); axisAnonymousService.addOperation(asyncOperation); AxisServiceGroup axisAnonSvcGroup = new AxisServiceGroup(axisCfg); axisAnonSvcGroup.setServiceGroupName(serviceKey); axisAnonSvcGroup.addParameter(SynapseConstants.HIDDEN_SERVICE_PARAM, "true"); axisAnonymousService.setClientSide(true); axisAnonSvcGroup.addService(axisAnonymousService); axisCfg.addServiceGroup(axisAnonSvcGroup); axisCfg.getPhasesInfo().setOperationPhases(dynamicOperation); return axisAnonymousService; } catch (AxisFault e) { handleException( "Error occured while creating an anonymous service for QoS : " + serviceKey, e); } return null; } /** * Create a single callback receiver if required, and return its reference * @param synCfg the Synapse configuration * @return the callback receiver thats created or now exists */ private static synchronized SynapseCallbackReceiver getCallbackReceiver( SynapseConfiguration synCfg) { if (synapseCallbackReceiver == null) { synapseCallbackReceiver = new SynapseCallbackReceiver(synCfg); ServerManager.getInstance().setSynapseCallbackReceiver(synapseCallbackReceiver); } return synapseCallbackReceiver; } }
false
true
public static AxisService getAnonymousService(SynapseConfiguration synCfg, AxisConfiguration axisCfg, boolean wsAddrOn, boolean wsRMOn, boolean wsSecOn) { // if non of addressing, security and rm is engaged then checkbit is 0 int checkbit = 0; // if addressing is on increase the checkbit by 1 if (wsAddrOn) { checkbit += 1; } // if security is on increase the checkbit by 2 if (wsSecOn) { checkbit += 2; } // if reliable messaging is on increase the checkbit by 4 if (wsRMOn) { checkbit += 4; } String servicekey; switch (checkbit) { case 0 : servicekey = NONE; break; case 1 : servicekey = ADDR_ONLY; break; case 2 : servicekey = SEC_ONLY; break; case 3 : servicekey = SEC_AND_ADDR; break; case 4 & 5 : servicekey = RM_AND_ADDR; break; case 6 & 7 : servicekey = RM_SEC_AND_ADDR; break; default : servicekey = NONE; break; } try { AxisService service = axisCfg.getService(servicekey); if (service == null) { synchronized (AnonymousServiceFactory.class) { // fix with double locking, issue found on performance test service = axisCfg.getService(servicekey); if (service != null) { return service; } service = createAnonymousService(synCfg, axisCfg, servicekey); if (wsAddrOn) { service.engageModule(axisCfg.getModule( SynapseConstants.ADDRESSING_MODULE_NAME), axisCfg); if (wsRMOn) { service.engageModule(axisCfg.getModule( SynapseConstants.RM_MODULE_NAME), axisCfg); } } // if WS-A is off, WS-RM should be too if (wsSecOn) { service.engageModule(axisCfg.getModule( SynapseConstants.SECURITY_MODULE_NAME), axisCfg); } } } return service; } catch (AxisFault e) { handleException("Error retrieving anonymous service for QoS : " + servicekey, e); } return null; }
public static AxisService getAnonymousService(SynapseConfiguration synCfg, AxisConfiguration axisCfg, boolean wsAddrOn, boolean wsRMOn, boolean wsSecOn) { // if non of addressing, security and rm is engaged then checkbit is 0 int checkbit = 0; // if addressing is on increase the checkbit by 1 if (wsAddrOn) { checkbit += 1; } // if security is on increase the checkbit by 2 if (wsSecOn) { checkbit += 2; } // if reliable messaging is on increase the checkbit by 4 if (wsRMOn) { checkbit += 4; } String servicekey; switch (checkbit) { case 0 : servicekey = NONE; break; case 1 : servicekey = ADDR_ONLY; break; case 2 : servicekey = SEC_ONLY; break; case 3 : servicekey = SEC_AND_ADDR; break; case 4 : servicekey = RM_AND_ADDR; break; case 5 : servicekey = RM_AND_ADDR; break; case 6: servicekey = RM_SEC_AND_ADDR; break; case 7: servicekey = RM_SEC_AND_ADDR; break; default : servicekey = NONE; break; } try { AxisService service = axisCfg.getService(servicekey); if (service == null) { synchronized (AnonymousServiceFactory.class) { // fix with double locking, issue found on performance test service = axisCfg.getService(servicekey); if (service != null) { return service; } service = createAnonymousService(synCfg, axisCfg, servicekey); if (wsAddrOn) { service.engageModule(axisCfg.getModule( SynapseConstants.ADDRESSING_MODULE_NAME), axisCfg); if (wsRMOn) { service.engageModule(axisCfg.getModule( SynapseConstants.RM_MODULE_NAME), axisCfg); } } // if WS-A is off, WS-RM should be too if (wsSecOn) { service.engageModule(axisCfg.getModule( SynapseConstants.SECURITY_MODULE_NAME), axisCfg); } } } return service; } catch (AxisFault e) { handleException("Error retrieving anonymous service for QoS : " + servicekey, e); } return null; }
diff --git a/src/main/java/service/command/impl/DeleteLineCommand.java b/src/main/java/service/command/impl/DeleteLineCommand.java index 58b5eee..4dd0215 100644 --- a/src/main/java/service/command/impl/DeleteLineCommand.java +++ b/src/main/java/service/command/impl/DeleteLineCommand.java @@ -1,65 +1,66 @@ package service.command.impl; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; import model.configuration.Config; import service.AbstractSockectService; import service.StatusCodes; import service.command.ServiceCommand; public class DeleteLineCommand extends ServiceCommand { public DeleteLineCommand(AbstractSockectService owner) { super(owner); } @Override public void execute(String[] params) throws IOException { if (params.length < 2) { owner.echoLine(StatusCodes.ERR_INVALID_PARAMETERS_ARGUMENTS); return; } int lineNumberToRemove; try { lineNumberToRemove = Integer.valueOf(params[0]); } catch (NumberFormatException e) { owner.echoLine(StatusCodes.ERR_INVALID_PARAMETERS_NUMBER, "input: " + params[0]); return; } String fullPath = Config.getInstance().getConfigFullPath(params[1]); if (fullPath == null) { owner.echoLine(StatusCodes.ERR_INVALID_PARAMETERS_FILE); return; } StringBuilder text = getTextWithoutLine(fullPath, lineNumberToRemove); try { PrintWriter out = new PrintWriter(fullPath); out.print(text.toString()); out.close(); owner.echoLine(StatusCodes.OK_FILE_UPDATED); + Config.getInstance().update(params[1]); } catch (FileNotFoundException e) { // should never happen... e.printStackTrace(); } } public StringBuilder getTextWithoutLine(String fullPath, int lineNumber) throws IOException { StringBuilder modifiedFile = new StringBuilder(); Scanner scanner = new Scanner(new File(fullPath)); int currLine = 1; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (currLine != lineNumber) { modifiedFile.append(line + "\r\n"); } currLine++; } scanner.close(); return modifiedFile; } }
true
true
public void execute(String[] params) throws IOException { if (params.length < 2) { owner.echoLine(StatusCodes.ERR_INVALID_PARAMETERS_ARGUMENTS); return; } int lineNumberToRemove; try { lineNumberToRemove = Integer.valueOf(params[0]); } catch (NumberFormatException e) { owner.echoLine(StatusCodes.ERR_INVALID_PARAMETERS_NUMBER, "input: " + params[0]); return; } String fullPath = Config.getInstance().getConfigFullPath(params[1]); if (fullPath == null) { owner.echoLine(StatusCodes.ERR_INVALID_PARAMETERS_FILE); return; } StringBuilder text = getTextWithoutLine(fullPath, lineNumberToRemove); try { PrintWriter out = new PrintWriter(fullPath); out.print(text.toString()); out.close(); owner.echoLine(StatusCodes.OK_FILE_UPDATED); } catch (FileNotFoundException e) { // should never happen... e.printStackTrace(); } }
public void execute(String[] params) throws IOException { if (params.length < 2) { owner.echoLine(StatusCodes.ERR_INVALID_PARAMETERS_ARGUMENTS); return; } int lineNumberToRemove; try { lineNumberToRemove = Integer.valueOf(params[0]); } catch (NumberFormatException e) { owner.echoLine(StatusCodes.ERR_INVALID_PARAMETERS_NUMBER, "input: " + params[0]); return; } String fullPath = Config.getInstance().getConfigFullPath(params[1]); if (fullPath == null) { owner.echoLine(StatusCodes.ERR_INVALID_PARAMETERS_FILE); return; } StringBuilder text = getTextWithoutLine(fullPath, lineNumberToRemove); try { PrintWriter out = new PrintWriter(fullPath); out.print(text.toString()); out.close(); owner.echoLine(StatusCodes.OK_FILE_UPDATED); Config.getInstance().update(params[1]); } catch (FileNotFoundException e) { // should never happen... e.printStackTrace(); } }
diff --git a/generator/src/main/java/org/richfaces/cdk/xmlconfig/JAXBBinding.java b/generator/src/main/java/org/richfaces/cdk/xmlconfig/JAXBBinding.java index 619c1cb..ac78ff2 100644 --- a/generator/src/main/java/org/richfaces/cdk/xmlconfig/JAXBBinding.java +++ b/generator/src/main/java/org/richfaces/cdk/xmlconfig/JAXBBinding.java @@ -1,259 +1,259 @@ /* * $Id$ * * License Agreement. * * Rich Faces - Natural Ajax for Java Server Faces (JSF) * * Copyright (C) 2007 Exadel, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.richfaces.cdk.xmlconfig; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.Writer; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.bind.UnmarshallerHandler; import javax.xml.bind.util.ValidationEventCollector; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import org.apache.cocoon.pipeline.component.sax.XIncludeTransformer; import org.richfaces.cdk.CdkException; import org.richfaces.cdk.Logger; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.ext.EntityResolver2; import org.xml.sax.helpers.XMLReaderFactory; import com.google.common.collect.ImmutableSet; import com.google.inject.Inject; /** * <p class="changed_added_4_0"> * </p> * * @author [email protected] * */ public class JAXBBinding implements JAXB { public static final ImmutableSet<String> IGNORE_PROPERTIES = ImmutableSet.of("class", "extension"); private static final FacesConfigNamespacePreffixMapper PREFFIX_MAPPER = new FacesConfigNamespacePreffixMapper(); @Inject private EntityResolver2 resolver; @Inject private Logger log; public JAXBBinding() { } /* * (non-Javadoc) * * @see org.richfaces.cdk.xmlconfig.JAXB#unmarshal(java.io.File, java.lang.String, java.lang.Class) */ @Override public <T> T unmarshal(File file, String schemaLocation, Class<T> bindClass) throws CdkException, FileNotFoundException { InputSource input = new InputSource(new FileInputStream(file)); input.setSystemId(file.toURI().toString()); T unmarshal = unmarshal(schemaLocation, bindClass, input); return unmarshal; } /* * (non-Javadoc) * * @see org.richfaces.cdk.xmlconfig.JAXB#unmarshal(java.lang.String, java.lang.String, java.lang.Class) */ @Override public <T> T unmarshal(String url, String schemaLocation, Class<T> bindClass) throws CdkException, FileNotFoundException { try { InputSource inputSource; try { inputSource = resolver.resolveEntity(null, url); } catch (SAXException e) { inputSource = null; } if (null == inputSource) { inputSource = new InputSource(url); } T unmarshal = unmarshal(schemaLocation, bindClass, inputSource); return unmarshal; } catch (IOException e) { throw new FileNotFoundException("XML file not found at " + url); } } @SuppressWarnings("unchecked") // TODO nick - schemaLocation is unused <T> T unmarshal(String schemaLocation, Class<T> bindClass, InputSource inputSource) throws CdkException { T unmarshal = null; try { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(resolver); xmlReader.setFeature("http://xml.org/sax/features/validation", true); xmlReader.setFeature("http://apache.org/xml/features/validation/schema", true); xmlReader.setFeature("http://apache.org/xml/features/validation/dynamic", true); // Setup JAXB to unmarshal // TODO - create xinclude content handler that process xinclude directives // and send SAX event to the unmarshaller handler. Unmarshaller u = JAXBContext.newInstance(bindClass).createUnmarshaller(); u.setEventHandler(new ValidationEventCollector()); XIncludeTransformer xIncludeTransformer = new XIncludeTransformer(log); if (null != inputSource.getSystemId()) { xIncludeTransformer.setBaseUri(new URI(inputSource.getSystemId())); } UnmarshallerHandler unmarshallerHandler = u.getUnmarshallerHandler(); xIncludeTransformer.setContentHandler(unmarshallerHandler); xIncludeTransformer.setResolver(resolver); xmlReader.setContentHandler(xIncludeTransformer); xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", xIncludeTransformer); xmlReader.parse(inputSource); // turn off the JAXB provider's default validation mechanism to // avoid duplicate validation // u.setValidating(false); unmarshal = (T) unmarshallerHandler.getResult(); } catch (JAXBException e) { - throw new CdkException("JAXB Unmarshaller error", e); + throw new CdkException("JAXB Unmarshaller error: " + e.getMessage(), e); } catch (URISyntaxException e) { - throw new CdkException("Invalid XML source URI", e); + throw new CdkException("Invalid XML source URI: " + e.getMessage(), e); } catch (IOException e) { - throw new CdkException("JAXB Unmarshaller input error", e); + throw new CdkException("JAXB Unmarshaller input error: " + e.getMessage(), e); } catch (SAXException e) { - throw new CdkException("XML error", e); + throw new CdkException("XML error: " + e.getMessage(), e); } finally { // TODO Refactoring } return unmarshal; } /* * (non-Javadoc) * * @see org.richfaces.cdk.xmlconfig.JAXB#marshal(java.io.File, java.lang.String, T) */ @Override public <T> void marshal(Writer output, String schemaLocation, T model) throws CdkException { try { StreamResult result = new StreamResult(output); marshal(result, schemaLocation, model); output.flush(); output.close(); } catch (FileNotFoundException e) { throw new CdkException("File not found", e); } catch (IOException e) { throw new CdkException("XML file writting error", e); } } /* * (non-Javadoc) * * @see org.richfaces.cdk.xmlconfig.JAXB#marshal(javax.xml.transform.Result, java.lang.String, T) */ @Override public <T> void marshal(Result output, String schemaLocation, T model) throws CdkException { try { JAXBContext jc = JAXBContext.newInstance(model.getClass()); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE); // TODO - let writer to define additional schemes. // marshaller.setProperty("jaxb.schemaLocation", Boolean.TRUE); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); if (null != schemaLocation) { marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, schemaLocation); marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", PREFFIX_MAPPER); } marshaller.marshal(model, output); } catch (JAXBException e) { throw new CdkException("JAXB Marshaller error", e); } finally { // TODO Refactoring } } /** * <p class="changed_added_4_0"> * Close input source after parsing. * </p> * * @param source */ private void closeSource(Source source) { if (source instanceof SAXSource) { SAXSource saxSource = (SAXSource) source; InputSource inputSource = saxSource.getInputSource(); try { Reader stream = inputSource.getCharacterStream(); if (null != stream) { stream.close(); } else { InputStream byteStream = inputSource.getByteStream(); if (null != byteStream) { byteStream.close(); } } } catch (IOException e) { // Can be ignored because source has already been read. } } } public static boolean isCollections(Class<?> targetType, Object propertyValue) { return Collection.class.isAssignableFrom(targetType) && propertyValue instanceof Collection; } }
false
true
<T> T unmarshal(String schemaLocation, Class<T> bindClass, InputSource inputSource) throws CdkException { T unmarshal = null; try { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(resolver); xmlReader.setFeature("http://xml.org/sax/features/validation", true); xmlReader.setFeature("http://apache.org/xml/features/validation/schema", true); xmlReader.setFeature("http://apache.org/xml/features/validation/dynamic", true); // Setup JAXB to unmarshal // TODO - create xinclude content handler that process xinclude directives // and send SAX event to the unmarshaller handler. Unmarshaller u = JAXBContext.newInstance(bindClass).createUnmarshaller(); u.setEventHandler(new ValidationEventCollector()); XIncludeTransformer xIncludeTransformer = new XIncludeTransformer(log); if (null != inputSource.getSystemId()) { xIncludeTransformer.setBaseUri(new URI(inputSource.getSystemId())); } UnmarshallerHandler unmarshallerHandler = u.getUnmarshallerHandler(); xIncludeTransformer.setContentHandler(unmarshallerHandler); xIncludeTransformer.setResolver(resolver); xmlReader.setContentHandler(xIncludeTransformer); xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", xIncludeTransformer); xmlReader.parse(inputSource); // turn off the JAXB provider's default validation mechanism to // avoid duplicate validation // u.setValidating(false); unmarshal = (T) unmarshallerHandler.getResult(); } catch (JAXBException e) { throw new CdkException("JAXB Unmarshaller error", e); } catch (URISyntaxException e) { throw new CdkException("Invalid XML source URI", e); } catch (IOException e) { throw new CdkException("JAXB Unmarshaller input error", e); } catch (SAXException e) { throw new CdkException("XML error", e); } finally { // TODO Refactoring } return unmarshal; }
<T> T unmarshal(String schemaLocation, Class<T> bindClass, InputSource inputSource) throws CdkException { T unmarshal = null; try { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(resolver); xmlReader.setFeature("http://xml.org/sax/features/validation", true); xmlReader.setFeature("http://apache.org/xml/features/validation/schema", true); xmlReader.setFeature("http://apache.org/xml/features/validation/dynamic", true); // Setup JAXB to unmarshal // TODO - create xinclude content handler that process xinclude directives // and send SAX event to the unmarshaller handler. Unmarshaller u = JAXBContext.newInstance(bindClass).createUnmarshaller(); u.setEventHandler(new ValidationEventCollector()); XIncludeTransformer xIncludeTransformer = new XIncludeTransformer(log); if (null != inputSource.getSystemId()) { xIncludeTransformer.setBaseUri(new URI(inputSource.getSystemId())); } UnmarshallerHandler unmarshallerHandler = u.getUnmarshallerHandler(); xIncludeTransformer.setContentHandler(unmarshallerHandler); xIncludeTransformer.setResolver(resolver); xmlReader.setContentHandler(xIncludeTransformer); xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", xIncludeTransformer); xmlReader.parse(inputSource); // turn off the JAXB provider's default validation mechanism to // avoid duplicate validation // u.setValidating(false); unmarshal = (T) unmarshallerHandler.getResult(); } catch (JAXBException e) { throw new CdkException("JAXB Unmarshaller error: " + e.getMessage(), e); } catch (URISyntaxException e) { throw new CdkException("Invalid XML source URI: " + e.getMessage(), e); } catch (IOException e) { throw new CdkException("JAXB Unmarshaller input error: " + e.getMessage(), e); } catch (SAXException e) { throw new CdkException("XML error: " + e.getMessage(), e); } finally { // TODO Refactoring } return unmarshal; }
diff --git a/kie-internal/src/main/java/org/kie/internal/utils/ServiceRegistryImpl.java b/kie-internal/src/main/java/org/kie/internal/utils/ServiceRegistryImpl.java index fdd0b058..61b7e3d9 100644 --- a/kie-internal/src/main/java/org/kie/internal/utils/ServiceRegistryImpl.java +++ b/kie-internal/src/main/java/org/kie/internal/utils/ServiceRegistryImpl.java @@ -1,253 +1,253 @@ /* * Copyright 2010 JBoss 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. */ /* * 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.kie.internal.utils; import org.kie.api.KieServices; import org.kie.api.Service; import org.kie.api.builder.KieScanner; import org.kie.api.concurrent.KieExecutors; import org.kie.api.marshalling.KieMarshallers; import org.kie.api.persistence.jpa.KieStoreServices; import org.kie.internal.process.CorrelationKeyFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; /** * This is an internal class, not for public consumption. */ public class ServiceRegistryImpl implements ServiceRegistry { private static final ServiceRegistry instance = new ServiceRegistryImpl(); protected static final transient Logger logger = LoggerFactory.getLogger( ServiceRegistryImpl.class ); private final Map<String, Callable< ? >> registry = new HashMap<String, Callable< ? >>(); private final Map<String, Callable< ? >> defaultServices = new HashMap<String, Callable< ? >>(); public static synchronized ServiceRegistry getInstance() { return instance; } public ServiceRegistryImpl() { init(); } /* (non-Javadoc) * @see org.kie.util.internal.ServiceRegistry#registerLocator(java.lang.String, java.util.concurrent.Callable) */ public synchronized void registerLocator(Class cls, Callable cal) { this.registry.put( cls.getName(), cal ); } /* (non-Javadoc) * @see org.kie.util.internal.ServiceRegistry#unregisterLocator(java.lang.String) */ public synchronized void unregisterLocator(Class cls) { this.registry.remove( cls.getName() ); } synchronized void registerInstance(Service service, Map map) { //this.context.getProperties().put( "org.dr, value ) logger.info( "regInstance : " + map ); String[] values = (String[]) map.get( "objectClass" ); for ( String v : values ) { logger.info( v ); } // logger.info( "register : " + service ); this.registry.put( service.getClass().getInterfaces()[0].getName(), new ReturnInstance<Service>( service ) ); // // BundleContext bc = this.context.getBundleContext(); // ServiceReference confAdminRef = bc.getServiceReference( ConfigurationAdmin.class.getName() ); // ConfigurationAdmin admin = ( ConfigurationAdmin ) bc.getService( confAdminRef ); // // try { // Configuration conf = admin.getConfiguration( (String) confAdminRef.getProperty( "service.id" ) ); // Dictionary properties = conf.getProperties(); // properties.put( values[0], "true" ); // conf.update( properties ); // } catch ( IOException e ) { // logger.error("error", e); // } } /* (non-Javadoc) * @see org.kie.util.internal.ServiceRegistry#unregisterLocator(java.lang.String) */ synchronized void unregisterInstance(Service service, Map map) { logger.info( "unregister : " + map ); String name = service.getClass().getInterfaces()[0].getName(); this.registry.remove( name ); this.registry.put( name, this.defaultServices.get( name ) ); } // ConfigurationAdmin confAdmin; // synchronized void setConfigurationAdmin(ConfigurationAdmin confAdmin) { // this.confAdmin = confAdmin; // logger.info( "ConfAdmin : " + this.confAdmin ); // } // // synchronized void unsetConfigurationAdmin(ConfigurationAdmin confAdmin) { // this.confAdmin = null; // } // private ComponentContext context; // void activate(ComponentContext context) { // logger.info( "reg comp" + context.getProperties() ); // this.context = context; // // // // BundleContext bc = this.context.getBundleContext(); // // ServiceReference confAdminRef = bc.getServiceReference( ConfigurationAdmin.class.getName() ); // ConfigurationAdmin admin = ( ConfigurationAdmin ) bc.getService( confAdminRef ); // logger.info( "conf admin : " + admin ); // //context. // // log = (LogService) context.locateService("LOG"); // } // void deactivate(ComponentContext context ){ // // } public synchronized <T> T get(Class<T> cls) { Callable< ? > cal = this.registry.get( cls.getName() ); if ( cal != null ) { try { return cls.cast( cal.call() ); } catch ( Exception e ) { throw new IllegalArgumentException( "Unable to instantiate service for Class '" + (cls != null ? cls.getName() : null) + "'", e ); } } else { cal = this.defaultServices.get( cls.getName() ); try { return cls.cast( cal.call() ); } catch ( Exception e ) { throw new IllegalArgumentException( "Unable to instantiate service for Class '" + (cls != null ? cls.getName() : null) + "'", e ); } } } private void init() { addDefault( "org.kie.internal.builder.KnowledgeBuilderFactoryService", "org.drools.compiler.builder.impl.KnowledgeBuilderFactoryServiceImpl" ); addDefault( "org.kie.api.builder.KnowledgeContainerFactoryService", "org.drools.core.builder.impl.KnowledgeContainerFactoryServiceImpl" ); addDefault( "org.kie.internal.KnowledgeBaseFactoryService", "org.drools.core.impl.KnowledgeBaseFactoryServiceImpl" ); addDefault( "org.kie.internal.io.ResourceFactoryService", "org.drools.core.io.impl.ResourceFactoryServiceImpl" ); addDefault( "org.kie.internal.SystemEventListenerService", "org.drools.core.impl.SystemEventListenerServiceImpl" ); addDefault( KieMarshallers.class, "org.drools.core.marshalling.impl.MarshallerProviderImpl"); addDefault( KieExecutors.class, "org.drools.core.concurrent.ExecutorProviderImpl"); addDefault( KieServices.class, "org.drools.compiler.kie.builder.impl.KieServicesImpl"); addDefault( KieScanner.class, - "org.drools.scanner.KieRepositoryScannerImpl"); + "org.kie.scanner.KieRepositoryScannerImpl"); addDefault( KieStoreServices.class, "org.drools.persistence.jpa.KnowledgeStoreServiceImpl"); addDefault( CorrelationKeyFactory.class, "org.jbpm.persistence.correlation.JPACorrelationKeyFactory"); } public synchronized void addDefault(Class cls, String impl) { addDefault(cls.getName(), impl); } private synchronized void addDefault(String service, String impl) { ReflectionInstantiator<Service> resourceRi = new ReflectionInstantiator<Service>( impl ); defaultServices.put( service, resourceRi ); } static class ReflectionInstantiator<V> implements Callable<V> { private final String name; public ReflectionInstantiator(String name) { this.name = name; } public V call() throws Exception { return (V) newInstance( name ); } static <T> T newInstance(String name) { try { Class<T> cls = (Class<T>) Class.forName( name ); return cls.newInstance(); } catch ( Exception e2 ) { throw new IllegalArgumentException( "Unable to instantiate '" + name + "'", e2 ); } } } static class ReturnInstance<V> implements Callable<V> { private final Service service; public ReturnInstance(Service service) { this.service = service; } public V call() throws Exception { return (V) service; } } }
true
true
private void init() { addDefault( "org.kie.internal.builder.KnowledgeBuilderFactoryService", "org.drools.compiler.builder.impl.KnowledgeBuilderFactoryServiceImpl" ); addDefault( "org.kie.api.builder.KnowledgeContainerFactoryService", "org.drools.core.builder.impl.KnowledgeContainerFactoryServiceImpl" ); addDefault( "org.kie.internal.KnowledgeBaseFactoryService", "org.drools.core.impl.KnowledgeBaseFactoryServiceImpl" ); addDefault( "org.kie.internal.io.ResourceFactoryService", "org.drools.core.io.impl.ResourceFactoryServiceImpl" ); addDefault( "org.kie.internal.SystemEventListenerService", "org.drools.core.impl.SystemEventListenerServiceImpl" ); addDefault( KieMarshallers.class, "org.drools.core.marshalling.impl.MarshallerProviderImpl"); addDefault( KieExecutors.class, "org.drools.core.concurrent.ExecutorProviderImpl"); addDefault( KieServices.class, "org.drools.compiler.kie.builder.impl.KieServicesImpl"); addDefault( KieScanner.class, "org.drools.scanner.KieRepositoryScannerImpl"); addDefault( KieStoreServices.class, "org.drools.persistence.jpa.KnowledgeStoreServiceImpl"); addDefault( CorrelationKeyFactory.class, "org.jbpm.persistence.correlation.JPACorrelationKeyFactory"); }
private void init() { addDefault( "org.kie.internal.builder.KnowledgeBuilderFactoryService", "org.drools.compiler.builder.impl.KnowledgeBuilderFactoryServiceImpl" ); addDefault( "org.kie.api.builder.KnowledgeContainerFactoryService", "org.drools.core.builder.impl.KnowledgeContainerFactoryServiceImpl" ); addDefault( "org.kie.internal.KnowledgeBaseFactoryService", "org.drools.core.impl.KnowledgeBaseFactoryServiceImpl" ); addDefault( "org.kie.internal.io.ResourceFactoryService", "org.drools.core.io.impl.ResourceFactoryServiceImpl" ); addDefault( "org.kie.internal.SystemEventListenerService", "org.drools.core.impl.SystemEventListenerServiceImpl" ); addDefault( KieMarshallers.class, "org.drools.core.marshalling.impl.MarshallerProviderImpl"); addDefault( KieExecutors.class, "org.drools.core.concurrent.ExecutorProviderImpl"); addDefault( KieServices.class, "org.drools.compiler.kie.builder.impl.KieServicesImpl"); addDefault( KieScanner.class, "org.kie.scanner.KieRepositoryScannerImpl"); addDefault( KieStoreServices.class, "org.drools.persistence.jpa.KnowledgeStoreServiceImpl"); addDefault( CorrelationKeyFactory.class, "org.jbpm.persistence.correlation.JPACorrelationKeyFactory"); }
diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java b/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java index a4524ca..8712531 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java @@ -1,67 +1,68 @@ package com.earth2me.essentials.commands; import org.bukkit.Server; import org.bukkit.command.CommandSender; import com.earth2me.essentials.Essentials; import com.earth2me.essentials.User; public class Commandtogglejail extends EssentialsCommand { public Commandtogglejail() { super("togglejail"); } @Override public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception { if (args.length < 1 || args.length > 2) { sender.sendMessage("Usage: /" + commandLabel + " [player] [jailname]"); return; } User p; try { p = User.get(server.matchPlayer(args[0]).get(0)); } catch (Exception ex) { sender.sendMessage("§cThat player does not exist."); return; } if (p.isOp() || p.isAuthorized("essentials.jail.exempt")) { sender.sendMessage("§cYou may not jail that person"); return; } if (args.length == 2 && !p.isJailed()) { User.charge(sender, this); sender.sendMessage("§7Player " + p.getName() + " " + (p.toggleJailed() ? "jailed." : "unjailed.")); p.sendMessage("§7You have been jailed"); + p.currentJail = null; Essentials.getJail().sendToJail(p, args[1]); p.currentJail = (args[1]); return; } if (args.length == 2 && p.isJailed() && !args[1].equalsIgnoreCase(p.currentJail)) { sender.sendMessage("§cPerson is already in jail "+ p.currentJail); return; } if (args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase(p.currentJail))) { if (!p.isJailed()) { sender.sendMessage("Usage: /" + commandLabel + " [player] [jailname]"); return; } sender.sendMessage("§7Player " + p.getName() + " " + (p.toggleJailed() ? "jailed." : "unjailed.")); p.sendMessage("§7You have been released"); p.currentJail = ""; p.teleportBack(); } } }
true
true
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception { if (args.length < 1 || args.length > 2) { sender.sendMessage("Usage: /" + commandLabel + " [player] [jailname]"); return; } User p; try { p = User.get(server.matchPlayer(args[0]).get(0)); } catch (Exception ex) { sender.sendMessage("§cThat player does not exist."); return; } if (p.isOp() || p.isAuthorized("essentials.jail.exempt")) { sender.sendMessage("§cYou may not jail that person"); return; } if (args.length == 2 && !p.isJailed()) { User.charge(sender, this); sender.sendMessage("§7Player " + p.getName() + " " + (p.toggleJailed() ? "jailed." : "unjailed.")); p.sendMessage("§7You have been jailed"); Essentials.getJail().sendToJail(p, args[1]); p.currentJail = (args[1]); return; } if (args.length == 2 && p.isJailed() && !args[1].equalsIgnoreCase(p.currentJail)) { sender.sendMessage("§cPerson is already in jail "+ p.currentJail); return; } if (args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase(p.currentJail))) { if (!p.isJailed()) { sender.sendMessage("Usage: /" + commandLabel + " [player] [jailname]"); return; } sender.sendMessage("§7Player " + p.getName() + " " + (p.toggleJailed() ? "jailed." : "unjailed.")); p.sendMessage("§7You have been released"); p.currentJail = ""; p.teleportBack(); } }
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception { if (args.length < 1 || args.length > 2) { sender.sendMessage("Usage: /" + commandLabel + " [player] [jailname]"); return; } User p; try { p = User.get(server.matchPlayer(args[0]).get(0)); } catch (Exception ex) { sender.sendMessage("§cThat player does not exist."); return; } if (p.isOp() || p.isAuthorized("essentials.jail.exempt")) { sender.sendMessage("§cYou may not jail that person"); return; } if (args.length == 2 && !p.isJailed()) { User.charge(sender, this); sender.sendMessage("§7Player " + p.getName() + " " + (p.toggleJailed() ? "jailed." : "unjailed.")); p.sendMessage("§7You have been jailed"); p.currentJail = null; Essentials.getJail().sendToJail(p, args[1]); p.currentJail = (args[1]); return; } if (args.length == 2 && p.isJailed() && !args[1].equalsIgnoreCase(p.currentJail)) { sender.sendMessage("§cPerson is already in jail "+ p.currentJail); return; } if (args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase(p.currentJail))) { if (!p.isJailed()) { sender.sendMessage("Usage: /" + commandLabel + " [player] [jailname]"); return; } sender.sendMessage("§7Player " + p.getName() + " " + (p.toggleJailed() ? "jailed." : "unjailed.")); p.sendMessage("§7You have been released"); p.currentJail = ""; p.teleportBack(); } }
diff --git a/Scrapper/src/SampleScrapper.java b/Scrapper/src/SampleScrapper.java index 2df064e..2c7117d 100644 --- a/Scrapper/src/SampleScrapper.java +++ b/Scrapper/src/SampleScrapper.java @@ -1,247 +1,256 @@ import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class SampleScrapper { static List<PlayerRecord> twentyTwo = new ArrayList<PlayerRecord>(); static ConvertDAO dao = new ConvertDAO(); public static void main(String[] args) throws Exception { System.out.println("Enter Cricinfo Match Scorecard URL: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Document doc = Jsoup.connect(br.readLine()).get(); Element inningsBat1 = doc.getElementById("inningsBat1"); Elements inningsRow = inningsBat1.getElementsByClass("inningsRow"); int count = addtoList(inningsRow); Elements inningsTable = doc.getElementsByClass("inningsTable");//max of 3 for each team + boolean firstInningsAllout = true; if(count!=11) + { addDNB(inningsTable.get(1)); + firstInningsAllout= false; + } //11 players of team 1 added by now Element inningsBat2 = doc.getElementById("inningsBat2"); inningsRow = inningsBat2.getElementsByClass("inningsRow"); count = addtoList(inningsRow); if(count!=11) - addDNB(inningsTable.get(5)); + { + if(!firstInningsAllout) + addDNB(inningsTable.get(5)); + else + addDNB(inningsTable.get(4)); + } //dismissal inningsRow = inningsBat1.getElementsByClass("inningsRow"); for (int i=0;i<inningsRow.size()-2;i++) { Element batsman = inningsRow.get(i); Elements battingDismissal = batsman.getElementsByClass("battingDismissal"); updateDismissal(battingDismissal.text(),i); } inningsRow = inningsBat2.getElementsByClass("inningsRow"); for (int i=0;i<inningsRow.size()-2;i++) { Element batsman = inningsRow.get(i); Elements battingDismissal = batsman.getElementsByClass("battingDismissal"); updateDismissal(battingDismissal.text(),i+11); } //bowling Element inningsBowl1 = doc.getElementById("inningsBowl1"); inningsRow = inningsBowl1.getElementsByClass("inningsRow"); updateBowlingFigures(inningsRow); Element inningsBowl2 = doc.getElementById("inningsBowl2"); inningsRow = inningsBowl2.getElementsByClass("inningsRow"); updateBowlingFigures(inningsRow); System.out.println("\n\n"); for(int i=0;i<twentyTwo.size();i++) { twentyTwo.get(i).print(); System.out.println(); } } private static void updateBowlingFigures(Elements inningsRow) { for (int i=0;i<inningsRow.size();i++) { int bowlingDetails[] = new int[5]; Element bowler = inningsRow.get(i); Elements bowlerName = bowler.getElementsByTag("a"); int tempID = lookupIDUnder22(bowlerName.text()); Elements bowlDetails = bowler.getElementsByClass("bowlingDetails"); float oversBowled = Float.parseFloat(bowlDetails.get(0).text()); bowlingDetails[0] = Integer.parseInt(bowlDetails.get(1).text());//maidens bowlingDetails[1] = Integer.parseInt(bowlDetails.get(2).text());//R bowlingDetails[2] = Integer.parseInt(bowlDetails.get(3).text());//W String input = bowlDetails.get(5).text(); if(!input.equals("")) { input=input.replaceAll("\\(", ""); input=input.replaceAll("\\)", ""); String[] extra = input.split(", "); if(extra.length>1) { extra[0]=extra[0].replace("nb", ""); bowlingDetails[4]=Integer.parseInt(extra[0]); extra[1]=extra[1].replace("w", ""); bowlingDetails[3]=Integer.parseInt(extra[1]); } else { if(extra[0].contains("w")) { extra[0]=extra[0].replace("w", ""); bowlingDetails[3]=Integer.parseInt(extra[0]); } else { extra[0]=extra[0].replace("nb", ""); bowlingDetails[4]=Integer.parseInt(extra[0]); } } } twentyTwo.get(tempID).oversBowled= oversBowled; twentyTwo.get(tempID).bowlingDetails=bowlingDetails; } } private static int lookupIDUnder22(String text) { for(int i=0;i<twentyTwo.size();i++) { PlayerRecord pr = twentyTwo.get(i); if(pr.playerName.contains(text)) return i; } return -1; } private static void updateDismissal(String input,int i) { String[] dismissal = input.split(" ", 2); String[] nextSplit; int tempID; switch(dismissal[0]) { case "run" : //TODO : how to handle this? twentyTwo.get(i).dismissal="runout"; incRunouts(dismissal[1]); break; case "not" : twentyTwo.get(i).dismissal="NO"; break; case "lbw" : twentyTwo.get(i).dismissal="lbw"; nextSplit = dismissal[1].split("b "); tempID=lookupPlayerIDInMatch(nextSplit[0]); twentyTwo.get(i).wicketTaker = tempID; break; case "st" : twentyTwo.get(i).dismissal="stumped"; nextSplit = dismissal[1].split(" b "); tempID=lookupPlayerIDInMatch(nextSplit[1]); incStumpings(nextSplit[0].replaceFirst("�", "")); twentyTwo.get(i).wicketTaker = tempID; break; case "c" : //handle '&' twentyTwo.get(i).dismissal="caught"; nextSplit = dismissal[1].split(" b "); if(nextSplit[0].equals("&")) incCatches(nextSplit[1]); else incCatches(nextSplit[0].replaceFirst("�", "")); tempID=lookupPlayerIDInMatch(nextSplit[1]); twentyTwo.get(i).wicketTaker = tempID; break; case "b" : twentyTwo.get(i).dismissal="bowled"; tempID=lookupPlayerIDInMatch(dismissal[1]); twentyTwo.get(i).wicketTaker = tempID; break; } } private static void incRunouts(String input) { input=input.replaceAll("\\(", ""); input=input.replaceAll("\\)", ""); input=input.replaceAll("out ", ""); String[] runout = input.split("/"); for(int i=0;i<runout.length;i++) { int tempID = lookupIDUnder22(runout[i].replaceFirst("�", "")); twentyTwo.get(tempID).runouts++; } } private static void incCatches(String string) { for(int i=0;i<twentyTwo.size();i++) { PlayerRecord pr = twentyTwo.get(i); if(pr.playerName.contains(string)) pr.catches++; } } private static void incStumpings(String string) { for(int i=0;i<twentyTwo.size();i++) { PlayerRecord pr = twentyTwo.get(i); if(pr.playerName.contains(string)) pr.stumps++; } } private static int lookupPlayerIDInMatch(String string) { for(int i=0;i<twentyTwo.size();i++) { PlayerRecord pr = twentyTwo.get(i); if(pr.playerName.contains(string)) return pr.playerID; } return -1; } private static void addDNB(Element dNB) { Elements inningsDetails = dNB.getElementsByTag("a"); for(int i=0;i<inningsDetails.size();i++) { PlayerRecord player = new PlayerRecord(); // System.out.println(inningsDetails.get(i).text()); player.playerName = inningsDetails.get(i).text(); player.playerID = dao.lookupID(player.playerName); twentyTwo.add(player); } } private static int addtoList(Elements inningsRow) { int count=0; for (int i=0;i<inningsRow.size()-2;i++) { count++; Element batsman = inningsRow.get(i); PlayerRecord player = new PlayerRecord(); Elements batsmanName = batsman.getElementsByTag("a"); Elements wKC = batsman.getElementsByClass("playerName"); if(wKC.get(0).text().contains("*")) player.isCap=true; if(wKC.get(0).text().contains("�")) player.isWK=true; player.playerName = batsmanName.text(); player.playerID = dao.lookupID(player.playerName); Elements runDetails = batsman.getElementsByClass("battingRuns"); int runs[] = new int[5]; runs[0] = Integer.parseInt(runDetails.get(0).text()); runDetails = batsman.getElementsByClass("battingDetails"); runs[1] = Integer.parseInt(runDetails.get(0).text()); runs[2] = Integer.parseInt(runDetails.get(1).text()); runs[3] = Integer.parseInt(runDetails.get(2).text()); runs[4] = Integer.parseInt(runDetails.get(3).text()); player.runDetails=runs; twentyTwo.add(player); } return count; } }
false
true
public static void main(String[] args) throws Exception { System.out.println("Enter Cricinfo Match Scorecard URL: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Document doc = Jsoup.connect(br.readLine()).get(); Element inningsBat1 = doc.getElementById("inningsBat1"); Elements inningsRow = inningsBat1.getElementsByClass("inningsRow"); int count = addtoList(inningsRow); Elements inningsTable = doc.getElementsByClass("inningsTable");//max of 3 for each team if(count!=11) addDNB(inningsTable.get(1)); //11 players of team 1 added by now Element inningsBat2 = doc.getElementById("inningsBat2"); inningsRow = inningsBat2.getElementsByClass("inningsRow"); count = addtoList(inningsRow); if(count!=11) addDNB(inningsTable.get(5)); //dismissal inningsRow = inningsBat1.getElementsByClass("inningsRow"); for (int i=0;i<inningsRow.size()-2;i++) { Element batsman = inningsRow.get(i); Elements battingDismissal = batsman.getElementsByClass("battingDismissal"); updateDismissal(battingDismissal.text(),i); } inningsRow = inningsBat2.getElementsByClass("inningsRow"); for (int i=0;i<inningsRow.size()-2;i++) { Element batsman = inningsRow.get(i); Elements battingDismissal = batsman.getElementsByClass("battingDismissal"); updateDismissal(battingDismissal.text(),i+11); } //bowling Element inningsBowl1 = doc.getElementById("inningsBowl1"); inningsRow = inningsBowl1.getElementsByClass("inningsRow"); updateBowlingFigures(inningsRow); Element inningsBowl2 = doc.getElementById("inningsBowl2"); inningsRow = inningsBowl2.getElementsByClass("inningsRow"); updateBowlingFigures(inningsRow); System.out.println("\n\n"); for(int i=0;i<twentyTwo.size();i++) { twentyTwo.get(i).print(); System.out.println(); } }
public static void main(String[] args) throws Exception { System.out.println("Enter Cricinfo Match Scorecard URL: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Document doc = Jsoup.connect(br.readLine()).get(); Element inningsBat1 = doc.getElementById("inningsBat1"); Elements inningsRow = inningsBat1.getElementsByClass("inningsRow"); int count = addtoList(inningsRow); Elements inningsTable = doc.getElementsByClass("inningsTable");//max of 3 for each team boolean firstInningsAllout = true; if(count!=11) { addDNB(inningsTable.get(1)); firstInningsAllout= false; } //11 players of team 1 added by now Element inningsBat2 = doc.getElementById("inningsBat2"); inningsRow = inningsBat2.getElementsByClass("inningsRow"); count = addtoList(inningsRow); if(count!=11) { if(!firstInningsAllout) addDNB(inningsTable.get(5)); else addDNB(inningsTable.get(4)); } //dismissal inningsRow = inningsBat1.getElementsByClass("inningsRow"); for (int i=0;i<inningsRow.size()-2;i++) { Element batsman = inningsRow.get(i); Elements battingDismissal = batsman.getElementsByClass("battingDismissal"); updateDismissal(battingDismissal.text(),i); } inningsRow = inningsBat2.getElementsByClass("inningsRow"); for (int i=0;i<inningsRow.size()-2;i++) { Element batsman = inningsRow.get(i); Elements battingDismissal = batsman.getElementsByClass("battingDismissal"); updateDismissal(battingDismissal.text(),i+11); } //bowling Element inningsBowl1 = doc.getElementById("inningsBowl1"); inningsRow = inningsBowl1.getElementsByClass("inningsRow"); updateBowlingFigures(inningsRow); Element inningsBowl2 = doc.getElementById("inningsBowl2"); inningsRow = inningsBowl2.getElementsByClass("inningsRow"); updateBowlingFigures(inningsRow); System.out.println("\n\n"); for(int i=0;i<twentyTwo.size();i++) { twentyTwo.get(i).print(); System.out.println(); } }
diff --git a/android/org.daum.library.android.sitac/src/main/java/org/daum/library/android/sitac/SITACEngine.java b/android/org.daum.library.android.sitac/src/main/java/org/daum/library/android/sitac/SITACEngine.java index 34f16e3..e00f52b 100644 --- a/android/org.daum.library.android.sitac/src/main/java/org/daum/library/android/sitac/SITACEngine.java +++ b/android/org.daum.library.android.sitac/src/main/java/org/daum/library/android/sitac/SITACEngine.java @@ -1,190 +1,190 @@ package org.daum.library.android.sitac; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import org.daum.common.genmodel.impl.*; import org.daum.library.android.sitac.engine.IEngine; import org.daum.library.android.sitac.listener.OnEngineStateChangeListener; import org.daum.library.ormH.persistence.PersistenceConfiguration; import org.daum.library.ormH.persistence.PersistenceSession; import org.daum.library.ormH.persistence.PersistenceSessionFactoryImpl; import org.daum.library.ormH.store.ReplicaStore; import org.daum.library.ormH.utils.PersistenceException; import android.util.Log; import org.daum.library.replica.listener.PropertyChangeEvent; import org.daum.library.replica.listener.PropertyChangeListener; import org.daum.library.replica.listener.SyncListener; import org.daum.library.replica.msg.SyncEvent; import org.daum.common.genmodel.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * SITACEngine save/update/delete data from/to the Replica/Persistence system */ public class SITACEngine implements IEngine { private static final String TAG = "SITACEngine"; private static final Logger logger = LoggerFactory.getLogger(SITACEngine.class); /** Persisted classes in replica */ private final Class[] classes = { VehiculeImpl.class, ArrowActionImpl.class, ZoneActionImpl.class, CibleImpl.class, SourceDangerImpl.class, AgentImpl.class }; private PersistenceSessionFactoryImpl factory; private OnEngineStateChangeListener listener; public SITACEngine(final String nodeName, ReplicaStore store) { try { // configuring persistence PersistenceConfiguration configuration = new PersistenceConfiguration(nodeName); configuration.setStore(store); for (Class c : classes) configuration.addPersistentClass(c); // retrieve the persistence factory this.factory = configuration.getPersistenceSessionFactory(); } catch (PersistenceException ex) { Log.e(TAG, "Error while initializing persistence in engine", ex); } // add a callback to populate engine when sync is ready SITACComponent.getChangeListenerInstance().addSyncListener(new SyncListener() { @Override public void sync(SyncEvent e) { if (listener != null) { PersistenceSession session = null; try { session = factory.getSession(); ArrayList<IModel> data = new ArrayList<IModel>(); for (Class c : classes) { Map<String, IModel> map = session.getAll(c); if (map != null && !map.isEmpty()) { data.addAll(map.values()); } } listener.onReplicaSynced(data); } catch (PersistenceException ex) { Log.e(TAG, "Error while retrieving data on sync", ex); } finally { if (session != null) session.close(); } } } }); // add callback to handle remote events on replica for (final Class c : classes) { SITACComponent.getChangeListenerInstance().addEventListener(c, new PropertyChangeListener() { @Override public void update(PropertyChangeEvent e) { if (listener != null) { PersistenceSession session = null; try { session = factory.getSession(); IModel m = null; switch (e.getEvent()) { case ADD: m = (IModel) session.get(c, e.getId()); - logger.debug(TAG, "Replica Event: ADD "+m); + logger.debug(TAG+ " Replica Event: ADD "+m); listener.onAdd(m); break; case DELETE: - logger.debug(TAG, "Replica Event: DELETE "+e.getId()); + logger.debug(TAG+" Replica Event: DELETE "+e.getId()); listener.onDelete((String) e.getId()); break; case UPDATE: m = (IModel) session.get(c, e.getId()); - logger.debug(TAG, "Replica Event: UPDATE "+m); + logger.debug(TAG+ " Replica Event: UPDATE "+m); listener.onUpdate(m); break; } } catch (PersistenceException ex) { Log.e(TAG, "Error while initializing replica events handler", ex); } finally { if (session != null) session.close(); } } } }); } } public void add(IModel m) { PersistenceSession session = null; try { session = factory.getSession(); session.save(m); } catch (PersistenceException ex) { Log.e(TAG, "Error while adding object in Replica", ex); } finally { if (session != null) session.close(); } } public void update(IModel m) { PersistenceSession session = null; try { session = factory.getSession(); session.update(m); } catch (PersistenceException ex) { Log.e(TAG, "Error while updating object in Replica", ex); } finally { if (session != null) session.close(); } } public void updateAll() { PersistenceSession session = null; try { session = factory.getSession(); ArrayList<IModel> data = new ArrayList<IModel>(); for (Class c : classes) { Map<Object, IModel> map = session.getAll(c); if (map != null && !map.isEmpty()) { data.addAll(map.values()); } } if (listener != null) listener.onUpdateAll(data); } catch (PersistenceException ex) { Log.e(TAG, "Error while updating object in Replica", ex); } finally { if (session != null) session.close(); } } public void delete(IModel m) { PersistenceSession session = null; try { session = factory.getSession(); session.delete(m); } catch (PersistenceException ex) { Log.e(TAG, "Error while deleting object in Replica", ex); } finally { if (session != null) session.close(); } } public void setHandler(OnEngineStateChangeListener handler) { this.listener = handler; updateAll(); } }
false
true
public SITACEngine(final String nodeName, ReplicaStore store) { try { // configuring persistence PersistenceConfiguration configuration = new PersistenceConfiguration(nodeName); configuration.setStore(store); for (Class c : classes) configuration.addPersistentClass(c); // retrieve the persistence factory this.factory = configuration.getPersistenceSessionFactory(); } catch (PersistenceException ex) { Log.e(TAG, "Error while initializing persistence in engine", ex); } // add a callback to populate engine when sync is ready SITACComponent.getChangeListenerInstance().addSyncListener(new SyncListener() { @Override public void sync(SyncEvent e) { if (listener != null) { PersistenceSession session = null; try { session = factory.getSession(); ArrayList<IModel> data = new ArrayList<IModel>(); for (Class c : classes) { Map<String, IModel> map = session.getAll(c); if (map != null && !map.isEmpty()) { data.addAll(map.values()); } } listener.onReplicaSynced(data); } catch (PersistenceException ex) { Log.e(TAG, "Error while retrieving data on sync", ex); } finally { if (session != null) session.close(); } } } }); // add callback to handle remote events on replica for (final Class c : classes) { SITACComponent.getChangeListenerInstance().addEventListener(c, new PropertyChangeListener() { @Override public void update(PropertyChangeEvent e) { if (listener != null) { PersistenceSession session = null; try { session = factory.getSession(); IModel m = null; switch (e.getEvent()) { case ADD: m = (IModel) session.get(c, e.getId()); logger.debug(TAG, "Replica Event: ADD "+m); listener.onAdd(m); break; case DELETE: logger.debug(TAG, "Replica Event: DELETE "+e.getId()); listener.onDelete((String) e.getId()); break; case UPDATE: m = (IModel) session.get(c, e.getId()); logger.debug(TAG, "Replica Event: UPDATE "+m); listener.onUpdate(m); break; } } catch (PersistenceException ex) { Log.e(TAG, "Error while initializing replica events handler", ex); } finally { if (session != null) session.close(); } } } }); } }
public SITACEngine(final String nodeName, ReplicaStore store) { try { // configuring persistence PersistenceConfiguration configuration = new PersistenceConfiguration(nodeName); configuration.setStore(store); for (Class c : classes) configuration.addPersistentClass(c); // retrieve the persistence factory this.factory = configuration.getPersistenceSessionFactory(); } catch (PersistenceException ex) { Log.e(TAG, "Error while initializing persistence in engine", ex); } // add a callback to populate engine when sync is ready SITACComponent.getChangeListenerInstance().addSyncListener(new SyncListener() { @Override public void sync(SyncEvent e) { if (listener != null) { PersistenceSession session = null; try { session = factory.getSession(); ArrayList<IModel> data = new ArrayList<IModel>(); for (Class c : classes) { Map<String, IModel> map = session.getAll(c); if (map != null && !map.isEmpty()) { data.addAll(map.values()); } } listener.onReplicaSynced(data); } catch (PersistenceException ex) { Log.e(TAG, "Error while retrieving data on sync", ex); } finally { if (session != null) session.close(); } } } }); // add callback to handle remote events on replica for (final Class c : classes) { SITACComponent.getChangeListenerInstance().addEventListener(c, new PropertyChangeListener() { @Override public void update(PropertyChangeEvent e) { if (listener != null) { PersistenceSession session = null; try { session = factory.getSession(); IModel m = null; switch (e.getEvent()) { case ADD: m = (IModel) session.get(c, e.getId()); logger.debug(TAG+ " Replica Event: ADD "+m); listener.onAdd(m); break; case DELETE: logger.debug(TAG+" Replica Event: DELETE "+e.getId()); listener.onDelete((String) e.getId()); break; case UPDATE: m = (IModel) session.get(c, e.getId()); logger.debug(TAG+ " Replica Event: UPDATE "+m); listener.onUpdate(m); break; } } catch (PersistenceException ex) { Log.e(TAG, "Error while initializing replica events handler", ex); } finally { if (session != null) session.close(); } } } }); } }
diff --git a/src/com/taboozle/Turn.java b/src/com/taboozle/Turn.java index 91a2bdb..6183d80 100644 --- a/src/com/taboozle/Turn.java +++ b/src/com/taboozle/Turn.java @@ -1,346 +1,346 @@ package com.taboozle; import java.util.ArrayList; import java.util.StringTokenizer; import android.app.*; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.animation.Animation; import android.view.animation.OvershootInterpolator; import android.view.animation.TranslateAnimation; import android.database.Cursor; import android.media.AudioManager; import android.media.SoundPool; import android.os.Bundle; import android.os.CountDownTimer; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import android.widget.ViewFlipper; /** * This handles a single turn consisting of cards presented to a player for a * limited amount of time. * * @author The Taboozle Team */ public class Turn extends Activity { /** * Small private class for representing the card in memory as strings */ private class CardStrings { public String title; public ArrayList<String> badWords; public CardStrings() { title = ""; badWords = new ArrayList<String>(); } } /** * A variable-length list of cards for in-memory storage */ protected ArrayList<CardStrings> Deck; /** * An integer to keep track of where we are */ protected int DeckPosition; /** * Boolean to track which views are currently active */ protected boolean AIsActive; /** * Sound pool for playing the buzz sound on a loop. */ protected SoundPool soundPool; protected int buzzSoundId; protected int buzzStreamId; /** * Unique IDs for Options menu */ protected static final int MENU_ENDGAME = 0; protected static final int MENU_SCORE = 1; protected static final int MENU_RULES = 2; /** * Creates the menu items */ public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, MENU_ENDGAME, 0, "End Game"); menu.add(0, MENU_SCORE, 0, "Score"); menu.add(0, MENU_RULES, 0, "Rules"); return true; } /** * OnClickListener for the buzzer button */ private OnTouchListener BuzzListener = new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { AudioManager mgr = (AudioManager) v.getContext().getSystemService( Context.AUDIO_SERVICE ); float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC); float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC); float volume = streamVolumeCurrent / streamVolumeMax; boolean ret = false; if( event.getAction() == MotionEvent.ACTION_DOWN ) { buzzStreamId = soundPool.play( buzzSoundId, volume, volume, 1, -1, 1.0f ); ret = true; } else if( event.getAction() == MotionEvent.ACTION_UP) { soundPool.stop( buzzStreamId ); ret = true; } else { ret = false; } return ret; } }; /** * constant for the logging tag */ //private static final String TAG = "taboozle"; private Animation InFromRightAnimation () { Animation inFromRight = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, 1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f ); inFromRight.setDuration(2000); inFromRight.setInterpolator(new OvershootInterpolator(1)); return inFromRight; } private Animation OutToLeftAnimation () { Animation outToLeft = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f ); outToLeft.setDuration(2000); outToLeft.setInterpolator(new OvershootInterpolator(1)); return outToLeft; } /** * Function for changing the currently viewed card. It does a bit of bounds * checking. */ protected void ShowCard() { if( this.DeckPosition >= this.Deck.size() || this.DeckPosition < 0 ) { this.DeckPosition = 0; } int curTitle = 0; int curWords = 0; if( this.AIsActive ) { curTitle = R.id.CardTitleA; curWords = R.id.CardWordsA; } else { curTitle = R.id.CardTitleB; curWords = R.id.CardWordsB; } TextView cardTitle = (TextView) this.findViewById( curTitle ); ListView cardWords = (ListView) this.findViewById( curWords ); // Disable the ListView to prevent its children from being clickable cardWords.setEnabled(false); ArrayAdapter<String> cardAdapter = new ArrayAdapter<String>( this, R.layout.word ); CardStrings curCard = this.Deck.get( this.DeckPosition ); cardTitle.setText( curCard.title ); for( int i = 0; i < curCard.badWords.size(); i++ ) { cardAdapter.add( curCard.badWords.get( i ) ); } cardWords.setAdapter( cardAdapter ); } private OnClickListener CorrectListener = new OnClickListener() { public void onClick(View v) { AIsActive = !AIsActive; ViewFlipper flipper = (ViewFlipper) findViewById( R.id.ViewFlipper0 ); flipper.showNext(); DeckPosition++; ShowCard(); } }; private OnClickListener SkipListener = new OnClickListener() { public void onClick(View v) { AIsActive = !AIsActive; ViewFlipper flipper = (ViewFlipper) findViewById( R.id.ViewFlipper0 ); flipper.showNext(); DeckPosition--; if( DeckPosition < 0 ) { DeckPosition = Deck.size()-1; } ShowCard(); } }; /** * CountdownTimer - This initializes a timer during every turn that runs a * method when it completes as well as during update intervals. */ public class TurnTimer extends CountDownTimer { public TurnTimer(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); } @Override public void onFinish() { OnTurnEnd(); } @Override public void onTick(long millisUntilFinished) { TextView countdownTxt = (TextView) findViewById( R.id.Timer ); countdownTxt.setText( Long.toString(( millisUntilFinished / 1000 ) + 1 )); } }; /** * OnTurnEnd - Hands off the intent to the next turn summary activity. */ protected void OnTurnEnd( ) { //Stop the sound if someone had the buzzer held down soundPool.stop( buzzStreamId ); Intent newintent = new Intent( this, TurnSummary.class); startActivity(newintent); } /** * onCreate - initializes the activity to display the word you have to cause * your team mates to say with the words you cannot say below. */ @Override public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); this.Deck = new ArrayList<CardStrings>(); this.DeckPosition = 0; this.AIsActive = true; this.soundPool = new SoundPool( 4, AudioManager.STREAM_MUSIC, 100 ); this.buzzSoundId = this.soundPool.load( this, R.raw.buzzer, 1 ); // Setup the view this.setContentView(R.layout.turn ); ViewFlipper flipper = (ViewFlipper) this.findViewById( R.id.ViewFlipper0 ); flipper.setInAnimation(InFromRightAnimation()); flipper.setOutAnimation(OutToLeftAnimation()); // If no data was given in the intent (because we were started // as a MAIN activity), then use our default content provider. Intent intent = this.getIntent(); if( intent.getData() == null ) { intent.setData( GameData.Cards.CONTENT_URI ); } // Add content to our content provider ContentResolver resolver = this.getContentResolver(); // Form an array specifying which columns to return. String[] projection = new String[] { GameData.Cards.TITLE, GameData.Cards.BAD_WORDS }; // Query and print the added card record Cursor cur = resolver.query( GameData.Cards.CONTENT_URI, projection, null, null, null ); // Iterate through cursor transferring from database to memory if( cur.moveToFirst() ) { int titleColumn = cur.getColumnIndex( GameData.Cards.TITLE ); int badWordsColumn = cur.getColumnIndex( GameData.Cards.BAD_WORDS ); do { // Get the field values String title = cur.getString( titleColumn ); String badWords = cur.getString( badWordsColumn ); StringTokenizer tok = new StringTokenizer(badWords); CardStrings cWords = new CardStrings(); cWords.title = title; while( tok.hasMoreTokens() ) { - cWords.badWords.add( tok.nextToken( "," ) ); + cWords.badWords.add( tok.nextToken( "," ).toUpperCase() ); } this.Deck.add( cWords ); } while( cur.moveToNext() ); } this.ShowCard(); TurnTimer counter = new TurnTimer( 10000, 200); counter.start(); ImageButton buzzerButton = (ImageButton)this.findViewById( R.id.BuzzerButtonA ); buzzerButton.setOnTouchListener( BuzzListener ); buzzerButton = (ImageButton)this.findViewById( R.id.BuzzerButtonB ); buzzerButton.setOnTouchListener( BuzzListener ); ImageButton nextButton = (ImageButton)this.findViewById( R.id.CorrectButtonA ); nextButton.setOnClickListener( CorrectListener ); nextButton = (ImageButton)this.findViewById( R.id.CorrectButtonB ); nextButton.setOnClickListener( CorrectListener ); Button skipButton = (Button)this.findViewById( R.id.SkipButtonA ); skipButton.setOnClickListener( SkipListener ); skipButton = (Button)this.findViewById( R.id.SkipButtonB ); skipButton.setOnClickListener( SkipListener ); } }
true
true
public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); this.Deck = new ArrayList<CardStrings>(); this.DeckPosition = 0; this.AIsActive = true; this.soundPool = new SoundPool( 4, AudioManager.STREAM_MUSIC, 100 ); this.buzzSoundId = this.soundPool.load( this, R.raw.buzzer, 1 ); // Setup the view this.setContentView(R.layout.turn ); ViewFlipper flipper = (ViewFlipper) this.findViewById( R.id.ViewFlipper0 ); flipper.setInAnimation(InFromRightAnimation()); flipper.setOutAnimation(OutToLeftAnimation()); // If no data was given in the intent (because we were started // as a MAIN activity), then use our default content provider. Intent intent = this.getIntent(); if( intent.getData() == null ) { intent.setData( GameData.Cards.CONTENT_URI ); } // Add content to our content provider ContentResolver resolver = this.getContentResolver(); // Form an array specifying which columns to return. String[] projection = new String[] { GameData.Cards.TITLE, GameData.Cards.BAD_WORDS }; // Query and print the added card record Cursor cur = resolver.query( GameData.Cards.CONTENT_URI, projection, null, null, null ); // Iterate through cursor transferring from database to memory if( cur.moveToFirst() ) { int titleColumn = cur.getColumnIndex( GameData.Cards.TITLE ); int badWordsColumn = cur.getColumnIndex( GameData.Cards.BAD_WORDS ); do { // Get the field values String title = cur.getString( titleColumn ); String badWords = cur.getString( badWordsColumn ); StringTokenizer tok = new StringTokenizer(badWords); CardStrings cWords = new CardStrings(); cWords.title = title; while( tok.hasMoreTokens() ) { cWords.badWords.add( tok.nextToken( "," ) ); } this.Deck.add( cWords ); } while( cur.moveToNext() ); } this.ShowCard(); TurnTimer counter = new TurnTimer( 10000, 200); counter.start(); ImageButton buzzerButton = (ImageButton)this.findViewById( R.id.BuzzerButtonA ); buzzerButton.setOnTouchListener( BuzzListener ); buzzerButton = (ImageButton)this.findViewById( R.id.BuzzerButtonB ); buzzerButton.setOnTouchListener( BuzzListener ); ImageButton nextButton = (ImageButton)this.findViewById( R.id.CorrectButtonA ); nextButton.setOnClickListener( CorrectListener ); nextButton = (ImageButton)this.findViewById( R.id.CorrectButtonB ); nextButton.setOnClickListener( CorrectListener ); Button skipButton = (Button)this.findViewById( R.id.SkipButtonA ); skipButton.setOnClickListener( SkipListener ); skipButton = (Button)this.findViewById( R.id.SkipButtonB ); skipButton.setOnClickListener( SkipListener ); }
public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); this.Deck = new ArrayList<CardStrings>(); this.DeckPosition = 0; this.AIsActive = true; this.soundPool = new SoundPool( 4, AudioManager.STREAM_MUSIC, 100 ); this.buzzSoundId = this.soundPool.load( this, R.raw.buzzer, 1 ); // Setup the view this.setContentView(R.layout.turn ); ViewFlipper flipper = (ViewFlipper) this.findViewById( R.id.ViewFlipper0 ); flipper.setInAnimation(InFromRightAnimation()); flipper.setOutAnimation(OutToLeftAnimation()); // If no data was given in the intent (because we were started // as a MAIN activity), then use our default content provider. Intent intent = this.getIntent(); if( intent.getData() == null ) { intent.setData( GameData.Cards.CONTENT_URI ); } // Add content to our content provider ContentResolver resolver = this.getContentResolver(); // Form an array specifying which columns to return. String[] projection = new String[] { GameData.Cards.TITLE, GameData.Cards.BAD_WORDS }; // Query and print the added card record Cursor cur = resolver.query( GameData.Cards.CONTENT_URI, projection, null, null, null ); // Iterate through cursor transferring from database to memory if( cur.moveToFirst() ) { int titleColumn = cur.getColumnIndex( GameData.Cards.TITLE ); int badWordsColumn = cur.getColumnIndex( GameData.Cards.BAD_WORDS ); do { // Get the field values String title = cur.getString( titleColumn ); String badWords = cur.getString( badWordsColumn ); StringTokenizer tok = new StringTokenizer(badWords); CardStrings cWords = new CardStrings(); cWords.title = title; while( tok.hasMoreTokens() ) { cWords.badWords.add( tok.nextToken( "," ).toUpperCase() ); } this.Deck.add( cWords ); } while( cur.moveToNext() ); } this.ShowCard(); TurnTimer counter = new TurnTimer( 10000, 200); counter.start(); ImageButton buzzerButton = (ImageButton)this.findViewById( R.id.BuzzerButtonA ); buzzerButton.setOnTouchListener( BuzzListener ); buzzerButton = (ImageButton)this.findViewById( R.id.BuzzerButtonB ); buzzerButton.setOnTouchListener( BuzzListener ); ImageButton nextButton = (ImageButton)this.findViewById( R.id.CorrectButtonA ); nextButton.setOnClickListener( CorrectListener ); nextButton = (ImageButton)this.findViewById( R.id.CorrectButtonB ); nextButton.setOnClickListener( CorrectListener ); Button skipButton = (Button)this.findViewById( R.id.SkipButtonA ); skipButton.setOnClickListener( SkipListener ); skipButton = (Button)this.findViewById( R.id.SkipButtonB ); skipButton.setOnClickListener( SkipListener ); }
diff --git a/AE-go_GameServer/src/com/aionemu/gameserver/network/aion/serverpackets/SM_EMOTION.java b/AE-go_GameServer/src/com/aionemu/gameserver/network/aion/serverpackets/SM_EMOTION.java index a7306b61..676a8406 100644 --- a/AE-go_GameServer/src/com/aionemu/gameserver/network/aion/serverpackets/SM_EMOTION.java +++ b/AE-go_GameServer/src/com/aionemu/gameserver/network/aion/serverpackets/SM_EMOTION.java @@ -1,171 +1,171 @@ /* * This file is part of aion-emu <aion-emu.com>. * * aion-emu 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. * * aion-emu 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 aion-emu. If not, see <http://www.gnu.org/licenses/>. */ package com.aionemu.gameserver.network.aion.serverpackets; import java.nio.ByteBuffer; import org.apache.log4j.Logger; import com.aionemu.gameserver.network.aion.AionConnection; import com.aionemu.gameserver.network.aion.AionServerPacket; /** * Emotion packet * * @author SoulKeeper */ public class SM_EMOTION extends AionServerPacket { private static final Logger log = Logger.getLogger(SM_EMOTION.class); /** * Object id of emotion sender */ private int senderObjectId; /** * Some unknown variable */ private int unknown; /** * ID of emotion */ private int emotionId; /** * Constructs new server packet with specified opcode * * @param senderObjectId * who sended emotion * @param unknown * Dunno what it is, can be 0x10 or 0x11 * @param emotionId * emotion to play */ public SM_EMOTION(int senderObjectId, int unknown, int emotionId) { this.senderObjectId = senderObjectId; this.emotionId = emotionId; this.unknown = unknown; } /** * {@inheritDoc} */ @Override protected void writeImpl(AionConnection con, ByteBuffer buf) { writeD(buf, senderObjectId); writeC(buf, unknown); if (unknown == 13 ){ //emote die writeD(buf, 0x07); // unknown writeC(buf, 0xC0); // unknown writeC(buf, 0x40); // unknown writeD(buf, emotionId); } else if (unknown == 6 ) { // fly writeC(buf, 0x02); // unknown writeC(buf, 0x00); // unknown writeC(buf, 0x00); // unknown writeC(buf, 0x00); // unknown writeH(buf, 16576); // unsure about this - verteron has 16656, akarios 16576 - writeH(buf, emotionId); // teleport Id + writeD(buf, emotionId); // teleport Id writeC(buf, 0x00); // unknown writeC(buf, 0x00); // unknown } else if (unknown == 35 ) { //emote startloop writeD(buf, 44); // unknown writeC(buf, 0xc0); // unknown writeC(buf, 0x40); // unknown } else if (unknown == 30 ) { //emote startloop writeD(buf, 33); // unknown writeC(buf, 0xe0); // unknown writeC(buf, 0x40); // unknown writeH(buf, 2142); // unknown writeH(buf, 2142); // unknown } else if (unknown == 19 ) { //emote startloop writeD(buf, 1); // unknown writeC(buf, 0xe0); // unknown writeC(buf, 0x40); // unknown } else if (unknown == 36 ) { //emote endloop writeD(buf, 33); // unknown writeC(buf, 0xc0); // unknown writeC(buf, 0x40); // unknown } else if (unknown == 0x16)//Run { writeC(buf, 0x01); writeC(buf, 0x00); writeH(buf, 0x00); writeC(buf, 0xC0); writeC(buf, 0x40); } else if (unknown == 0x15)//Walk { writeC(buf, 0x41); writeC(buf, 0x00); writeH(buf, 0x00); writeC(buf, 0xC0); writeC(buf, 0x3F); } else if (unknown == 0x20) //? { writeC(buf, 0x01); writeC(buf, 0x00); writeH(buf, 0x00); writeC(buf, 0x00); writeC(buf, 0x40); } else { writeC(buf, 0x01); // unknown writeC(buf, 0x00); // unknown writeH(buf, 0x00); // unknown writeC(buf, 0xC0); // unknown writeC(buf, 0x40); // unknown } if(unknown == 0x10) { writeD(buf, 0x00); // unknown writeH(buf, emotionId); writeC(buf, 0x01); // unknown } } }
true
true
protected void writeImpl(AionConnection con, ByteBuffer buf) { writeD(buf, senderObjectId); writeC(buf, unknown); if (unknown == 13 ){ //emote die writeD(buf, 0x07); // unknown writeC(buf, 0xC0); // unknown writeC(buf, 0x40); // unknown writeD(buf, emotionId); } else if (unknown == 6 ) { // fly writeC(buf, 0x02); // unknown writeC(buf, 0x00); // unknown writeC(buf, 0x00); // unknown writeC(buf, 0x00); // unknown writeH(buf, 16576); // unsure about this - verteron has 16656, akarios 16576 writeH(buf, emotionId); // teleport Id writeC(buf, 0x00); // unknown writeC(buf, 0x00); // unknown } else if (unknown == 35 ) { //emote startloop writeD(buf, 44); // unknown writeC(buf, 0xc0); // unknown writeC(buf, 0x40); // unknown } else if (unknown == 30 ) { //emote startloop writeD(buf, 33); // unknown writeC(buf, 0xe0); // unknown writeC(buf, 0x40); // unknown writeH(buf, 2142); // unknown writeH(buf, 2142); // unknown } else if (unknown == 19 ) { //emote startloop writeD(buf, 1); // unknown writeC(buf, 0xe0); // unknown writeC(buf, 0x40); // unknown } else if (unknown == 36 ) { //emote endloop writeD(buf, 33); // unknown writeC(buf, 0xc0); // unknown writeC(buf, 0x40); // unknown } else if (unknown == 0x16)//Run { writeC(buf, 0x01); writeC(buf, 0x00); writeH(buf, 0x00); writeC(buf, 0xC0); writeC(buf, 0x40); } else if (unknown == 0x15)//Walk { writeC(buf, 0x41); writeC(buf, 0x00); writeH(buf, 0x00); writeC(buf, 0xC0); writeC(buf, 0x3F); } else if (unknown == 0x20) //? { writeC(buf, 0x01); writeC(buf, 0x00); writeH(buf, 0x00); writeC(buf, 0x00); writeC(buf, 0x40); } else { writeC(buf, 0x01); // unknown writeC(buf, 0x00); // unknown writeH(buf, 0x00); // unknown writeC(buf, 0xC0); // unknown writeC(buf, 0x40); // unknown } if(unknown == 0x10) { writeD(buf, 0x00); // unknown writeH(buf, emotionId); writeC(buf, 0x01); // unknown } }
protected void writeImpl(AionConnection con, ByteBuffer buf) { writeD(buf, senderObjectId); writeC(buf, unknown); if (unknown == 13 ){ //emote die writeD(buf, 0x07); // unknown writeC(buf, 0xC0); // unknown writeC(buf, 0x40); // unknown writeD(buf, emotionId); } else if (unknown == 6 ) { // fly writeC(buf, 0x02); // unknown writeC(buf, 0x00); // unknown writeC(buf, 0x00); // unknown writeC(buf, 0x00); // unknown writeH(buf, 16576); // unsure about this - verteron has 16656, akarios 16576 writeD(buf, emotionId); // teleport Id writeC(buf, 0x00); // unknown writeC(buf, 0x00); // unknown } else if (unknown == 35 ) { //emote startloop writeD(buf, 44); // unknown writeC(buf, 0xc0); // unknown writeC(buf, 0x40); // unknown } else if (unknown == 30 ) { //emote startloop writeD(buf, 33); // unknown writeC(buf, 0xe0); // unknown writeC(buf, 0x40); // unknown writeH(buf, 2142); // unknown writeH(buf, 2142); // unknown } else if (unknown == 19 ) { //emote startloop writeD(buf, 1); // unknown writeC(buf, 0xe0); // unknown writeC(buf, 0x40); // unknown } else if (unknown == 36 ) { //emote endloop writeD(buf, 33); // unknown writeC(buf, 0xc0); // unknown writeC(buf, 0x40); // unknown } else if (unknown == 0x16)//Run { writeC(buf, 0x01); writeC(buf, 0x00); writeH(buf, 0x00); writeC(buf, 0xC0); writeC(buf, 0x40); } else if (unknown == 0x15)//Walk { writeC(buf, 0x41); writeC(buf, 0x00); writeH(buf, 0x00); writeC(buf, 0xC0); writeC(buf, 0x3F); } else if (unknown == 0x20) //? { writeC(buf, 0x01); writeC(buf, 0x00); writeH(buf, 0x00); writeC(buf, 0x00); writeC(buf, 0x40); } else { writeC(buf, 0x01); // unknown writeC(buf, 0x00); // unknown writeH(buf, 0x00); // unknown writeC(buf, 0xC0); // unknown writeC(buf, 0x40); // unknown } if(unknown == 0x10) { writeD(buf, 0x00); // unknown writeH(buf, emotionId); writeC(buf, 0x01); // unknown } }
diff --git a/Essentials/src/com/earth2me/essentials/Essentials.java b/Essentials/src/com/earth2me/essentials/Essentials.java index 1d40f44..7531c03 100644 --- a/Essentials/src/com/earth2me/essentials/Essentials.java +++ b/Essentials/src/com/earth2me/essentials/Essentials.java @@ -1,747 +1,747 @@ /* * Essentials - a bukkit plugin * Copyright (C) 2011 Essentials Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earth2me.essentials; import com.earth2me.essentials.commands.EssentialsCommand; import java.io.*; import java.util.*; import java.util.logging.*; import org.bukkit.*; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import com.earth2me.essentials.commands.IEssentialsCommand; import com.earth2me.essentials.commands.NotEnoughArgumentsException; import com.earth2me.essentials.register.payment.Methods; import java.math.BigInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.craftbukkit.scheduler.CraftScheduler; import org.bukkit.entity.Player; import org.bukkit.event.Event.Priority; import org.bukkit.event.Event.Type; import org.bukkit.event.server.ServerListener; import org.bukkit.plugin.*; import org.bukkit.plugin.java.*; public class Essentials extends JavaPlugin implements IEssentials { public static final String AUTHORS = "Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo, ceulemans and Xeology"; public static final int minBukkitBuildVersion = 818; private static final Logger logger = Logger.getLogger("Minecraft"); private Settings settings; private EssentialsPlayerListener playerListener; private EssentialsBlockListener blockListener; private EssentialsEntityListener entityListener; private JailPlayerListener jailPlayerListener; private static Essentials instance = null; private Spawn spawn; private Jail jail; private Warps warps; private Worth worth; private List<IConf> confList; public ArrayList bans = new ArrayList(); public ArrayList bannedIps = new ArrayList(); private Backup backup; private final Map<String, User> users = new HashMap<String, User>(); private EssentialsTimer timer; private EssentialsUpdateTimer updateTimer; private boolean registerFallback = true; private final Methods paymentMethod = new Methods(); private final static boolean enableErrorLogging = false; private final EssentialsErrorHandler errorHandler = new EssentialsErrorHandler(); public static IEssentials getStatic() { return instance; } public Settings getSettings() { return settings; } public void setupForTesting(Server server) throws IOException, InvalidDescriptionException { File dataFolder = File.createTempFile("essentialstest", ""); dataFolder.delete(); dataFolder.mkdir(); logger.log(Level.INFO, Util.i18n("usingTempFolderForTesting")); logger.log(Level.INFO, dataFolder.toString()); this.initialize(null, server, new PluginDescriptionFile(new FileReader(new File("src" + File.separator + "plugin.yml"))), dataFolder, null, null); settings = new Settings(dataFolder); setStatic(); } public void setStatic() { instance = this; } public void onEnable() { if (enableErrorLogging) { logger.addHandler(errorHandler); } setStatic(); EssentialsUpgrade upgrade = new EssentialsUpgrade(this.getDescription().getVersion(), this); upgrade.beforeSettings(); confList = new ArrayList<IConf>(); settings = new Settings(this.getDataFolder()); confList.add(settings); upgrade.afterSettings(); Util.updateLocale(settings.getLocale(), this.getDataFolder()); spawn = new Spawn(getServer(), this.getDataFolder()); confList.add(spawn); warps = new Warps(getServer(), this.getDataFolder()); confList.add(warps); worth = new Worth(this.getDataFolder()); confList.add(worth); reload(); backup = new Backup(this); PluginManager pm = getServer().getPluginManager(); for (Plugin plugin : pm.getPlugins()) { if (plugin.getDescription().getName().startsWith("Essentials")) { if (!plugin.getDescription().getVersion().equals(this.getDescription().getVersion())) { logger.log(Level.WARNING, Util.format("versionMismatch", plugin.getDescription().getName())); } } } Matcher versionMatch = Pattern.compile("git-Bukkit-([0-9]+).([0-9]+).([0-9]+)-[0-9]+-[0-9a-z]+-b([0-9]+)jnks.*").matcher(getServer().getVersion()); if (versionMatch.matches()) { int versionNumber = Integer.parseInt(versionMatch.group(4)); if (versionNumber < minBukkitBuildVersion) { logger.log(Level.WARNING, Util.i18n("notRecommendedBukkit")); } } else { logger.log(Level.INFO, Util.i18n("bukkitFormatChanged")); } ServerListener serverListener = new EssentialsPluginListener(paymentMethod); pm.registerEvent(Type.PLUGIN_ENABLE, serverListener, Priority.Low, this); pm.registerEvent(Type.PLUGIN_DISABLE, serverListener, Priority.Low, this); playerListener = new EssentialsPlayerListener(this); pm.registerEvent(Type.PLAYER_JOIN, playerListener, Priority.Monitor, this); pm.registerEvent(Type.PLAYER_QUIT, playerListener, Priority.Monitor, this); pm.registerEvent(Type.PLAYER_CHAT, playerListener, Priority.Lowest, this); if (getSettings().getNetherPortalsEnabled()) { pm.registerEvent(Type.PLAYER_MOVE, playerListener, Priority.High, this); } pm.registerEvent(Type.PLAYER_LOGIN, playerListener, Priority.High, this); pm.registerEvent(Type.PLAYER_TELEPORT, playerListener, Priority.High, this); pm.registerEvent(Type.PLAYER_INTERACT, playerListener, Priority.High, this); pm.registerEvent(Type.PLAYER_EGG_THROW, playerListener, Priority.High, this); pm.registerEvent(Type.PLAYER_BUCKET_EMPTY, playerListener, Priority.High, this); pm.registerEvent(Type.PLAYER_ANIMATION, playerListener, Priority.High, this); blockListener = new EssentialsBlockListener(this); pm.registerEvent(Type.SIGN_CHANGE, blockListener, Priority.Low, this); pm.registerEvent(Type.BLOCK_BREAK, blockListener, Priority.Lowest, this); pm.registerEvent(Type.BLOCK_PLACE, blockListener, Priority.Lowest, this); entityListener = new EssentialsEntityListener(this); pm.registerEvent(Type.ENTITY_DAMAGE, entityListener, Priority.Lowest, this); pm.registerEvent(Type.ENTITY_COMBUST, entityListener, Priority.Lowest, this); pm.registerEvent(Type.ENTITY_DEATH, entityListener, Priority.Lowest, this); jail = new Jail(this); jailPlayerListener = new JailPlayerListener(this); confList.add(jail); pm.registerEvent(Type.BLOCK_BREAK, jail, Priority.High, this); pm.registerEvent(Type.BLOCK_DAMAGE, jail, Priority.High, this); pm.registerEvent(Type.BLOCK_PLACE, jail, Priority.High, this); pm.registerEvent(Type.PLAYER_INTERACT, jailPlayerListener, Priority.High, this); attachEcoListeners(); if (settings.isNetherEnabled() && getServer().getWorlds().size() < 2) { logger.log(Level.WARNING, "Old nether is disabled until multiworld support in bukkit is fixed."); getServer().createWorld(settings.getNetherName(), World.Environment.NETHER); } timer = new EssentialsTimer(this); getScheduler().scheduleSyncRepeatingTask(this, timer, 1, 50); if (enableErrorLogging) { updateTimer = new EssentialsUpdateTimer(this); getScheduler().scheduleAsyncRepeatingTask(this, updateTimer, 50, 50 * 60 * (this.getDescription().getVersion().startsWith("Dev") ? 60 : 360)); } logger.info(Util.format("loadinfo", this.getDescription().getName(), this.getDescription().getVersion(), AUTHORS)); } public void onDisable() { instance = null; logger.removeHandler(errorHandler); } public void reload() { loadBanList(); for (IConf iConf : confList) { iConf.reloadConfig(); } Util.updateLocale(settings.getLocale(), this.getDataFolder()); for (User user : users.values()) { user.reloadConfig(); } // for motd getConfiguration().load(); try { ItemDb.load(getDataFolder(), "items.csv"); } catch (Exception ex) { logger.log(Level.WARNING, Util.i18n("itemsCsvNotLoaded"), ex); } } public String[] getMotd(CommandSender sender, String def) { return getLines(sender, "motd", def); } public String[] getLines(CommandSender sender, String node, String def) { List<String> lines = (List<String>)getConfiguration().getProperty(node); if (lines == null) { return new String[0]; } String[] retval = new String[lines.size()]; if (lines == null || lines.isEmpty() || lines.get(0) == null) { try { lines = new ArrayList<String>(); // "[]" in YaML indicates empty array, so respect that if (!getConfiguration().getString(node, def).equals("[]")) { lines.add(getConfiguration().getString(node, def)); retval = new String[lines.size()]; } } catch (Throwable ex2) { logger.log(Level.WARNING, Util.format("corruptNodeInConfig", node)); return new String[0]; } } // if still empty, call it a day if (lines == null || lines.isEmpty() || lines.get(0) == null) { return new String[0]; } for (int i = 0; i < lines.size(); i++) { String m = lines.get(i); if (m == null) { continue; } m = m.replace('&', '§').replace("§§", "&"); if (sender instanceof User || sender instanceof Player) { User user = getUser(sender); m = m.replace("{PLAYER}", user.getDisplayName()); m = m.replace("{IP}", user.getAddress().toString()); m = m.replace("{BALANCE}", Double.toString(user.getMoney())); m = m.replace("{MAILS}", Integer.toString(user.getMails().size())); } m = m.replace("{ONLINE}", Integer.toString(getServer().getOnlinePlayers().length)); if (m.matches(".*\\{PLAYERLIST\\}.*")) { StringBuilder online = new StringBuilder(); for (Player p : getServer().getOnlinePlayers()) { if (online.length() > 0) { online.append(", "); } online.append(p.getDisplayName()); } m = m.replace("{PLAYERLIST}", online.toString()); } if (sender instanceof Player) { try { Class User = getClassLoader().loadClass("bukkit.Vandolis.User"); Object vuser = User.getConstructor(User.class).newInstance((Player)sender); m = m.replace("{RED:BALANCE}", User.getMethod("getMoney").invoke(vuser).toString()); m = m.replace("{RED:BUYS}", User.getMethod("getNumTransactionsBuy").invoke(vuser).toString()); m = m.replace("{RED:SELLS}", User.getMethod("getNumTransactionsSell").invoke(vuser).toString()); } catch (Throwable ex) { m = m.replace("{RED:BALANCE}", "N/A"); m = m.replace("{RED:BUYS}", "N/A"); m = m.replace("{RED:SELLS}", "N/A"); } } retval[i] = m + " "; } return retval; } @SuppressWarnings("LoggerStringConcat") public static void previewCommand(CommandSender sender, Command command, String commandLabel, String[] args) { if (sender instanceof Player) { logger.info(ChatColor.BLUE + "[PLAYER_COMMAND] " + ((Player)sender).getName() + ": /" + commandLabel + " " + EssentialsCommand.getFinalArg(args, 0)); } } @Override public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { return onCommandEssentials(sender, command, commandLabel, args, Essentials.class.getClassLoader(), "com.earth2me.essentials.commands.Command"); } public boolean onCommandEssentials(CommandSender sender, Command command, String commandLabel, String[] args, ClassLoader classLoader, String commandPath) { - if ("msg".equals(commandLabel.toLowerCase()) || "r".equals(commandLabel.toLowerCase()) || "mail".equals(commandLabel.toLowerCase()) && sender instanceof CraftPlayer) + if (("msg".equals(commandLabel.toLowerCase()) || "r".equals(commandLabel.toLowerCase()) || "mail".equals(commandLabel.toLowerCase())) && sender instanceof Player) { StringBuilder str = new StringBuilder(); str.append(commandLabel).append(" "); for (String a : args) { str.append(a).append(" "); } for (Player player : getServer().getOnlinePlayers()) { if (getUser(player).isSocialSpyEnabled()) { player.sendMessage(getUser(sender).getDisplayName() + " : " + str); } } } // Allow plugins to override the command via onCommand if (!getSettings().isCommandOverridden(command.getName()) && !commandLabel.startsWith("e")) { for (Plugin p : getServer().getPluginManager().getPlugins()) { if (p.getDescription().getMain().contains("com.earth2me.essentials")) { continue; } PluginDescriptionFile desc = p.getDescription(); if (desc == null) { continue; } if (desc.getName() == null) { continue; } if (!(desc.getCommands() instanceof Map)) { continue; } Map<String, Object> cmds = (Map<String, Object>)desc.getCommands(); if (!cmds.containsKey(command.getName())) { continue; } return p.onCommand(sender, command, commandLabel, args); } } try { previewCommand(sender, command, commandLabel, args); User user = sender instanceof Player ? getUser(sender) : null; // New mail notification if (user != null && !getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail") && user.isAuthorized("essentials.mail")) { final List<String> mail = user.getMails(); if (mail != null && !mail.isEmpty()) { user.sendMessage(Util.format("youHaveNewMail", mail.size())); } } // Check for disabled commands if (getSettings().isCommandDisabled(commandLabel)) { return true; } IEssentialsCommand cmd; try { cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + command.getName()).newInstance(); cmd.setEssentials(this); } catch (Exception ex) { sender.sendMessage(Util.format("commandNotLoaded", commandLabel)); logger.log(Level.SEVERE, Util.format("commandNotLoaded", commandLabel), ex); return true; } // Check authorization if (user != null && !user.isAuthorized(cmd)) { logger.log(Level.WARNING, Util.format("deniedAccessCommand", user.getName())); user.sendMessage(Util.i18n("noAccessCommand")); return true; } // Run the command try { if (user == null) { cmd.run(getServer(), sender, commandLabel, command, args); } else { cmd.run(getServer(), user, commandLabel, command, args); } return true; } catch (NotEnoughArgumentsException ex) { sender.sendMessage(command.getDescription()); sender.sendMessage(command.getUsage().replaceAll("<command>", commandLabel)); return true; } catch (Throwable ex) { sender.sendMessage(Util.format("errorWithMessage", ex.getMessage())); LogRecord lr = new LogRecord(Level.WARNING, Util.format("errorCallingCommand", commandLabel)); lr.setThrown(ex); if (getSettings().isDebug()) { logger.log(lr); } else { if (enableErrorLogging) { errorHandler.publish(lr); errorHandler.flush(); } } return true; } } catch (Throwable ex) { logger.log(Level.SEVERE, Util.format("commandFailed", commandLabel), ex); return true; } } public void loadBanList() { //I don't like this but it needs to be done until CB fixors File file = new File("banned-players.txt"); File ipFile = new File("banned-ips.txt"); try { if (!file.exists()) { throw new FileNotFoundException(Util.i18n("bannedPlayersFileNotFound")); } final BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); try { bans.clear(); while (bufferedReader.ready()) { final String line = bufferedReader.readLine().trim().toLowerCase(); if (line.length() > 0 && line.charAt(0) == '#') { continue; } bans.add(line); } } catch (IOException io) { logger.log(Level.SEVERE, Util.i18n("bannedPlayersFileError"), io); } finally { try { bufferedReader.close(); } catch (IOException ex) { logger.log(Level.SEVERE, Util.i18n("bannedPlayersFileError"), ex); } } } catch (FileNotFoundException ex) { logger.log(Level.SEVERE, Util.i18n("bannedPlayersFileError"), ex); } try { if (!ipFile.exists()) { throw new FileNotFoundException(Util.i18n("bannedIpsFileNotFound")); } final BufferedReader bufferedReader = new BufferedReader(new FileReader(ipFile)); try { bannedIps.clear(); while (bufferedReader.ready()) { final String line = bufferedReader.readLine().trim().toLowerCase(); if (line.length() > 0 && line.charAt(0) == '#') { continue; } bannedIps.add(line); } } catch (IOException io) { logger.log(Level.SEVERE, Util.i18n("bannedIpsFileError"), io); } finally { try { bufferedReader.close(); } catch (IOException ex) { logger.log(Level.SEVERE, Util.i18n("bannedIpsFileError"), ex); } } } catch (FileNotFoundException ex) { logger.log(Level.SEVERE, Util.i18n("bannedIpsFileError"), ex); } } private void attachEcoListeners() { PluginManager pm = getServer().getPluginManager(); EssentialsEcoBlockListener ecoBlockListener = new EssentialsEcoBlockListener(this); EssentialsEcoPlayerListener ecoPlayerListener = new EssentialsEcoPlayerListener(this); pm.registerEvent(Type.PLAYER_INTERACT, ecoPlayerListener, Priority.High, this); pm.registerEvent(Type.BLOCK_BREAK, ecoBlockListener, Priority.High, this); pm.registerEvent(Type.SIGN_CHANGE, ecoBlockListener, Priority.Monitor, this); } public CraftScheduler getScheduler() { return (CraftScheduler)this.getServer().getScheduler(); } public Jail getJail() { return jail; } public Warps getWarps() { return warps; } public Worth getWorth() { return worth; } public Backup getBackup() { return backup; } public Spawn getSpawn() { return spawn; } public User getUser(Object base) { if (base instanceof Player) { return getUser((Player)base); } return null; } private <T extends Player> User getUser(T base) { if (base == null) { return null; } if (base instanceof User) { return (User)base; } if (users.containsKey(base.getName().toLowerCase())) { return users.get(base.getName().toLowerCase()).update(base); } User u = new User(base, this); users.put(u.getName().toLowerCase(), u); return u; } public User getOfflineUser(String name) { File userFolder = new File(getDataFolder(), "userdata"); File userFile = new File(userFolder, Util.sanitizeFileName(name) + ".yml"); if (userFile.exists()) { //Users do not get offline changes saved without being reproccessed as Users! ~ Xeology :) return getUser((Player)new OfflinePlayer(name)); } return null; } public World getWorld(String name) { if (name.matches("[0-9]+")) { int id = Integer.parseInt(name); if (id < getServer().getWorlds().size()) { return getServer().getWorlds().get(id); } } World w = getServer().getWorld(name); if (w != null) { return w; } return null; } public void setRegisterFallback(boolean registerFallback) { this.registerFallback = registerFallback; } public boolean isRegisterFallbackEnabled() { return registerFallback; } public void addReloadListener(IConf listener) { confList.add(listener); } public Methods getPaymentMethod() { return paymentMethod; } public int broadcastMessage(String name, String message) { Player[] players = getServer().getOnlinePlayers(); for (Player player : players) { User u = getUser(player); if (!u.isIgnoredPlayer(name)) { player.sendMessage(message); } } return players.length; } public Map<BigInteger, String> getErrors() { return errorHandler.getErrors(); } public int scheduleAsyncDelayedTask(final Runnable run) { return this.getScheduler().scheduleAsyncDelayedTask(this, run); } public int scheduleSyncDelayedTask(final Runnable run) { return this.getScheduler().scheduleSyncDelayedTask(this, run); } public int scheduleSyncRepeatingTask(final Runnable run, long delay, long period) { return this.getScheduler().scheduleSyncRepeatingTask(this, run, delay, period); } public List<String> getBans() { return bans; } public List<String> getBannedIps() { return bannedIps; } }
true
true
public boolean onCommandEssentials(CommandSender sender, Command command, String commandLabel, String[] args, ClassLoader classLoader, String commandPath) { if ("msg".equals(commandLabel.toLowerCase()) || "r".equals(commandLabel.toLowerCase()) || "mail".equals(commandLabel.toLowerCase()) && sender instanceof CraftPlayer) { StringBuilder str = new StringBuilder(); str.append(commandLabel).append(" "); for (String a : args) { str.append(a).append(" "); } for (Player player : getServer().getOnlinePlayers()) { if (getUser(player).isSocialSpyEnabled()) { player.sendMessage(getUser(sender).getDisplayName() + " : " + str); } } } // Allow plugins to override the command via onCommand if (!getSettings().isCommandOverridden(command.getName()) && !commandLabel.startsWith("e")) { for (Plugin p : getServer().getPluginManager().getPlugins()) { if (p.getDescription().getMain().contains("com.earth2me.essentials")) { continue; } PluginDescriptionFile desc = p.getDescription(); if (desc == null) { continue; } if (desc.getName() == null) { continue; } if (!(desc.getCommands() instanceof Map)) { continue; } Map<String, Object> cmds = (Map<String, Object>)desc.getCommands(); if (!cmds.containsKey(command.getName())) { continue; } return p.onCommand(sender, command, commandLabel, args); } } try { previewCommand(sender, command, commandLabel, args); User user = sender instanceof Player ? getUser(sender) : null; // New mail notification if (user != null && !getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail") && user.isAuthorized("essentials.mail")) { final List<String> mail = user.getMails(); if (mail != null && !mail.isEmpty()) { user.sendMessage(Util.format("youHaveNewMail", mail.size())); } } // Check for disabled commands if (getSettings().isCommandDisabled(commandLabel)) { return true; } IEssentialsCommand cmd; try { cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + command.getName()).newInstance(); cmd.setEssentials(this); } catch (Exception ex) { sender.sendMessage(Util.format("commandNotLoaded", commandLabel)); logger.log(Level.SEVERE, Util.format("commandNotLoaded", commandLabel), ex); return true; } // Check authorization if (user != null && !user.isAuthorized(cmd)) { logger.log(Level.WARNING, Util.format("deniedAccessCommand", user.getName())); user.sendMessage(Util.i18n("noAccessCommand")); return true; } // Run the command try { if (user == null) { cmd.run(getServer(), sender, commandLabel, command, args); } else { cmd.run(getServer(), user, commandLabel, command, args); } return true; } catch (NotEnoughArgumentsException ex) { sender.sendMessage(command.getDescription()); sender.sendMessage(command.getUsage().replaceAll("<command>", commandLabel)); return true; } catch (Throwable ex) { sender.sendMessage(Util.format("errorWithMessage", ex.getMessage())); LogRecord lr = new LogRecord(Level.WARNING, Util.format("errorCallingCommand", commandLabel)); lr.setThrown(ex); if (getSettings().isDebug()) { logger.log(lr); } else { if (enableErrorLogging) { errorHandler.publish(lr); errorHandler.flush(); } } return true; } } catch (Throwable ex) { logger.log(Level.SEVERE, Util.format("commandFailed", commandLabel), ex); return true; } }
public boolean onCommandEssentials(CommandSender sender, Command command, String commandLabel, String[] args, ClassLoader classLoader, String commandPath) { if (("msg".equals(commandLabel.toLowerCase()) || "r".equals(commandLabel.toLowerCase()) || "mail".equals(commandLabel.toLowerCase())) && sender instanceof Player) { StringBuilder str = new StringBuilder(); str.append(commandLabel).append(" "); for (String a : args) { str.append(a).append(" "); } for (Player player : getServer().getOnlinePlayers()) { if (getUser(player).isSocialSpyEnabled()) { player.sendMessage(getUser(sender).getDisplayName() + " : " + str); } } } // Allow plugins to override the command via onCommand if (!getSettings().isCommandOverridden(command.getName()) && !commandLabel.startsWith("e")) { for (Plugin p : getServer().getPluginManager().getPlugins()) { if (p.getDescription().getMain().contains("com.earth2me.essentials")) { continue; } PluginDescriptionFile desc = p.getDescription(); if (desc == null) { continue; } if (desc.getName() == null) { continue; } if (!(desc.getCommands() instanceof Map)) { continue; } Map<String, Object> cmds = (Map<String, Object>)desc.getCommands(); if (!cmds.containsKey(command.getName())) { continue; } return p.onCommand(sender, command, commandLabel, args); } } try { previewCommand(sender, command, commandLabel, args); User user = sender instanceof Player ? getUser(sender) : null; // New mail notification if (user != null && !getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail") && user.isAuthorized("essentials.mail")) { final List<String> mail = user.getMails(); if (mail != null && !mail.isEmpty()) { user.sendMessage(Util.format("youHaveNewMail", mail.size())); } } // Check for disabled commands if (getSettings().isCommandDisabled(commandLabel)) { return true; } IEssentialsCommand cmd; try { cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + command.getName()).newInstance(); cmd.setEssentials(this); } catch (Exception ex) { sender.sendMessage(Util.format("commandNotLoaded", commandLabel)); logger.log(Level.SEVERE, Util.format("commandNotLoaded", commandLabel), ex); return true; } // Check authorization if (user != null && !user.isAuthorized(cmd)) { logger.log(Level.WARNING, Util.format("deniedAccessCommand", user.getName())); user.sendMessage(Util.i18n("noAccessCommand")); return true; } // Run the command try { if (user == null) { cmd.run(getServer(), sender, commandLabel, command, args); } else { cmd.run(getServer(), user, commandLabel, command, args); } return true; } catch (NotEnoughArgumentsException ex) { sender.sendMessage(command.getDescription()); sender.sendMessage(command.getUsage().replaceAll("<command>", commandLabel)); return true; } catch (Throwable ex) { sender.sendMessage(Util.format("errorWithMessage", ex.getMessage())); LogRecord lr = new LogRecord(Level.WARNING, Util.format("errorCallingCommand", commandLabel)); lr.setThrown(ex); if (getSettings().isDebug()) { logger.log(lr); } else { if (enableErrorLogging) { errorHandler.publish(lr); errorHandler.flush(); } } return true; } } catch (Throwable ex) { logger.log(Level.SEVERE, Util.format("commandFailed", commandLabel), ex); return true; } }
diff --git a/wayback-core/src/main/java/org/archive/wayback/surt/SURTTokenizer.java b/wayback-core/src/main/java/org/archive/wayback/surt/SURTTokenizer.java index 0bfbc6f53..05e2bebef 100644 --- a/wayback-core/src/main/java/org/archive/wayback/surt/SURTTokenizer.java +++ b/wayback-core/src/main/java/org/archive/wayback/surt/SURTTokenizer.java @@ -1,193 +1,193 @@ /* * This file is part of the Wayback archival access software * (http://archive-access.sourceforge.net/projects/wayback/). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.wayback.surt; import org.apache.commons.httpclient.URIException; import org.archive.net.UURI; import org.archive.net.UURIFactory; import org.archive.util.ArchiveUtils; import org.archive.util.SURT; /** * provides iterative Url reduction for prefix matching to find ever coarser * grained URL-specific configuration. Assumes that a prefix binary search is * being attempted for each returned value. First value is the entire SURT * url String, with TAB appended. Second removes CGI ARGs. Then each subsequent * path segment ('/' separated) is removed. Then the login:password, if present * is removed. Then the port, if not :80 or omitted on the initial URL. Then * each subsequent authority segment(. separated) is removed. * * the nextSearch() method will return null, finally, when no broader searches * can be attempted on the URL. * * @author brad * @version $Date$, $Revision$ */ public class SURTTokenizer { private final static String EXACT_SUFFIX = "\t"; private String remainder; private boolean triedExact; private boolean triedFull; private boolean choppedArgs; private boolean choppedPath; private boolean choppedLogin; private boolean choppedPort; /** * constructor * * @param url String URL * @throws URIException */ public SURTTokenizer(final String url, boolean isSurt) throws URIException { if(url.startsWith("(") || isSurt) { remainder = url; } else { remainder = getKey(url,false); } } /** * update internal state and return the next smaller search string * for the url * * @return string to lookup for prefix match for relevant information. */ public String nextSearch() { if(!triedExact) { triedExact = true; return remainder + EXACT_SUFFIX; } if(!triedFull) { triedFull = true; if(remainder.endsWith(")/")) { choppedPath = true; } return remainder; } if(!choppedArgs) { choppedArgs = true; int argStart = remainder.indexOf('?'); if(argStart != -1) { remainder = remainder.substring(0,argStart); return remainder; } } // we have already returned remainder as-is, so we have slightly // special handling here to make sure we continue to make progress: // (com,foo,www,)/ => (com,foo,www, // (com,foo,www,)/bar => (com,foo,www,)/ // (com,foo,www,)/bar/ => (com,foo,www,)/bar // (com,foo,www,)/bar/foo => (com,foo,www,)/bar // (com,foo,www,)/bar/foo/ => (com,foo,www,)/bar/foo if(!choppedPath) { int lastSlash = remainder.lastIndexOf('/'); if(lastSlash != -1) { if(lastSlash == (remainder.length()-1)) { if(remainder.endsWith(")/")) { String tmp = remainder; remainder = remainder.substring(0,lastSlash-1); choppedPath = true; return tmp; } else { remainder = remainder.substring(0,lastSlash); return remainder; } } - if(remainder.charAt(lastSlash-1) == ')') { + if((lastSlash > 0) && remainder.charAt(lastSlash-1) == ')') { String tmp = remainder.substring(0,lastSlash+1); remainder = remainder.substring(0,lastSlash-1); return tmp; } else { remainder = remainder.substring(0,lastSlash); return remainder; } } choppedPath = true; } if(!choppedLogin) { choppedLogin = true; int lastAt = remainder.lastIndexOf('@'); if(lastAt != -1) { String tmp = remainder; remainder = remainder.substring(0,lastAt); return tmp; } } if(!choppedPort) { choppedPort = true; int lastColon = remainder.lastIndexOf(':'); if(lastColon != -1) { return remainder; } } // now just remove ','s int lastComma = remainder.lastIndexOf(','); if(lastComma == -1) { return null; } remainder = remainder.substring(0,lastComma); return remainder; } /** * @param url * @return String SURT which will match exactly argument url * @throws URIException */ public static String exactKey(String url) throws URIException { return getKey(url,false); } /** * @param url * @return String SURT which will match urls prefixed with the argument url * @throws URIException */ public static String prefixKey(String url) throws URIException { return getKey(url,true); } private static String getKey(String url, boolean prefix) throws URIException { String key = ArchiveUtils.addImpliedHttpIfNecessary(url); UURI uuri = UURIFactory.getInstance(key); key = uuri.getScheme() + "://" + uuri.getAuthority() + uuri.getEscapedPathQuery(); key = SURT.fromURI(key); int hashPos = key.indexOf('#'); if(hashPos != -1) { key = key.substring(0,hashPos); } if(key.startsWith("http://")) { key = key.substring(7); } if(prefix) { if(key.endsWith(",)/")) { key = key.substring(0,key.length()-3); } } return key; } }
true
true
public String nextSearch() { if(!triedExact) { triedExact = true; return remainder + EXACT_SUFFIX; } if(!triedFull) { triedFull = true; if(remainder.endsWith(")/")) { choppedPath = true; } return remainder; } if(!choppedArgs) { choppedArgs = true; int argStart = remainder.indexOf('?'); if(argStart != -1) { remainder = remainder.substring(0,argStart); return remainder; } } // we have already returned remainder as-is, so we have slightly // special handling here to make sure we continue to make progress: // (com,foo,www,)/ => (com,foo,www, // (com,foo,www,)/bar => (com,foo,www,)/ // (com,foo,www,)/bar/ => (com,foo,www,)/bar // (com,foo,www,)/bar/foo => (com,foo,www,)/bar // (com,foo,www,)/bar/foo/ => (com,foo,www,)/bar/foo if(!choppedPath) { int lastSlash = remainder.lastIndexOf('/'); if(lastSlash != -1) { if(lastSlash == (remainder.length()-1)) { if(remainder.endsWith(")/")) { String tmp = remainder; remainder = remainder.substring(0,lastSlash-1); choppedPath = true; return tmp; } else { remainder = remainder.substring(0,lastSlash); return remainder; } } if(remainder.charAt(lastSlash-1) == ')') { String tmp = remainder.substring(0,lastSlash+1); remainder = remainder.substring(0,lastSlash-1); return tmp; } else { remainder = remainder.substring(0,lastSlash); return remainder; } } choppedPath = true; } if(!choppedLogin) { choppedLogin = true; int lastAt = remainder.lastIndexOf('@'); if(lastAt != -1) { String tmp = remainder; remainder = remainder.substring(0,lastAt); return tmp; } } if(!choppedPort) { choppedPort = true; int lastColon = remainder.lastIndexOf(':'); if(lastColon != -1) { return remainder; } } // now just remove ','s int lastComma = remainder.lastIndexOf(','); if(lastComma == -1) { return null; } remainder = remainder.substring(0,lastComma); return remainder; }
public String nextSearch() { if(!triedExact) { triedExact = true; return remainder + EXACT_SUFFIX; } if(!triedFull) { triedFull = true; if(remainder.endsWith(")/")) { choppedPath = true; } return remainder; } if(!choppedArgs) { choppedArgs = true; int argStart = remainder.indexOf('?'); if(argStart != -1) { remainder = remainder.substring(0,argStart); return remainder; } } // we have already returned remainder as-is, so we have slightly // special handling here to make sure we continue to make progress: // (com,foo,www,)/ => (com,foo,www, // (com,foo,www,)/bar => (com,foo,www,)/ // (com,foo,www,)/bar/ => (com,foo,www,)/bar // (com,foo,www,)/bar/foo => (com,foo,www,)/bar // (com,foo,www,)/bar/foo/ => (com,foo,www,)/bar/foo if(!choppedPath) { int lastSlash = remainder.lastIndexOf('/'); if(lastSlash != -1) { if(lastSlash == (remainder.length()-1)) { if(remainder.endsWith(")/")) { String tmp = remainder; remainder = remainder.substring(0,lastSlash-1); choppedPath = true; return tmp; } else { remainder = remainder.substring(0,lastSlash); return remainder; } } if((lastSlash > 0) && remainder.charAt(lastSlash-1) == ')') { String tmp = remainder.substring(0,lastSlash+1); remainder = remainder.substring(0,lastSlash-1); return tmp; } else { remainder = remainder.substring(0,lastSlash); return remainder; } } choppedPath = true; } if(!choppedLogin) { choppedLogin = true; int lastAt = remainder.lastIndexOf('@'); if(lastAt != -1) { String tmp = remainder; remainder = remainder.substring(0,lastAt); return tmp; } } if(!choppedPort) { choppedPort = true; int lastColon = remainder.lastIndexOf(':'); if(lastColon != -1) { return remainder; } } // now just remove ','s int lastComma = remainder.lastIndexOf(','); if(lastComma == -1) { return null; } remainder = remainder.substring(0,lastComma); return remainder; }
diff --git a/src/org/eclipse/imp/pdb/facts/type/MapType.java b/src/org/eclipse/imp/pdb/facts/type/MapType.java index dd4c969c..2cd314f3 100644 --- a/src/org/eclipse/imp/pdb/facts/type/MapType.java +++ b/src/org/eclipse/imp/pdb/facts/type/MapType.java @@ -1,244 +1,248 @@ /******************************************************************************* * Copyright (c) 2008 CWI * 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: * Robert Fuhrer ([email protected]) - initial API and implementation *******************************************************************************/ package org.eclipse.imp.pdb.facts.type; import java.util.Map; import org.eclipse.imp.pdb.facts.IMap; import org.eclipse.imp.pdb.facts.IMapWriter; import org.eclipse.imp.pdb.facts.IValueFactory; import org.eclipse.imp.pdb.facts.exceptions.FactTypeUseException; import org.eclipse.imp.pdb.facts.exceptions.UndeclaredFieldException; /*package*/ final class MapType extends Type { private final Type fKeyType; private final Type fValueType; private final String fKeyLabel; private final String fValueLabel; /*package*/ MapType(Type keyType, Type valueType) { fKeyType= keyType; fValueType = valueType; fKeyLabel = null; fValueLabel = null; } /*package*/ MapType(Type keyType, String keyLabel, Type valueType, String valueLabel) { fKeyType= keyType; fValueType = valueType; fKeyLabel = keyLabel; fValueLabel = valueLabel; } @Override public Type getKeyType() { return fKeyType; } @Override public String getKeyLabel() { return fKeyLabel; } @Override public int getArity() { return 2; } @Override public String getValueLabel() { return fValueLabel; } @Override public Type getValueType() { return fValueType; } @Override public boolean isMapType() { return true; } @Override public boolean hasFieldNames() { return fKeyLabel != null && fValueLabel != null; } @Override public Type getFieldType(String fieldName) throws FactTypeUseException { if (fKeyLabel.equals(fieldName)) { return fKeyType; } if (fValueLabel.equals(fieldName)) { return fValueType; } throw new UndeclaredFieldException(this, fieldName); } @Override public boolean hasField(String fieldName) { if (fieldName.equals(fKeyLabel)) { return true; } else if (fieldName.equals(fValueLabel)) { return true; } return false; } @Override public Type getFieldType(int i) { switch (i) { case 0: return fKeyType; case 1: return fValueType; default: throw new IndexOutOfBoundsException(); } } @Override public String getFieldName(int i) { switch (i) { case 0: return fKeyLabel; case 1: return fValueLabel; default: throw new IndexOutOfBoundsException(); } } @Override public Type select(int... fields) { return TypeFactory.getInstance().setType(getFieldTypes().select(fields)); } @Override public Type select(String... names) { return TypeFactory.getInstance().setType(getFieldTypes().select(names)); } @Override public int getFieldIndex(String fieldName) { if (fKeyLabel.equals(fieldName)) { return 0; } if (fValueLabel.equals(fieldName)) { return 1; } throw new UndeclaredFieldException(this, fieldName); } @Override public Type getFieldTypes() { if (hasFieldNames()) { return TypeFactory.getInstance().tupleType(fKeyType, fKeyLabel, fValueType, fValueLabel); } else { return TypeFactory.getInstance().tupleType(fKeyType, fValueType); } } @Override public boolean isSubtypeOf(Type o) { if (o.isMapType() && !o.isVoidType()) { return fKeyType.isSubtypeOf(o.getKeyType()) && fValueType.isSubtypeOf(o.getValueType()); } return super.isSubtypeOf(o); } @Override public Type lub(Type o) { if (o.isMapType()) { // reusing tuple type here because of complexity dealing with labels return TypeFactory.getInstance().mapTypeFromTuple(getFieldTypes().lub(o.getFieldTypes())); } return super.lub(o); } @Override public Type carrier() { TypeFactory tf = TypeFactory.getInstance(); return tf.setType(fKeyType.lub(fValueType)); } @Override public int hashCode() { return 56509 + 3511 * fKeyType.hashCode() + 1171 * fValueType.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof MapType)) { return false; } MapType other= (MapType) obj; if (fKeyLabel != null) { if (!fKeyLabel.equals(other.fKeyLabel)) { return false; } } + else if(other.fKeyLabel != null) + return false; if (fValueLabel != null) { if (!fValueLabel.equals(other.fValueLabel)) { return false; } } + else if(other.fValueLabel != null) + return false; // N.B.: The element type must have been created and canonicalized before any // attempt to manipulate the outer type (i.e. SetType), so we can use object // identity here for the fEltType. return fKeyType == other.fKeyType && fValueType == other.fValueType; } @Override public String toString() { return "map[" + fKeyType + (fKeyLabel != null ? " " + fKeyLabel : "") + ", " + fValueType + (fValueLabel != null ? " " + fValueLabel : "") + "]"; } @Override public <T> T accept(ITypeVisitor<T> visitor) { return visitor.visitMap(this); } @Override public IMap make(IValueFactory f) { return f.map(fKeyType, fValueType); } @SuppressWarnings("unchecked") @Override public IMapWriter writer(IValueFactory f) { return f.mapWriter(fKeyType, fValueType); } @Override public boolean match(Type matched, Map<Type, Type> bindings) throws FactTypeUseException { return super.match(matched, bindings) && getKeyType().match(matched.getKeyType(), bindings) &&getValueType().match(matched.getValueType(), bindings); } @Override public Type instantiate(Map<Type, Type> bindings) { return TypeFactory.getInstance().mapType(getKeyType().instantiate(bindings), getValueType().instantiate(bindings)); } }
false
true
public boolean equals(Object obj) { if (!(obj instanceof MapType)) { return false; } MapType other= (MapType) obj; if (fKeyLabel != null) { if (!fKeyLabel.equals(other.fKeyLabel)) { return false; } } if (fValueLabel != null) { if (!fValueLabel.equals(other.fValueLabel)) { return false; } } // N.B.: The element type must have been created and canonicalized before any // attempt to manipulate the outer type (i.e. SetType), so we can use object // identity here for the fEltType. return fKeyType == other.fKeyType && fValueType == other.fValueType; }
public boolean equals(Object obj) { if (!(obj instanceof MapType)) { return false; } MapType other= (MapType) obj; if (fKeyLabel != null) { if (!fKeyLabel.equals(other.fKeyLabel)) { return false; } } else if(other.fKeyLabel != null) return false; if (fValueLabel != null) { if (!fValueLabel.equals(other.fValueLabel)) { return false; } } else if(other.fValueLabel != null) return false; // N.B.: The element type must have been created and canonicalized before any // attempt to manipulate the outer type (i.e. SetType), so we can use object // identity here for the fEltType. return fKeyType == other.fKeyType && fValueType == other.fValueType; }
diff --git a/webui/core/src/main/java/org/exoplatform/webui/application/ConfigurationManager.java b/webui/core/src/main/java/org/exoplatform/webui/application/ConfigurationManager.java index 153e5cbb6..34c5110e7 100644 --- a/webui/core/src/main/java/org/exoplatform/webui/application/ConfigurationManager.java +++ b/webui/core/src/main/java/org/exoplatform/webui/application/ConfigurationManager.java @@ -1,360 +1,360 @@ /** * Copyright (C) 2009 eXo Platform SAS. * * 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.exoplatform.webui.application; import org.exoplatform.webui.config.Component; import org.exoplatform.webui.config.Event; import org.exoplatform.webui.config.EventInterceptor; import org.exoplatform.webui.config.InitParams; import org.exoplatform.webui.config.Param; import org.exoplatform.webui.config.Validator; import org.exoplatform.webui.config.WebuiConfiguration; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.ComponentConfigs; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.config.annotation.EventInterceptorConfig; import org.exoplatform.webui.config.annotation.ParamConfig; import org.exoplatform.webui.config.annotation.ValidatorConfig; import org.jibx.runtime.BindingDirectory; import org.jibx.runtime.IBindingFactory; import org.jibx.runtime.IUnmarshallingContext; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * May 10, 2006 * <p/> * Manages the ComponentConfig of a list of components. * * @see ComponentConfig */ public class ConfigurationManager { /** * todo (julien) : this map should be synchronized somehow * <p/> * The components of which we manage the configuration */ private Map<String, Component> configs_ = new HashMap<String, Component>(); private org.exoplatform.webui.config.Application application_; /** * @param inputStream A stream that links the configuration file * @throws Exception */ public ConfigurationManager(InputStream inputStream) throws Exception { IBindingFactory bfact = BindingDirectory.getFactory(WebuiConfiguration.class); IUnmarshallingContext uctx = bfact.createUnmarshallingContext(); WebuiConfiguration config = (WebuiConfiguration)uctx.unmarshalDocument(inputStream, null); ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (config.getAnnotationClasses() != null) { for (String annotationClass : config.getAnnotationClasses()) { //process annotation and get the Component Component[] components = annotationToComponents(cl, annotationClass); setComponentConfigs(components); } } if (config.getComponents() != null) { for (Component component : config.getComponents()) { String key = component.getType(); if (component.getId() != null) { key = key + ":" + component.getId(); } configs_.put(key, component); } } application_ = config.getApplication(); } /** * Adds components to the list * * @param configs An array of Component */ void setComponentConfigs(Component[] configs) { for (Component component : configs) { String key = component.getType(); if (component.getId() != null) { key = key + ":" + component.getId(); } configs_.put(key, component); } } /** * Gets the components of a given class * * @param clazz The class of the components * @return the list of components */ public List<Component> getComponentConfig(Class<?> clazz) { List<Component> configs = new ArrayList<Component>(); Collection<Component> values = configs_.values(); String type = clazz.getName(); for (Component comp : values) { if (comp.getType().equals(type)) { configs.add(comp); } } return configs; } /** * Gets a component of a given class and identified by id * * @param type The class of the component * @param id The id of the component * @return The component */ public Component getComponentConfig(Class<?> type, String id) { String key = type.getName(); if (id != null) { key = key + ":" + id; } Component config = configs_.get(key); if (config != null) { return config; } try { Component[] components = annotationToComponents(type); setComponentConfigs(components); return configs_.get(key); } catch (Exception e) { return null; } } public org.exoplatform.webui.config.Application getApplication() { return application_; } /** * Gets an array of Component from a ComponentConfig annotation * * @param cl the classloader to create the annotation * @param annClass the annotation class * @return The array of Component * @throws Exception */ Component[] annotationToComponents(ClassLoader cl, String annClass) throws Exception { Class<?> clazz = cl.loadClass(annClass); return annotationToComponents(clazz); } /** * Gets an array of Component from a ComponentConfig annotation * * @param clazz The annotation class from which to get the ComponentConfig * @return The array of Component * @throws Exception */ Component[] annotationToComponents(Class<?> clazz) throws Exception { ComponentConfig annotation = clazz.getAnnotation(ComponentConfig.class); if (annotation != null) { return new Component[]{toComponentConfig(annotation, clazz)}; } ComponentConfigs annotations = clazz.getAnnotation(ComponentConfigs.class); if (annotations != null) { ComponentConfig[] listAnnotations = annotations.value(); Component[] componentConfigs = new Component[listAnnotations.length]; for (int i = 0; i < componentConfigs.length; i++) { componentConfigs[i] = toComponentConfig(listAnnotations[i], clazz); } return componentConfigs; } return new Component[]{}; } private Component toComponentConfig(ComponentConfig annotation, Class<?> clazz) throws Exception { Component config = new Component(); if (annotation.id().length() > 0) { config.setId(annotation.id()); } Class<?> type = annotation.type() == void.class ? clazz : annotation.type(); config.setType(type.getName()); if (annotation.template().length() > 0) { config.setTemplate(annotation.template()); } if (annotation.lifecycle() != void.class) { config.setLifecycle(annotation.lifecycle().getName()); } if (annotation.decorator().length() > 0) { config.setDecorator(annotation.decorator()); } config.setInitParams(toInitParams(annotation.initParams())); EventConfig[] eventAnnotations = annotation.events(); - List<Event> events; + ArrayList<Event> events; if (eventAnnotations.length != 0) { events = new ArrayList<Event>(); for (EventConfig eventAnnotation : eventAnnotations) { events.add(toEventConfig(eventAnnotation)); } } else { - events = Collections.emptyList(); + events = new ArrayList<Event>(); } config.setEvents(events); EventInterceptorConfig[] eventInterceptorAnnotations = annotation.eventInterceptors(); - List<EventInterceptor> eventInterceptors; + ArrayList<EventInterceptor> eventInterceptors; if (eventInterceptorAnnotations.length != 0) { eventInterceptors = new ArrayList<EventInterceptor>(); for (EventInterceptorConfig eventAnnotation : eventInterceptorAnnotations) { eventInterceptors.add(toEventInterceptorConfig(eventAnnotation)); } } else { - eventInterceptors = Collections.emptyList(); + eventInterceptors = new ArrayList<EventInterceptor>(); } config.setEventInterceptors(eventInterceptors); ValidatorConfig[] validatorAnnotations = annotation.validators(); - List<Validator> validators; + ArrayList<Validator> validators; if (validatorAnnotations.length != 0) { validators = new ArrayList<Validator>(); for (ValidatorConfig ele : validatorAnnotations) { validators.add(toValidator(ele)); } } else { - validators = Collections.emptyList(); + validators = new ArrayList<Validator>(); } config.setValidators(validators); return config; } private Event toEventConfig(EventConfig annotation) throws Exception { Event event = new Event(); event.setExecutionPhase(annotation.phase()); event.setConfirm(annotation.confirm()); event.setInitParams(toInitParams(annotation.initParams())); ArrayList<String> listeners = new ArrayList<String>(); for (Class<?> clazz : annotation.listeners()) { listeners.add(clazz.getName()); } if (annotation.name().length() > 0) { event.setName(annotation.name()); } else if (annotation.listeners().length > 0) { String name = annotation.listeners()[0].getSimpleName(); int idx = name.indexOf("ActionListener"); if (idx > -1) { name = name.substring(0, idx); } event.setName(name); } event.setListeners(listeners); return event; } private EventInterceptor toEventInterceptorConfig(EventInterceptorConfig annotation) throws Exception { EventInterceptor eventInterceptor = new EventInterceptor(); eventInterceptor.setType(annotation.type().getName()); ArrayList<String> list = new ArrayList<String>(); Collections.addAll(list, annotation.interceptors()); eventInterceptor.setInterceptors(list); eventInterceptor.setInitParams(toInitParams(annotation.initParams())); return eventInterceptor; } private Validator toValidator(ValidatorConfig annotation) throws Exception { Validator validator = new Validator(); validator.setType(annotation.type().getName()); validator.setInitParams(toInitParams(annotation.initParams())); return validator; } private InitParams toInitParams(ParamConfig[] annotations) { if (annotations == null || annotations.length < 1) { return null; } ArrayList<Param> listParam = new ArrayList<Param>(); for (ParamConfig ele : annotations) { Param param = new Param(); param.setName(ele.name()); param.setValue(ele.value()); listParam.add(param); } InitParams initParams = new InitParams(); initParams.setParams(listParam); return initParams; } }
false
true
private Component toComponentConfig(ComponentConfig annotation, Class<?> clazz) throws Exception { Component config = new Component(); if (annotation.id().length() > 0) { config.setId(annotation.id()); } Class<?> type = annotation.type() == void.class ? clazz : annotation.type(); config.setType(type.getName()); if (annotation.template().length() > 0) { config.setTemplate(annotation.template()); } if (annotation.lifecycle() != void.class) { config.setLifecycle(annotation.lifecycle().getName()); } if (annotation.decorator().length() > 0) { config.setDecorator(annotation.decorator()); } config.setInitParams(toInitParams(annotation.initParams())); EventConfig[] eventAnnotations = annotation.events(); List<Event> events; if (eventAnnotations.length != 0) { events = new ArrayList<Event>(); for (EventConfig eventAnnotation : eventAnnotations) { events.add(toEventConfig(eventAnnotation)); } } else { events = Collections.emptyList(); } config.setEvents(events); EventInterceptorConfig[] eventInterceptorAnnotations = annotation.eventInterceptors(); List<EventInterceptor> eventInterceptors; if (eventInterceptorAnnotations.length != 0) { eventInterceptors = new ArrayList<EventInterceptor>(); for (EventInterceptorConfig eventAnnotation : eventInterceptorAnnotations) { eventInterceptors.add(toEventInterceptorConfig(eventAnnotation)); } } else { eventInterceptors = Collections.emptyList(); } config.setEventInterceptors(eventInterceptors); ValidatorConfig[] validatorAnnotations = annotation.validators(); List<Validator> validators; if (validatorAnnotations.length != 0) { validators = new ArrayList<Validator>(); for (ValidatorConfig ele : validatorAnnotations) { validators.add(toValidator(ele)); } } else { validators = Collections.emptyList(); } config.setValidators(validators); return config; }
private Component toComponentConfig(ComponentConfig annotation, Class<?> clazz) throws Exception { Component config = new Component(); if (annotation.id().length() > 0) { config.setId(annotation.id()); } Class<?> type = annotation.type() == void.class ? clazz : annotation.type(); config.setType(type.getName()); if (annotation.template().length() > 0) { config.setTemplate(annotation.template()); } if (annotation.lifecycle() != void.class) { config.setLifecycle(annotation.lifecycle().getName()); } if (annotation.decorator().length() > 0) { config.setDecorator(annotation.decorator()); } config.setInitParams(toInitParams(annotation.initParams())); EventConfig[] eventAnnotations = annotation.events(); ArrayList<Event> events; if (eventAnnotations.length != 0) { events = new ArrayList<Event>(); for (EventConfig eventAnnotation : eventAnnotations) { events.add(toEventConfig(eventAnnotation)); } } else { events = new ArrayList<Event>(); } config.setEvents(events); EventInterceptorConfig[] eventInterceptorAnnotations = annotation.eventInterceptors(); ArrayList<EventInterceptor> eventInterceptors; if (eventInterceptorAnnotations.length != 0) { eventInterceptors = new ArrayList<EventInterceptor>(); for (EventInterceptorConfig eventAnnotation : eventInterceptorAnnotations) { eventInterceptors.add(toEventInterceptorConfig(eventAnnotation)); } } else { eventInterceptors = new ArrayList<EventInterceptor>(); } config.setEventInterceptors(eventInterceptors); ValidatorConfig[] validatorAnnotations = annotation.validators(); ArrayList<Validator> validators; if (validatorAnnotations.length != 0) { validators = new ArrayList<Validator>(); for (ValidatorConfig ele : validatorAnnotations) { validators.add(toValidator(ele)); } } else { validators = new ArrayList<Validator>(); } config.setValidators(validators); return config; }
diff --git a/stripes/src/net/sourceforge/stripes/util/HttpUtil.java b/stripes/src/net/sourceforge/stripes/util/HttpUtil.java index 593a7410..4a27f0b4 100644 --- a/stripes/src/net/sourceforge/stripes/util/HttpUtil.java +++ b/stripes/src/net/sourceforge/stripes/util/HttpUtil.java @@ -1,82 +1,82 @@ /* Copyright 2008 Ben Gunter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sourceforge.stripes.util; import javax.servlet.http.HttpServletRequest; import net.sourceforge.stripes.controller.StripesConstants; /** * Provides helper methods for working with HTTP requests and responses. * * @author Ben Gunter * @since Stripes 1.5.1 */ public class HttpUtil { /** * <p> * Get the path from the given request. This method is different from * {@link HttpServletRequest#getRequestURI()} in that it concatenates and returns the servlet * path plus the path info from the request. These are usually the same, but in some cases they * are not. * </p> * <p> * One case where they are known to differ is when a request for a directory is forwarded by the * servlet container to a welcome file. In that case, {@link HttpServletRequest#getRequestURI()} * returns the path that was actually requested (e.g., {@code "/"}), whereas the servlet path * plus path info is the path to the welcome file (e.g. {@code "/index.jsp"}). * </p> */ public static String getRequestedPath(HttpServletRequest request) { String servletPath, pathInfo; // Check to see if the request is processing an include, and pull the path // information from the appropriate source. servletPath = (String) request.getAttribute(StripesConstants.REQ_ATTR_INCLUDE_PATH); if (servletPath != null) { pathInfo = (String) request.getAttribute(StripesConstants.REQ_ATTR_INCLUDE_PATH_INFO); } else { servletPath = request.getServletPath(); pathInfo = request.getPathInfo(); } if (servletPath == null) - return pathInfo == null ? "" : pathInfo; + return pathInfo == null ? "" : StringUtil.urlDecode(pathInfo); else if (pathInfo == null) - return servletPath; + return StringUtil.urlDecode(servletPath); else - return servletPath + pathInfo; + return StringUtil.urlDecode(servletPath + pathInfo); } /** * Get the servlet path of the current request. The value returned by this method may differ * from {@link HttpServletRequest#getServletPath()}. If the given request is an include, then * the servlet path of the included resource is returned. */ public static String getRequestedServletPath(HttpServletRequest request) { // Check to see if the request is processing an include, and pull the path // information from the appropriate source. String path = (String) request.getAttribute(StripesConstants.REQ_ATTR_INCLUDE_PATH); if (path == null) { path = request.getServletPath(); } return path == null ? "" : path; } /** No instances */ private HttpUtil() { } }
false
true
public static String getRequestedPath(HttpServletRequest request) { String servletPath, pathInfo; // Check to see if the request is processing an include, and pull the path // information from the appropriate source. servletPath = (String) request.getAttribute(StripesConstants.REQ_ATTR_INCLUDE_PATH); if (servletPath != null) { pathInfo = (String) request.getAttribute(StripesConstants.REQ_ATTR_INCLUDE_PATH_INFO); } else { servletPath = request.getServletPath(); pathInfo = request.getPathInfo(); } if (servletPath == null) return pathInfo == null ? "" : pathInfo; else if (pathInfo == null) return servletPath; else return servletPath + pathInfo; }
public static String getRequestedPath(HttpServletRequest request) { String servletPath, pathInfo; // Check to see if the request is processing an include, and pull the path // information from the appropriate source. servletPath = (String) request.getAttribute(StripesConstants.REQ_ATTR_INCLUDE_PATH); if (servletPath != null) { pathInfo = (String) request.getAttribute(StripesConstants.REQ_ATTR_INCLUDE_PATH_INFO); } else { servletPath = request.getServletPath(); pathInfo = request.getPathInfo(); } if (servletPath == null) return pathInfo == null ? "" : StringUtil.urlDecode(pathInfo); else if (pathInfo == null) return StringUtil.urlDecode(servletPath); else return StringUtil.urlDecode(servletPath + pathInfo); }
diff --git a/xjc/src/com/sun/tools/xjc/Options.java b/xjc/src/com/sun/tools/xjc/Options.java index 2b6aca3e..e31a90e1 100644 --- a/xjc/src/com/sun/tools/xjc/Options.java +++ b/xjc/src/com/sun/tools/xjc/Options.java @@ -1,929 +1,930 @@ /* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.xjc; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Array; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.sun.codemodel.CodeWriter; import com.sun.codemodel.writer.FileCodeWriter; import com.sun.codemodel.writer.PrologCodeWriter; import com.sun.org.apache.xml.internal.resolver.CatalogManager; import com.sun.org.apache.xml.internal.resolver.tools.CatalogResolver; import com.sun.tools.xjc.api.ClassNameAllocator; import com.sun.tools.xjc.api.SpecVersion; import com.sun.tools.xjc.generator.bean.field.FieldRendererFactory; import com.sun.tools.xjc.model.Model; import com.sun.tools.xjc.reader.Util; import com.sun.xml.bind.api.impl.NameConverter; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; /** * Global options. * * <p> * This class stores invocation configuration for XJC. * The configuration in this class shoule be abstract enough so that * it could be parsed from both command-line or Ant. */ public class Options { /** If "-debug" is specified. */ public boolean debugMode; /** If the "-verbose" option is specified. */ public boolean verbose; /** If the "-quiet" option is specified. */ public boolean quiet; /** If the -readOnly option is specified. */ public boolean readOnly; /** No file header comment (to be more friendly with diff.) */ public boolean noFileHeader; /** * Check the source schemas with extra scrutiny. * The exact meaning depends on the schema language. */ public boolean strictCheck =true; /** * If -explicit-annotation option is specified. * <p> * This generates code that works around issues specific to 1.4 runtime. */ public boolean runtime14 = false; /** * If true, try to resolve name conflicts automatically by assigning mechanical numbers. */ public boolean automaticNameConflictResolution = false; /** * strictly follow the compatibility rules and reject schemas that * contain features from App. E.2, use vendor binding extensions */ public static final int STRICT = 1; /** * loosely follow the compatibility rules and allow the use of vendor * binding extensions */ public static final int EXTENSION = 2; /** * this switch determines how carefully the compiler will follow * the compatibility rules in the spec. Either <code>STRICT</code> * or <code>EXTENSION</code>. */ public int compatibilityMode = STRICT; public boolean isExtensionMode() { return compatibilityMode==EXTENSION; } /** * Generates output for the specified version of the runtime. */ public SpecVersion target = SpecVersion.V2_1; /** Target direcoty when producing files. */ public File targetDir = new File("."); /** * Actually stores {@link CatalogResolver}, but the field * type is made to {@link EntityResolver} so that XJC can be * used even if resolver.jar is not available in the classpath. */ public EntityResolver entityResolver = null; /** * Type of input schema language. One of the <code>SCHEMA_XXX</code> * constants. */ private Language schemaLanguage = null; /** * The -p option that should control the default Java package that * will contain the generated code. Null if unspecified. */ public String defaultPackage = null; /** * Similar to the -p option, but this one works with a lower priority, * and customizations overrides this. Used by JAX-RPC. */ public String defaultPackage2 = null; /** * Input schema files as a list of {@link InputSource}s. */ private final List<InputSource> grammars = new ArrayList<InputSource>(); private final List<InputSource> bindFiles = new ArrayList<InputSource>(); // Proxy setting. private String proxyHost = null; private String proxyPort = null; private String proxyUser = null; private String proxyPassword = null; /** * {@link Plugin}s that are enabled in this compilation. */ public final List<Plugin> activePlugins = new ArrayList<Plugin>(); /** * All discovered {@link Plugin}s. * This is lazily parsed, so that we can take '-cp' option into account. * * @see #getAllPlugins() */ private List<Plugin> allPlugins; /** * Set of URIs that plug-ins recognize as extension bindings. */ public final Set<String> pluginURIs = new HashSet<String>(); /** * This allocator has the final say on deciding the class name. */ public ClassNameAllocator classNameAllocator; /** * This switch controls whether or not xjc will generate package level annotations */ public boolean packageLevelAnnotations = true; /** * This {@link FieldRendererFactory} determines how the fields are generated. */ private FieldRendererFactory fieldRendererFactory = new FieldRendererFactory(); /** * Used to detect if two {@link Plugin}s try to overwrite {@link #fieldRendererFactory}. */ private Plugin fieldRendererFactoryOwner = null; /** * If this is non-null, we use this {@link NameConverter} over the one * given in the schema/binding. */ private NameConverter nameConverter = null; /** * Used to detect if two {@link Plugin}s try to overwrite {@link #nameConverter}. */ private Plugin nameConverterOwner = null; /** * Gets the active {@link FieldRendererFactory} that shall be used to build {@link Model}. * * @return always non-null. */ public FieldRendererFactory getFieldRendererFactory() { return fieldRendererFactory; } /** * Sets the {@link FieldRendererFactory}. * * <p> * This method is for plugins to call to set a custom {@link FieldRendererFactory}. * * @param frf * The {@link FieldRendererFactory} to be installed. Must not be null. * @param owner * Identifies the plugin that owns this {@link FieldRendererFactory}. * When two {@link Plugin}s try to call this method, this allows XJC * to report it as a user-friendly error message. * * @throws BadCommandLineException * If a conflit happens, this exception carries a user-friendly error * message, indicating a conflict. */ public void setFieldRendererFactory(FieldRendererFactory frf, Plugin owner) throws BadCommandLineException { // since this method is for plugins, make it bit more fool-proof than usual if(frf==null) throw new IllegalArgumentException(); if(fieldRendererFactoryOwner!=null) { throw new BadCommandLineException( Messages.format(Messages.FIELD_RENDERER_CONFLICT, fieldRendererFactoryOwner.getOptionName(), owner.getOptionName() )); } this.fieldRendererFactoryOwner = owner; this.fieldRendererFactory = frf; } /** * Gets the active {@link NameConverter} that shall be used to build {@link Model}. * * @return can be null, in which case it's up to the binding. */ public NameConverter getNameConverter() { return nameConverter; } /** * Sets the {@link NameConverter}. * * <p> * This method is for plugins to call to set a custom {@link NameConverter}. * * @param nc * The {@link NameConverter} to be installed. Must not be null. * @param owner * Identifies the plugin that owns this {@link NameConverter}. * When two {@link Plugin}s try to call this method, this allows XJC * to report it as a user-friendly error message. * * @throws BadCommandLineException * If a conflit happens, this exception carries a user-friendly error * message, indicating a conflict. */ public void setNameConverter(NameConverter nc, Plugin owner) throws BadCommandLineException { // since this method is for plugins, make it bit more fool-proof than usual if(nc==null) throw new IllegalArgumentException(); if(nameConverter!=null) { throw new BadCommandLineException( Messages.format(Messages.NAME_CONVERTER_CONFLICT, nameConverterOwner.getOptionName(), owner.getOptionName() )); } this.nameConverterOwner = owner; this.nameConverter = nc; } /** * Gets all the {@link Plugin}s discovered so far. * * <p> * A plugins are enumerated when this method is called for the first time, * by taking {@link #classpaths} into account. That means * "-cp plugin.jar" has to come before you specify options to enable it. */ public List<Plugin> getAllPlugins() { if(allPlugins==null) { allPlugins = new ArrayList<Plugin>(); ClassLoader ucl = getUserClassLoader(getClass().getClassLoader()); for( Plugin aug : findServices(Plugin.class,ucl) ) allPlugins.add(aug); } return allPlugins; } public Language getSchemaLanguage() { if( schemaLanguage==null) schemaLanguage = guessSchemaLanguage(); return schemaLanguage; } public void setSchemaLanguage(Language _schemaLanguage) { this.schemaLanguage = _schemaLanguage; } /** Input schema files. */ public InputSource[] getGrammars() { return grammars.toArray(new InputSource[grammars.size()]); } /** * Adds a new input schema. */ public void addGrammar( InputSource is ) { grammars.add(absolutize(is)); } private InputSource fileToInputSource( File source ) { try { String url = source.toURL().toExternalForm(); return new InputSource(Util.escapeSpace(url)); } catch (MalformedURLException e) { return new InputSource(source.getPath()); } } public void addGrammar( File source ) { addGrammar(fileToInputSource(source)); } /** * Recursively scan directories and add all XSD files in it. */ public void addGrammarRecursive( File dir ) { addRecursive(dir,".xsd",grammars); } private void addRecursive( File dir, String suffix, List<InputSource> result ) { File[] files = dir.listFiles(); if(files==null) return; // work defensively for( File f : files ) { if(f.isDirectory()) addRecursive(f,suffix,result); else if(f.getPath().endsWith(suffix)) result.add(absolutize(fileToInputSource(f))); } } private InputSource absolutize(InputSource is) { // absolutize all the system IDs in the input, // so that we can map system IDs to DOM trees. try { URL baseURL = new File(".").getCanonicalFile().toURL(); is.setSystemId( new URL(baseURL,is.getSystemId()).toExternalForm() ); } catch( IOException e ) { // ignore } return is; } /** Input external binding files. */ public InputSource[] getBindFiles() { return bindFiles.toArray(new InputSource[bindFiles.size()]); } /** * Adds a new binding file. */ public void addBindFile( InputSource is ) { bindFiles.add(absolutize(is)); } /** * Adds a new binding file. */ public void addBindFile( File bindFile ) { bindFiles.add(fileToInputSource(bindFile)); } /** * Recursively scan directories and add all ".xjb" files in it. */ public void addBindFileRecursive( File dir ) { addRecursive(dir,".xjb",bindFiles); } public final List<URL> classpaths = new ArrayList<URL>(); /** * Gets a classLoader that can load classes specified via the * -classpath option. */ public URLClassLoader getUserClassLoader( ClassLoader parent ) { return new URLClassLoader( classpaths.toArray(new URL[classpaths.size()]),parent); } /** * Parses an option <code>args[i]</code> and return * the number of tokens consumed. * * @return * 0 if the argument is not understood. Returning 0 * will let the caller report an error. * @exception BadCommandLineException * If the callee wants to provide a custom message for an error. */ public int parseArgument( String[] args, int i ) throws BadCommandLineException { if (args[i].equals("-classpath") || args[i].equals("-cp")) { File file = new File(requireArgument(args[i],args,++i)); try { classpaths.add(file.toURL()); } catch (MalformedURLException e) { throw new BadCommandLineException( Messages.format(Messages.NOT_A_VALID_FILENAME,file),e); } return 2; } if (args[i].equals("-d")) { targetDir = new File(requireArgument("-d",args,++i)); if( !targetDir.exists() ) throw new BadCommandLineException( Messages.format(Messages.NON_EXISTENT_DIR,targetDir)); return 2; } if (args[i].equals("-readOnly")) { readOnly = true; return 1; } if (args[i].equals("-p")) { defaultPackage = requireArgument("-p",args,++i); if(defaultPackage.length()==0) { // user specified default package // there won't be any package to annotate, so disable them // automatically as a usability feature packageLevelAnnotations = false; } return 2; } if (args[i].equals("-debug")) { debugMode = true; verbose = true; return 1; } if (args[i].equals("-nv")) { strictCheck = false; return 1; } if( args[i].equals("-npa")) { packageLevelAnnotations = false; return 1; } if( args[i].equals("-no-header")) { noFileHeader = true; return 1; } if (args[i].equals("-verbose")) { verbose = true; return 1; } if (args[i].equals("-quiet")) { quiet = true; return 1; } if (args[i].equals("-XexplicitAnnotation")) { runtime14 = true; return 1; } if (args[i].equals("-XautoNameResolution")) { automaticNameConflictResolution = true; return 1; } if (args[i].equals("-b")) { addFile(requireArgument("-b",args,++i),bindFiles,".xjb"); return 2; } if (args[i].equals("-dtd")) { schemaLanguage = Language.DTD; return 1; } if (args[i].equals("-relaxng")) { schemaLanguage = Language.RELAXNG; return 1; } if (args[i].equals("-relaxng-compact")) { schemaLanguage = Language.RELAXNG_COMPACT; return 1; } if (args[i].equals("-xmlschema")) { schemaLanguage = Language.XMLSCHEMA; return 1; } if (args[i].equals("-wsdl")) { schemaLanguage = Language.WSDL; return 1; } if (args[i].equals("-extension")) { compatibilityMode = EXTENSION; return 1; } if (args[i].equals("-target")) { String token = requireArgument("-target",args,++i); target = SpecVersion.parse(token); if(target==null) throw new BadCommandLineException(Messages.format(Messages.ILLEGAL_TARGET_VERSION,token)); + return 2; } if (args[i].equals("-httpproxyfile")) { if (i == args.length - 1 || args[i + 1].startsWith("-")) { throw new BadCommandLineException( Messages.format(Messages.MISSING_PROXYFILE)); } File file = new File(args[++i]); if(!file.exists()) { throw new BadCommandLineException( Messages.format(Messages.NO_SUCH_FILE,file)); } try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8")); parseProxy(in.readLine()); in.close(); } catch (IOException e) { throw new BadCommandLineException( Messages.format(Messages.FAILED_TO_PARSE,file,e.getMessage()),e); } return 2; } if (args[i].equals("-httpproxy")) { if (i == args.length - 1 || args[i + 1].startsWith("-")) { throw new BadCommandLineException( Messages.format(Messages.MISSING_PROXY)); } parseProxy(args[++i]); return 2; } if (args[i].equals("-host")) { proxyHost = requireArgument("-host",args,++i); return 2; } if (args[i].equals("-port")) { proxyPort = requireArgument("-port",args,++i); return 2; } if( args[i].equals("-catalog") ) { // use Sun's "XML Entity and URI Resolvers" by Norman Walsh // to resolve external entities. // http://www.sun.com/xml/developers/resolver/ File catalogFile = new File(requireArgument("-catalog",args,++i)); try { addCatalog(catalogFile); } catch (IOException e) { throw new BadCommandLineException( Messages.format(Messages.FAILED_TO_PARSE,catalogFile,e.getMessage()),e); } return 2; } if (args[i].equals("-source")) { String version = requireArgument("-source",args,++i); //For source 1.0 the 1.0 Driver is loaded //Hence anything other than 2.0 is defaulted to //2.0 if( !version.equals("2.0") && !version.equals("2.1") ) throw new BadCommandLineException( Messages.format(Messages.DEFAULT_VERSION)); return 2; } if( args[i].equals("-Xtest-class-name-allocator") ) { classNameAllocator = new ClassNameAllocator() { public String assignClassName(String packageName, String className) { System.out.printf("assignClassName(%s,%s)\n",packageName,className); return className+"_Type"; } }; return 1; } // see if this is one of the extensions for( Plugin plugin : getAllPlugins() ) { try { if( ('-'+plugin.getOptionName()).equals(args[i]) ) { activePlugins.add(plugin); plugin.onActivated(this); pluginURIs.addAll(plugin.getCustomizationURIs()); // give the plugin a chance to parse arguments to this option. // this is new in 2.1, and due to the backward compatibility reason, // if plugin didn't understand it, we still return 1 to indicate // that this option is consumed. int r = plugin.parseArgument(this,args,i); if(r!=0) return r; else return 1; } int r = plugin.parseArgument(this,args,i); if(r!=0) return r; } catch (IOException e) { throw new BadCommandLineException(e.getMessage(),e); } } return 0; // unrecognized } private void parseProxy(String text) throws BadCommandLineException { // syntax is [user[:password]@]proxyHost:proxyPort String token = "([^@:]+)"; Pattern p = Pattern.compile("(?:"+token+"(?:\\:"+token+")?\\@)?"+token+"(?:\\:"+token+")"); Matcher matcher = p.matcher(text); if(!matcher.matches()) throw new BadCommandLineException(Messages.format(Messages.ILLEGAL_PROXY,text)); proxyUser = matcher.group(1); proxyPassword = matcher.group(2); proxyHost = matcher.group(3); proxyPort = matcher.group(4); try { Integer.valueOf(proxyPort); } catch (NumberFormatException e) { throw new BadCommandLineException(Messages.format(Messages.ILLEGAL_PROXY,text)); } } /** * Obtains an operand and reports an error if it's not there. */ public String requireArgument(String optionName, String[] args, int i) throws BadCommandLineException { if (i == args.length || args[i].startsWith("-")) { throw new BadCommandLineException( Messages.format(Messages.MISSING_OPERAND,optionName)); } return args[i]; } /** * Parses a token to a file (or a set of files) * and add them as {@link InputSource} to the specified list. * * @param suffix * If the given token is a directory name, we do a recusive search * and find all files that have the given suffix. */ private void addFile(String name, List<InputSource> target, String suffix) throws BadCommandLineException { Object src; try { src = Util.getFileOrURL(name); } catch (IOException e) { throw new BadCommandLineException( Messages.format(Messages.NOT_A_FILE_NOR_URL,name)); } if(src instanceof URL) { target.add(absolutize(new InputSource(Util.escapeSpace(((URL)src).toExternalForm())))); } else { File fsrc = (File)src; if(fsrc.isDirectory()) { addRecursive(fsrc,suffix,target); } else { target.add(absolutize(fileToInputSource(fsrc))); } } } /** * Adds a new catalog file. */ public void addCatalog(File catalogFile) throws IOException { if(entityResolver==null) { CatalogManager.getStaticManager().setIgnoreMissingProperties(true); entityResolver = new CatalogResolver(true); } ((CatalogResolver)entityResolver).getCatalog().parseCatalog(catalogFile.getPath()); } /** * Parses arguments and fill fields of this object. * * @exception BadCommandLineException * thrown when there's a problem in the command-line arguments */ public void parseArguments( String[] args ) throws BadCommandLineException { for (int i = 0; i < args.length; i++) { if(args[i].length()==0) throw new BadCommandLineException(); if (args[i].charAt(0) == '-') { int j = parseArgument(args,i); if(j==0) throw new BadCommandLineException( Messages.format(Messages.UNRECOGNIZED_PARAMETER, args[i])); i += (j-1); } else { if(args[i].endsWith(".jar")) scanEpisodeFile(new File(args[i])); else addFile(args[i],grammars,".xsd"); } } // configure proxy if (proxyHost != null || proxyPort != null) { if (proxyHost != null && proxyPort != null) { System.setProperty("http.proxyHost", proxyHost); System.setProperty("http.proxyPort", proxyPort); System.setProperty("https.proxyHost", proxyHost); System.setProperty("https.proxyPort", proxyPort); } else if (proxyHost == null) { throw new BadCommandLineException( Messages.format(Messages.MISSING_PROXYHOST)); } else { throw new BadCommandLineException( Messages.format(Messages.MISSING_PROXYPORT)); } if(proxyUser!=null) System.setProperty("http.proxyUser", proxyUser); if(proxyPassword!=null) System.setProperty("http.proxyPassword", proxyPassword); } if (grammars.size() == 0) throw new BadCommandLineException( Messages.format(Messages.MISSING_GRAMMAR)); if( schemaLanguage==null ) schemaLanguage = guessSchemaLanguage(); if(pluginLoadFailure!=null) throw new BadCommandLineException( Messages.format(Messages.PLUGIN_LOAD_FAILURE,pluginLoadFailure)); } /** * Finds the <tt>META-INF/sun-jaxb.episode</tt> file to add as a binding customization. */ private void scanEpisodeFile(File jar) throws BadCommandLineException { try { URLClassLoader ucl = new URLClassLoader(new URL[]{jar.toURL()}); Enumeration<URL> resources = ucl.findResources("META-INF/sun-jaxb.episode"); while (resources.hasMoreElements()) { URL url = resources.nextElement(); addBindFile(new InputSource(url.toExternalForm())); } } catch (IOException e) { throw new BadCommandLineException( Messages.format(Messages.FAILED_TO_LOAD,jar,e.getMessage()), e); } } /** * Guesses the schema language. */ public Language guessSchemaLanguage() { // otherwise, use the file extension. // not a good solution, but very easy. String name = grammars.get(0).getSystemId().toLowerCase(); if (name.endsWith(".rng")) return Language.RELAXNG; if (name.endsWith(".rnc")) return Language.RELAXNG_COMPACT; if (name.endsWith(".dtd")) return Language.DTD; if (name.endsWith(".wsdl")) return Language.WSDL; // by default, assume XML Schema return Language.XMLSCHEMA; } /** * Creates a configured CodeWriter that produces files into the specified directory. */ public CodeWriter createCodeWriter() throws IOException { return createCodeWriter(new FileCodeWriter( targetDir, readOnly )); } /** * Creates a configured CodeWriter that produces files into the specified directory. */ public CodeWriter createCodeWriter( CodeWriter core ) { if(noFileHeader) return core; return new PrologCodeWriter( core,getPrologComment() ); } /** * Gets the string suitable to be used as the prolog comment baked into artifacts. * This is the string like "This file was generated by the JAXB RI on YYYY/mm/dd..." */ public String getPrologComment() { // generate format syntax: <date> 'at' <time> String format = Messages.format(Messages.DATE_FORMAT) + " '" + Messages.format(Messages.AT) + "' " + Messages.format(Messages.TIME_FORMAT); SimpleDateFormat dateFormat = new SimpleDateFormat(format); return Messages.format( Messages.FILE_PROLOG_COMMENT, dateFormat.format(new Date())); } /** * If a plugin failed to load, report. */ private static String pluginLoadFailure; /** * Looks for all "META-INF/services/[className]" files and * create one instance for each class name found inside this file. */ private static <T> T[] findServices( Class<T> clazz, ClassLoader classLoader ) { // if true, print debug output final boolean debug = com.sun.tools.xjc.util.Util.getSystemProperty(Options.class,"findServices")!=null; String serviceId = "META-INF/services/" + clazz.getName(); // used to avoid creating the same instance twice Set<String> classNames = new HashSet<String>(); if(debug) { System.out.println("Looking for "+serviceId+" for add-ons"); } // try to find services in CLASSPATH try { Enumeration<URL> e = classLoader.getResources(serviceId); if(e==null) return (T[])Array.newInstance(clazz,0); ArrayList<T> a = new ArrayList<T>(); while(e.hasMoreElements()) { URL url = e.nextElement(); BufferedReader reader=null; if(debug) { System.out.println("Checking "+url+" for an add-on"); } try { reader = new BufferedReader(new InputStreamReader(url.openStream())); String impl; while((impl = reader.readLine())!=null ) { // try to instanciate the object impl = impl.trim(); if(classNames.add(impl)) { Class implClass = classLoader.loadClass(impl); if(!clazz.isAssignableFrom(implClass)) { pluginLoadFailure = impl+" is not a subclass of "+clazz+". Skipping"; if(debug) System.out.println(pluginLoadFailure); continue; } if(debug) { System.out.println("Attempting to instanciate "+impl); } a.add(clazz.cast(implClass.newInstance())); } } reader.close(); } catch( Exception ex ) { // let it go. StringWriter w = new StringWriter(); ex.printStackTrace(new PrintWriter(w)); pluginLoadFailure = w.toString(); if(debug) { System.out.println(pluginLoadFailure); } if( reader!=null ) { try { reader.close(); } catch( IOException ex2 ) { // ignore } } } } return a.toArray((T[])Array.newInstance(clazz,a.size())); } catch( Throwable e ) { // ignore any error StringWriter w = new StringWriter(); e.printStackTrace(new PrintWriter(w)); pluginLoadFailure = w.toString(); if(debug) { System.out.println(pluginLoadFailure); } return (T[])Array.newInstance(clazz,0); } } // this is a convenient place to expose the build version to xjc plugins public static String getBuildID() { return Messages.format(Messages.BUILD_ID); } }
true
true
public int parseArgument( String[] args, int i ) throws BadCommandLineException { if (args[i].equals("-classpath") || args[i].equals("-cp")) { File file = new File(requireArgument(args[i],args,++i)); try { classpaths.add(file.toURL()); } catch (MalformedURLException e) { throw new BadCommandLineException( Messages.format(Messages.NOT_A_VALID_FILENAME,file),e); } return 2; } if (args[i].equals("-d")) { targetDir = new File(requireArgument("-d",args,++i)); if( !targetDir.exists() ) throw new BadCommandLineException( Messages.format(Messages.NON_EXISTENT_DIR,targetDir)); return 2; } if (args[i].equals("-readOnly")) { readOnly = true; return 1; } if (args[i].equals("-p")) { defaultPackage = requireArgument("-p",args,++i); if(defaultPackage.length()==0) { // user specified default package // there won't be any package to annotate, so disable them // automatically as a usability feature packageLevelAnnotations = false; } return 2; } if (args[i].equals("-debug")) { debugMode = true; verbose = true; return 1; } if (args[i].equals("-nv")) { strictCheck = false; return 1; } if( args[i].equals("-npa")) { packageLevelAnnotations = false; return 1; } if( args[i].equals("-no-header")) { noFileHeader = true; return 1; } if (args[i].equals("-verbose")) { verbose = true; return 1; } if (args[i].equals("-quiet")) { quiet = true; return 1; } if (args[i].equals("-XexplicitAnnotation")) { runtime14 = true; return 1; } if (args[i].equals("-XautoNameResolution")) { automaticNameConflictResolution = true; return 1; } if (args[i].equals("-b")) { addFile(requireArgument("-b",args,++i),bindFiles,".xjb"); return 2; } if (args[i].equals("-dtd")) { schemaLanguage = Language.DTD; return 1; } if (args[i].equals("-relaxng")) { schemaLanguage = Language.RELAXNG; return 1; } if (args[i].equals("-relaxng-compact")) { schemaLanguage = Language.RELAXNG_COMPACT; return 1; } if (args[i].equals("-xmlschema")) { schemaLanguage = Language.XMLSCHEMA; return 1; } if (args[i].equals("-wsdl")) { schemaLanguage = Language.WSDL; return 1; } if (args[i].equals("-extension")) { compatibilityMode = EXTENSION; return 1; } if (args[i].equals("-target")) { String token = requireArgument("-target",args,++i); target = SpecVersion.parse(token); if(target==null) throw new BadCommandLineException(Messages.format(Messages.ILLEGAL_TARGET_VERSION,token)); } if (args[i].equals("-httpproxyfile")) { if (i == args.length - 1 || args[i + 1].startsWith("-")) { throw new BadCommandLineException( Messages.format(Messages.MISSING_PROXYFILE)); } File file = new File(args[++i]); if(!file.exists()) { throw new BadCommandLineException( Messages.format(Messages.NO_SUCH_FILE,file)); } try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8")); parseProxy(in.readLine()); in.close(); } catch (IOException e) { throw new BadCommandLineException( Messages.format(Messages.FAILED_TO_PARSE,file,e.getMessage()),e); } return 2; } if (args[i].equals("-httpproxy")) { if (i == args.length - 1 || args[i + 1].startsWith("-")) { throw new BadCommandLineException( Messages.format(Messages.MISSING_PROXY)); } parseProxy(args[++i]); return 2; } if (args[i].equals("-host")) { proxyHost = requireArgument("-host",args,++i); return 2; } if (args[i].equals("-port")) { proxyPort = requireArgument("-port",args,++i); return 2; } if( args[i].equals("-catalog") ) { // use Sun's "XML Entity and URI Resolvers" by Norman Walsh // to resolve external entities. // http://www.sun.com/xml/developers/resolver/ File catalogFile = new File(requireArgument("-catalog",args,++i)); try { addCatalog(catalogFile); } catch (IOException e) { throw new BadCommandLineException( Messages.format(Messages.FAILED_TO_PARSE,catalogFile,e.getMessage()),e); } return 2; } if (args[i].equals("-source")) { String version = requireArgument("-source",args,++i); //For source 1.0 the 1.0 Driver is loaded //Hence anything other than 2.0 is defaulted to //2.0 if( !version.equals("2.0") && !version.equals("2.1") ) throw new BadCommandLineException( Messages.format(Messages.DEFAULT_VERSION)); return 2; } if( args[i].equals("-Xtest-class-name-allocator") ) { classNameAllocator = new ClassNameAllocator() { public String assignClassName(String packageName, String className) { System.out.printf("assignClassName(%s,%s)\n",packageName,className); return className+"_Type"; } }; return 1; } // see if this is one of the extensions for( Plugin plugin : getAllPlugins() ) { try { if( ('-'+plugin.getOptionName()).equals(args[i]) ) { activePlugins.add(plugin); plugin.onActivated(this); pluginURIs.addAll(plugin.getCustomizationURIs()); // give the plugin a chance to parse arguments to this option. // this is new in 2.1, and due to the backward compatibility reason, // if plugin didn't understand it, we still return 1 to indicate // that this option is consumed. int r = plugin.parseArgument(this,args,i); if(r!=0) return r; else return 1; } int r = plugin.parseArgument(this,args,i); if(r!=0) return r; } catch (IOException e) { throw new BadCommandLineException(e.getMessage(),e); } } return 0; // unrecognized }
public int parseArgument( String[] args, int i ) throws BadCommandLineException { if (args[i].equals("-classpath") || args[i].equals("-cp")) { File file = new File(requireArgument(args[i],args,++i)); try { classpaths.add(file.toURL()); } catch (MalformedURLException e) { throw new BadCommandLineException( Messages.format(Messages.NOT_A_VALID_FILENAME,file),e); } return 2; } if (args[i].equals("-d")) { targetDir = new File(requireArgument("-d",args,++i)); if( !targetDir.exists() ) throw new BadCommandLineException( Messages.format(Messages.NON_EXISTENT_DIR,targetDir)); return 2; } if (args[i].equals("-readOnly")) { readOnly = true; return 1; } if (args[i].equals("-p")) { defaultPackage = requireArgument("-p",args,++i); if(defaultPackage.length()==0) { // user specified default package // there won't be any package to annotate, so disable them // automatically as a usability feature packageLevelAnnotations = false; } return 2; } if (args[i].equals("-debug")) { debugMode = true; verbose = true; return 1; } if (args[i].equals("-nv")) { strictCheck = false; return 1; } if( args[i].equals("-npa")) { packageLevelAnnotations = false; return 1; } if( args[i].equals("-no-header")) { noFileHeader = true; return 1; } if (args[i].equals("-verbose")) { verbose = true; return 1; } if (args[i].equals("-quiet")) { quiet = true; return 1; } if (args[i].equals("-XexplicitAnnotation")) { runtime14 = true; return 1; } if (args[i].equals("-XautoNameResolution")) { automaticNameConflictResolution = true; return 1; } if (args[i].equals("-b")) { addFile(requireArgument("-b",args,++i),bindFiles,".xjb"); return 2; } if (args[i].equals("-dtd")) { schemaLanguage = Language.DTD; return 1; } if (args[i].equals("-relaxng")) { schemaLanguage = Language.RELAXNG; return 1; } if (args[i].equals("-relaxng-compact")) { schemaLanguage = Language.RELAXNG_COMPACT; return 1; } if (args[i].equals("-xmlschema")) { schemaLanguage = Language.XMLSCHEMA; return 1; } if (args[i].equals("-wsdl")) { schemaLanguage = Language.WSDL; return 1; } if (args[i].equals("-extension")) { compatibilityMode = EXTENSION; return 1; } if (args[i].equals("-target")) { String token = requireArgument("-target",args,++i); target = SpecVersion.parse(token); if(target==null) throw new BadCommandLineException(Messages.format(Messages.ILLEGAL_TARGET_VERSION,token)); return 2; } if (args[i].equals("-httpproxyfile")) { if (i == args.length - 1 || args[i + 1].startsWith("-")) { throw new BadCommandLineException( Messages.format(Messages.MISSING_PROXYFILE)); } File file = new File(args[++i]); if(!file.exists()) { throw new BadCommandLineException( Messages.format(Messages.NO_SUCH_FILE,file)); } try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8")); parseProxy(in.readLine()); in.close(); } catch (IOException e) { throw new BadCommandLineException( Messages.format(Messages.FAILED_TO_PARSE,file,e.getMessage()),e); } return 2; } if (args[i].equals("-httpproxy")) { if (i == args.length - 1 || args[i + 1].startsWith("-")) { throw new BadCommandLineException( Messages.format(Messages.MISSING_PROXY)); } parseProxy(args[++i]); return 2; } if (args[i].equals("-host")) { proxyHost = requireArgument("-host",args,++i); return 2; } if (args[i].equals("-port")) { proxyPort = requireArgument("-port",args,++i); return 2; } if( args[i].equals("-catalog") ) { // use Sun's "XML Entity and URI Resolvers" by Norman Walsh // to resolve external entities. // http://www.sun.com/xml/developers/resolver/ File catalogFile = new File(requireArgument("-catalog",args,++i)); try { addCatalog(catalogFile); } catch (IOException e) { throw new BadCommandLineException( Messages.format(Messages.FAILED_TO_PARSE,catalogFile,e.getMessage()),e); } return 2; } if (args[i].equals("-source")) { String version = requireArgument("-source",args,++i); //For source 1.0 the 1.0 Driver is loaded //Hence anything other than 2.0 is defaulted to //2.0 if( !version.equals("2.0") && !version.equals("2.1") ) throw new BadCommandLineException( Messages.format(Messages.DEFAULT_VERSION)); return 2; } if( args[i].equals("-Xtest-class-name-allocator") ) { classNameAllocator = new ClassNameAllocator() { public String assignClassName(String packageName, String className) { System.out.printf("assignClassName(%s,%s)\n",packageName,className); return className+"_Type"; } }; return 1; } // see if this is one of the extensions for( Plugin plugin : getAllPlugins() ) { try { if( ('-'+plugin.getOptionName()).equals(args[i]) ) { activePlugins.add(plugin); plugin.onActivated(this); pluginURIs.addAll(plugin.getCustomizationURIs()); // give the plugin a chance to parse arguments to this option. // this is new in 2.1, and due to the backward compatibility reason, // if plugin didn't understand it, we still return 1 to indicate // that this option is consumed. int r = plugin.parseArgument(this,args,i); if(r!=0) return r; else return 1; } int r = plugin.parseArgument(this,args,i); if(r!=0) return r; } catch (IOException e) { throw new BadCommandLineException(e.getMessage(),e); } } return 0; // unrecognized }
diff --git a/src/main/java/org/apmem/tools/layouts/FlowLayout.java b/src/main/java/org/apmem/tools/layouts/FlowLayout.java index 56e8f3a..af22ab7 100644 --- a/src/main/java/org/apmem/tools/layouts/FlowLayout.java +++ b/src/main/java/org/apmem/tools/layouts/FlowLayout.java @@ -1,327 +1,327 @@ package org.apmem.tools.layouts; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import org.apmem.tools.R; public class FlowLayout extends ViewGroup { public static final int HORIZONTAL = 0; public static final int VERTICAL = 1; private int horizontalSpacing = 0; private int verticalSpacing = 0; private int orientation = 0; private boolean debugDraw = false; public FlowLayout(Context context) { super(context); this.readStyleParameters(context, null); } public FlowLayout(Context context, AttributeSet attributeSet) { super(context, attributeSet); this.readStyleParameters(context, attributeSet); } public FlowLayout(Context context, AttributeSet attributeSet, int defStyle) { super(context, attributeSet, defStyle); this.readStyleParameters(context, attributeSet); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int sizeWidth = MeasureSpec.getSize(widthMeasureSpec) - this.getPaddingRight() - this.getPaddingLeft(); int sizeHeight = MeasureSpec.getSize(heightMeasureSpec) - this.getPaddingRight() - this.getPaddingLeft(); int modeWidth = MeasureSpec.getMode(widthMeasureSpec); int modeHeight = MeasureSpec.getMode(heightMeasureSpec); int size; int mode; if (orientation == HORIZONTAL) { size = sizeWidth; mode = modeWidth; } else { size = sizeHeight; mode = modeHeight; } int lineThicknessWithSpacing = 0; int lineThickness = 0; int lineLengthWithSpacing = 0; int lineLength; int prevLinePosition = 0; int controlMaxLength = 0; int controlMaxThickness = 0; final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } child.measure( MeasureSpec.makeMeasureSpec(sizeWidth, modeWidth == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST : modeWidth), MeasureSpec.makeMeasureSpec(sizeHeight, modeHeight == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST : modeHeight) ); LayoutParams lp = (LayoutParams) child.getLayoutParams(); int hSpacing = this.getHorizontalSpacing(lp); int vSpacing = this.getVerticalSpacing(lp); int childWidth = child.getMeasuredWidth(); int childHeight = child.getMeasuredHeight(); int childLength; int childThickness; int spacingLength; int spacingThickness; if (orientation == HORIZONTAL) { childLength = childWidth; childThickness = childHeight; spacingLength = hSpacing; spacingThickness = vSpacing; } else { childLength = childHeight; childThickness = childWidth; spacingLength = vSpacing; spacingThickness = hSpacing; } lineLength = lineLengthWithSpacing + childLength; lineLengthWithSpacing = lineLength + spacingLength; boolean newLine = lp.newLine || (mode != MeasureSpec.UNSPECIFIED && lineLength > size); if (newLine) { prevLinePosition = prevLinePosition + lineThicknessWithSpacing; lineThickness = childThickness; lineLength = childLength; lineThicknessWithSpacing = childThickness + spacingThickness; lineLengthWithSpacing = lineLength + spacingLength; } lineThicknessWithSpacing = Math.max(lineThicknessWithSpacing, childThickness + spacingThickness); lineThickness = Math.max(lineThickness, childThickness); int posX; int posY; if (orientation == HORIZONTAL) { posX = getPaddingLeft() + lineLength - childLength; posY = getPaddingTop() + prevLinePosition; } else { posX = getPaddingLeft() + prevLinePosition; posY = getPaddingTop() + lineLength - childHeight; } lp.setPosition(posX, posY); controlMaxLength = Math.max(controlMaxLength, lineLength); controlMaxThickness = prevLinePosition + lineThickness; } /* need to take far side padding into account */ if (orientation == HORIZONTAL) { controlMaxLength += getPaddingRight(); - controlMaxThickness += getPaddingBottom(); + controlMaxThickness = controlMaxThickness+getPaddingBottom()+getPaddingTop(); } else { controlMaxLength += getPaddingBottom(); controlMaxThickness += getPaddingRight(); } if (orientation == HORIZONTAL) { this.setMeasuredDimension(resolveSize(controlMaxLength, widthMeasureSpec), resolveSize(controlMaxThickness, heightMeasureSpec)); } else { this.setMeasuredDimension(resolveSize(controlMaxThickness, widthMeasureSpec), resolveSize(controlMaxLength, heightMeasureSpec)); } } private int getVerticalSpacing(LayoutParams lp) { int vSpacing; if (lp.verticalSpacingSpecified()) { vSpacing = lp.verticalSpacing; } else { vSpacing = this.verticalSpacing; } return vSpacing; } private int getHorizontalSpacing(LayoutParams lp) { int hSpacing; if (lp.horizontalSpacingSpecified()) { hSpacing = lp.horizontalSpacing; } else { hSpacing = this.horizontalSpacing; } return hSpacing; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = getChildCount(); for (int i = 0; i < count; i++) { View child = getChildAt(i); LayoutParams lp = (LayoutParams) child.getLayoutParams(); child.layout(lp.x, lp.y, lp.x + child.getMeasuredWidth(), lp.y + child.getMeasuredHeight()); } } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { boolean more = super.drawChild(canvas, child, drawingTime); this.drawDebugInfo(canvas, child); return more; } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof LayoutParams; } @Override protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); } @Override public LayoutParams generateLayoutParams(AttributeSet attributeSet) { return new LayoutParams(getContext(), attributeSet); } @Override protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return new LayoutParams(p); } private void readStyleParameters(Context context, AttributeSet attributeSet) { TypedArray a = context.obtainStyledAttributes(attributeSet, R.styleable.FlowLayout); try { horizontalSpacing = a.getDimensionPixelSize(R.styleable.FlowLayout_horizontalSpacing, 0); verticalSpacing = a.getDimensionPixelSize(R.styleable.FlowLayout_verticalSpacing, 0); orientation = a.getInteger(R.styleable.FlowLayout_orientation, HORIZONTAL); debugDraw = a.getBoolean(R.styleable.FlowLayout_debugDraw, false); } finally { a.recycle(); } } private void drawDebugInfo(Canvas canvas, View child) { if (!debugDraw) { return; } Paint childPaint = this.createPaint(0xffffff00); Paint layoutPaint = this.createPaint(0xff00ff00); Paint newLinePaint = this.createPaint(0xffff0000); LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.horizontalSpacing > 0) { float x = child.getRight(); float y = child.getTop() + child.getHeight() / 2.0f; canvas.drawLine(x, y, x + lp.horizontalSpacing, y, childPaint); canvas.drawLine(x + lp.horizontalSpacing - 4.0f, y - 4.0f, x + lp.horizontalSpacing, y, childPaint); canvas.drawLine(x + lp.horizontalSpacing - 4.0f, y + 4.0f, x + lp.horizontalSpacing, y, childPaint); } else if (this.horizontalSpacing > 0) { float x = child.getRight(); float y = child.getTop() + child.getHeight() / 2.0f; canvas.drawLine(x, y, x + this.horizontalSpacing, y, layoutPaint); canvas.drawLine(x + this.horizontalSpacing - 4.0f, y - 4.0f, x + this.horizontalSpacing, y, layoutPaint); canvas.drawLine(x + this.horizontalSpacing - 4.0f, y + 4.0f, x + this.horizontalSpacing, y, layoutPaint); } if (lp.verticalSpacing > 0) { float x = child.getLeft() + child.getWidth() / 2.0f; float y = child.getBottom(); canvas.drawLine(x, y, x, y + lp.verticalSpacing, childPaint); canvas.drawLine(x - 4.0f, y + lp.verticalSpacing - 4.0f, x, y + lp.verticalSpacing, childPaint); canvas.drawLine(x + 4.0f, y + lp.verticalSpacing - 4.0f, x, y + lp.verticalSpacing, childPaint); } else if (this.verticalSpacing > 0) { float x = child.getLeft() + child.getWidth() / 2.0f; float y = child.getBottom(); canvas.drawLine(x, y, x, y + this.verticalSpacing, layoutPaint); canvas.drawLine(x - 4.0f, y + this.verticalSpacing - 4.0f, x, y + this.verticalSpacing, layoutPaint); canvas.drawLine(x + 4.0f, y + this.verticalSpacing - 4.0f, x, y + this.verticalSpacing, layoutPaint); } if (lp.newLine) { if (orientation == HORIZONTAL) { float x = child.getLeft(); float y = child.getTop() + child.getHeight() / 2.0f; canvas.drawLine(x, y - 6.0f, x, y + 6.0f, newLinePaint); } else { float x = child.getLeft() + child.getWidth() / 2.0f; float y = child.getTop(); canvas.drawLine(x - 6.0f, y, x + 6.0f, y, newLinePaint); } } } private Paint createPaint(int color) { Paint paint = new Paint(); paint.setAntiAlias(true); paint.setColor(color); paint.setStrokeWidth(2.0f); return paint; } public static class LayoutParams extends ViewGroup.LayoutParams { private static int NO_SPACING = -1; private int x; private int y; private int horizontalSpacing = NO_SPACING; private int verticalSpacing = NO_SPACING; private boolean newLine = false; public LayoutParams(Context context, AttributeSet attributeSet) { super(context, attributeSet); this.readStyleParameters(context, attributeSet); } public LayoutParams(int width, int height) { super(width, height); } public LayoutParams(ViewGroup.LayoutParams layoutParams) { super(layoutParams); } public boolean horizontalSpacingSpecified() { return horizontalSpacing != NO_SPACING; } public boolean verticalSpacingSpecified() { return verticalSpacing != NO_SPACING; } public void setPosition(int x, int y) { this.x = x; this.y = y; } private void readStyleParameters(Context context, AttributeSet attributeSet) { TypedArray a = context.obtainStyledAttributes(attributeSet, R.styleable.FlowLayout_LayoutParams); try { horizontalSpacing = a.getDimensionPixelSize(R.styleable.FlowLayout_LayoutParams_layout_horizontalSpacing, NO_SPACING); verticalSpacing = a.getDimensionPixelSize(R.styleable.FlowLayout_LayoutParams_layout_verticalSpacing, NO_SPACING); newLine = a.getBoolean(R.styleable.FlowLayout_LayoutParams_layout_newLine, false); } finally { a.recycle(); } } } }
true
true
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int sizeWidth = MeasureSpec.getSize(widthMeasureSpec) - this.getPaddingRight() - this.getPaddingLeft(); int sizeHeight = MeasureSpec.getSize(heightMeasureSpec) - this.getPaddingRight() - this.getPaddingLeft(); int modeWidth = MeasureSpec.getMode(widthMeasureSpec); int modeHeight = MeasureSpec.getMode(heightMeasureSpec); int size; int mode; if (orientation == HORIZONTAL) { size = sizeWidth; mode = modeWidth; } else { size = sizeHeight; mode = modeHeight; } int lineThicknessWithSpacing = 0; int lineThickness = 0; int lineLengthWithSpacing = 0; int lineLength; int prevLinePosition = 0; int controlMaxLength = 0; int controlMaxThickness = 0; final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } child.measure( MeasureSpec.makeMeasureSpec(sizeWidth, modeWidth == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST : modeWidth), MeasureSpec.makeMeasureSpec(sizeHeight, modeHeight == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST : modeHeight) ); LayoutParams lp = (LayoutParams) child.getLayoutParams(); int hSpacing = this.getHorizontalSpacing(lp); int vSpacing = this.getVerticalSpacing(lp); int childWidth = child.getMeasuredWidth(); int childHeight = child.getMeasuredHeight(); int childLength; int childThickness; int spacingLength; int spacingThickness; if (orientation == HORIZONTAL) { childLength = childWidth; childThickness = childHeight; spacingLength = hSpacing; spacingThickness = vSpacing; } else { childLength = childHeight; childThickness = childWidth; spacingLength = vSpacing; spacingThickness = hSpacing; } lineLength = lineLengthWithSpacing + childLength; lineLengthWithSpacing = lineLength + spacingLength; boolean newLine = lp.newLine || (mode != MeasureSpec.UNSPECIFIED && lineLength > size); if (newLine) { prevLinePosition = prevLinePosition + lineThicknessWithSpacing; lineThickness = childThickness; lineLength = childLength; lineThicknessWithSpacing = childThickness + spacingThickness; lineLengthWithSpacing = lineLength + spacingLength; } lineThicknessWithSpacing = Math.max(lineThicknessWithSpacing, childThickness + spacingThickness); lineThickness = Math.max(lineThickness, childThickness); int posX; int posY; if (orientation == HORIZONTAL) { posX = getPaddingLeft() + lineLength - childLength; posY = getPaddingTop() + prevLinePosition; } else { posX = getPaddingLeft() + prevLinePosition; posY = getPaddingTop() + lineLength - childHeight; } lp.setPosition(posX, posY); controlMaxLength = Math.max(controlMaxLength, lineLength); controlMaxThickness = prevLinePosition + lineThickness; } /* need to take far side padding into account */ if (orientation == HORIZONTAL) { controlMaxLength += getPaddingRight(); controlMaxThickness += getPaddingBottom(); } else { controlMaxLength += getPaddingBottom(); controlMaxThickness += getPaddingRight(); } if (orientation == HORIZONTAL) { this.setMeasuredDimension(resolveSize(controlMaxLength, widthMeasureSpec), resolveSize(controlMaxThickness, heightMeasureSpec)); } else { this.setMeasuredDimension(resolveSize(controlMaxThickness, widthMeasureSpec), resolveSize(controlMaxLength, heightMeasureSpec)); } }
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int sizeWidth = MeasureSpec.getSize(widthMeasureSpec) - this.getPaddingRight() - this.getPaddingLeft(); int sizeHeight = MeasureSpec.getSize(heightMeasureSpec) - this.getPaddingRight() - this.getPaddingLeft(); int modeWidth = MeasureSpec.getMode(widthMeasureSpec); int modeHeight = MeasureSpec.getMode(heightMeasureSpec); int size; int mode; if (orientation == HORIZONTAL) { size = sizeWidth; mode = modeWidth; } else { size = sizeHeight; mode = modeHeight; } int lineThicknessWithSpacing = 0; int lineThickness = 0; int lineLengthWithSpacing = 0; int lineLength; int prevLinePosition = 0; int controlMaxLength = 0; int controlMaxThickness = 0; final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } child.measure( MeasureSpec.makeMeasureSpec(sizeWidth, modeWidth == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST : modeWidth), MeasureSpec.makeMeasureSpec(sizeHeight, modeHeight == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST : modeHeight) ); LayoutParams lp = (LayoutParams) child.getLayoutParams(); int hSpacing = this.getHorizontalSpacing(lp); int vSpacing = this.getVerticalSpacing(lp); int childWidth = child.getMeasuredWidth(); int childHeight = child.getMeasuredHeight(); int childLength; int childThickness; int spacingLength; int spacingThickness; if (orientation == HORIZONTAL) { childLength = childWidth; childThickness = childHeight; spacingLength = hSpacing; spacingThickness = vSpacing; } else { childLength = childHeight; childThickness = childWidth; spacingLength = vSpacing; spacingThickness = hSpacing; } lineLength = lineLengthWithSpacing + childLength; lineLengthWithSpacing = lineLength + spacingLength; boolean newLine = lp.newLine || (mode != MeasureSpec.UNSPECIFIED && lineLength > size); if (newLine) { prevLinePosition = prevLinePosition + lineThicknessWithSpacing; lineThickness = childThickness; lineLength = childLength; lineThicknessWithSpacing = childThickness + spacingThickness; lineLengthWithSpacing = lineLength + spacingLength; } lineThicknessWithSpacing = Math.max(lineThicknessWithSpacing, childThickness + spacingThickness); lineThickness = Math.max(lineThickness, childThickness); int posX; int posY; if (orientation == HORIZONTAL) { posX = getPaddingLeft() + lineLength - childLength; posY = getPaddingTop() + prevLinePosition; } else { posX = getPaddingLeft() + prevLinePosition; posY = getPaddingTop() + lineLength - childHeight; } lp.setPosition(posX, posY); controlMaxLength = Math.max(controlMaxLength, lineLength); controlMaxThickness = prevLinePosition + lineThickness; } /* need to take far side padding into account */ if (orientation == HORIZONTAL) { controlMaxLength += getPaddingRight(); controlMaxThickness = controlMaxThickness+getPaddingBottom()+getPaddingTop(); } else { controlMaxLength += getPaddingBottom(); controlMaxThickness += getPaddingRight(); } if (orientation == HORIZONTAL) { this.setMeasuredDimension(resolveSize(controlMaxLength, widthMeasureSpec), resolveSize(controlMaxThickness, heightMeasureSpec)); } else { this.setMeasuredDimension(resolveSize(controlMaxThickness, widthMeasureSpec), resolveSize(controlMaxLength, heightMeasureSpec)); } }
diff --git a/server/src/main/java/io/druid/segment/realtime/plumber/FlushingPlumber.java b/server/src/main/java/io/druid/segment/realtime/plumber/FlushingPlumber.java index 9f6e4c41ac..a69d4bef4f 100644 --- a/server/src/main/java/io/druid/segment/realtime/plumber/FlushingPlumber.java +++ b/server/src/main/java/io/druid/segment/realtime/plumber/FlushingPlumber.java @@ -1,195 +1,195 @@ package io.druid.segment.realtime.plumber; import com.google.common.collect.Lists; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.metamx.common.concurrent.ScheduledExecutors; import com.metamx.emitter.EmittingLogger; import com.metamx.emitter.service.ServiceEmitter; import io.druid.common.guava.ThreadRenamingCallable; import io.druid.query.QueryRunnerFactoryConglomerate; import io.druid.segment.IndexGranularity; import io.druid.segment.realtime.FireDepartmentMetrics; import io.druid.segment.realtime.Schema; import io.druid.server.coordination.DataSegmentAnnouncer; import org.joda.time.DateTime; import org.joda.time.Duration; import org.joda.time.Period; import java.io.File; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; /** */ public class FlushingPlumber extends RealtimePlumber { private static final EmittingLogger log = new EmittingLogger(FlushingPlumber.class); private final Duration flushDuration; private volatile ScheduledExecutorService flushScheduledExec = null; private volatile boolean stopped = false; public FlushingPlumber( Duration flushDuration, Period windowPeriod, File basePersistDirectory, IndexGranularity segmentGranularity, Schema schema, FireDepartmentMetrics metrics, RejectionPolicy rejectionPolicy, ServiceEmitter emitter, QueryRunnerFactoryConglomerate conglomerate, DataSegmentAnnouncer segmentAnnouncer, ExecutorService queryExecutorService, VersioningPolicy versioningPolicy ) { super( windowPeriod, basePersistDirectory, segmentGranularity, schema, metrics, rejectionPolicy, emitter, conglomerate, segmentAnnouncer, queryExecutorService, versioningPolicy, null, null, null ); this.flushDuration = flushDuration; } @Override public void startJob() { log.info("Starting job for %s", getSchema().getDataSource()); computeBaseDir(getSchema()).mkdirs(); initializeExecutors(); if (flushScheduledExec == null) { flushScheduledExec = Executors.newScheduledThreadPool( 1, new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("flushing_scheduled_%d") .build() ); } bootstrapSinksFromDisk(); startFlushThread(); } protected void flushAfterDuration(final long truncatedTime, final Sink sink) { log.info( "Abandoning segment %s at %s", sink.getSegment().getIdentifier(), new DateTime().plusMillis(flushDuration.toPeriod().getMillis()) ); ScheduledExecutors.scheduleWithFixedDelay( flushScheduledExec, flushDuration, new Callable<ScheduledExecutors.Signal>() { @Override public ScheduledExecutors.Signal call() throws Exception { log.info("Abandoning segment %s", sink.getSegment().getIdentifier()); abandonSegment(truncatedTime, sink); return ScheduledExecutors.Signal.STOP; } } ); } private void startFlushThread() { final long truncatedNow = getSegmentGranularity().truncate(new DateTime()).getMillis(); final long windowMillis = getWindowPeriod().toStandardDuration().getMillis(); log.info( "Expect to run at [%s]", new DateTime().plus( new Duration(System.currentTimeMillis(), getSegmentGranularity().increment(truncatedNow) + windowMillis) ) ); ScheduledExecutors .scheduleAtFixedRate( flushScheduledExec, new Duration(System.currentTimeMillis(), getSegmentGranularity().increment(truncatedNow) + windowMillis), new Duration(truncatedNow, getSegmentGranularity().increment(truncatedNow)), new ThreadRenamingCallable<ScheduledExecutors.Signal>( String.format( "%s-flusher-%d", getSchema().getDataSource(), getSchema().getShardSpec().getPartitionNum() ) ) { @Override public ScheduledExecutors.Signal doCall() { if (stopped) { log.info("Stopping flusher thread"); return ScheduledExecutors.Signal.STOP; } long minTimestamp = getSegmentGranularity().truncate( getRejectionPolicy().getCurrMaxTime().minus(windowMillis) ).getMillis(); List<Map.Entry<Long, Sink>> sinksToPush = Lists.newArrayList(); for (Map.Entry<Long, Sink> entry : getSinks().entrySet()) { final Long intervalStart = entry.getKey(); if (intervalStart < minTimestamp) { - log.info("Adding entry[%s] for merge and push.", entry); + log.info("Adding entry[%s] to flush.", entry); sinksToPush.add(entry); } } for (final Map.Entry<Long, Sink> entry : sinksToPush) { flushAfterDuration(entry.getKey(), entry.getValue()); } if (stopped) { - log.info("Stopping merge-n-push overseer thread"); + log.info("Stopping flusher thread"); return ScheduledExecutors.Signal.STOP; } else { return ScheduledExecutors.Signal.REPEAT; } } } ); } @Override public void finishJob() { log.info("Stopping job"); for (final Map.Entry<Long, Sink> entry : getSinks().entrySet()) { flushAfterDuration(entry.getKey(), entry.getValue()); } shutdownExecutors(); if (flushScheduledExec != null) { flushScheduledExec.shutdown(); } stopped = true; } }
false
true
private void startFlushThread() { final long truncatedNow = getSegmentGranularity().truncate(new DateTime()).getMillis(); final long windowMillis = getWindowPeriod().toStandardDuration().getMillis(); log.info( "Expect to run at [%s]", new DateTime().plus( new Duration(System.currentTimeMillis(), getSegmentGranularity().increment(truncatedNow) + windowMillis) ) ); ScheduledExecutors .scheduleAtFixedRate( flushScheduledExec, new Duration(System.currentTimeMillis(), getSegmentGranularity().increment(truncatedNow) + windowMillis), new Duration(truncatedNow, getSegmentGranularity().increment(truncatedNow)), new ThreadRenamingCallable<ScheduledExecutors.Signal>( String.format( "%s-flusher-%d", getSchema().getDataSource(), getSchema().getShardSpec().getPartitionNum() ) ) { @Override public ScheduledExecutors.Signal doCall() { if (stopped) { log.info("Stopping flusher thread"); return ScheduledExecutors.Signal.STOP; } long minTimestamp = getSegmentGranularity().truncate( getRejectionPolicy().getCurrMaxTime().minus(windowMillis) ).getMillis(); List<Map.Entry<Long, Sink>> sinksToPush = Lists.newArrayList(); for (Map.Entry<Long, Sink> entry : getSinks().entrySet()) { final Long intervalStart = entry.getKey(); if (intervalStart < minTimestamp) { log.info("Adding entry[%s] for merge and push.", entry); sinksToPush.add(entry); } } for (final Map.Entry<Long, Sink> entry : sinksToPush) { flushAfterDuration(entry.getKey(), entry.getValue()); } if (stopped) { log.info("Stopping merge-n-push overseer thread"); return ScheduledExecutors.Signal.STOP; } else { return ScheduledExecutors.Signal.REPEAT; } } } ); }
private void startFlushThread() { final long truncatedNow = getSegmentGranularity().truncate(new DateTime()).getMillis(); final long windowMillis = getWindowPeriod().toStandardDuration().getMillis(); log.info( "Expect to run at [%s]", new DateTime().plus( new Duration(System.currentTimeMillis(), getSegmentGranularity().increment(truncatedNow) + windowMillis) ) ); ScheduledExecutors .scheduleAtFixedRate( flushScheduledExec, new Duration(System.currentTimeMillis(), getSegmentGranularity().increment(truncatedNow) + windowMillis), new Duration(truncatedNow, getSegmentGranularity().increment(truncatedNow)), new ThreadRenamingCallable<ScheduledExecutors.Signal>( String.format( "%s-flusher-%d", getSchema().getDataSource(), getSchema().getShardSpec().getPartitionNum() ) ) { @Override public ScheduledExecutors.Signal doCall() { if (stopped) { log.info("Stopping flusher thread"); return ScheduledExecutors.Signal.STOP; } long minTimestamp = getSegmentGranularity().truncate( getRejectionPolicy().getCurrMaxTime().minus(windowMillis) ).getMillis(); List<Map.Entry<Long, Sink>> sinksToPush = Lists.newArrayList(); for (Map.Entry<Long, Sink> entry : getSinks().entrySet()) { final Long intervalStart = entry.getKey(); if (intervalStart < minTimestamp) { log.info("Adding entry[%s] to flush.", entry); sinksToPush.add(entry); } } for (final Map.Entry<Long, Sink> entry : sinksToPush) { flushAfterDuration(entry.getKey(), entry.getValue()); } if (stopped) { log.info("Stopping flusher thread"); return ScheduledExecutors.Signal.STOP; } else { return ScheduledExecutors.Signal.REPEAT; } } } ); }
diff --git a/src/net/sf/freecol/server/ai/mission/PioneeringMission.java b/src/net/sf/freecol/server/ai/mission/PioneeringMission.java index 55faea690..b87ecdf6f 100644 --- a/src/net/sf/freecol/server/ai/mission/PioneeringMission.java +++ b/src/net/sf/freecol/server/ai/mission/PioneeringMission.java @@ -1,430 +1,431 @@ package net.sf.freecol.server.ai.mission; import java.io.IOException; import java.util.Iterator; import java.util.logging.Logger; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import net.sf.freecol.common.model.GoalDecider; import net.sf.freecol.common.model.Goods; import net.sf.freecol.common.model.PathNode; import net.sf.freecol.common.model.Tile; import net.sf.freecol.common.model.Unit; import net.sf.freecol.common.networking.Connection; import net.sf.freecol.common.networking.Message; import net.sf.freecol.server.ai.AIColony; import net.sf.freecol.server.ai.AIMain; import net.sf.freecol.server.ai.AIObject; import net.sf.freecol.server.ai.AIPlayer; import net.sf.freecol.server.ai.AIUnit; import net.sf.freecol.server.ai.TileImprovement; import org.w3c.dom.Element; /** * Mission for controlling a pioneer. * * @see Unit#isPioneer */ public class PioneeringMission extends Mission { /* * TODO-LATER: "updateTileImprovement" should be called * only once (in the beginning of the turn). */ private static final Logger logger = Logger.getLogger(PioneeringMission.class.getName()); public static final String COPYRIGHT = "Copyright (C) 2003-2005 The FreeCol Team"; public static final String LICENSE = "http://www.gnu.org/licenses/gpl.html"; public static final String REVISION = "$Revision$"; private TileImprovement tileImprovement = null; /** * Temporary variable for skipping the mission. */ private boolean skipMission = false; /** * Creates a mission for the given <code>AIUnit</code>. * * @param aiMain The main AI-object. * @param aiUnit The <code>AIUnit</code> this mission * is created for. */ public PioneeringMission(AIMain aiMain, AIUnit aiUnit) { super(aiMain, aiUnit); } /** * Loads a mission from the given element. * * @param aiMain The main AI-object. * @param element An <code>Element</code> containing an * XML-representation of this object. */ public PioneeringMission(AIMain aiMain, Element element) { super(aiMain); readFromXMLElement(element); } /** * Creates a new <code>PioneeringMission</code> and reads the given element. * * @param aiMain The main AI-object. * @param in The input stream containing the XML. * @throws XMLStreamException if a problem was encountered * during parsing. * @see AIObject#readFromXML */ public PioneeringMission(AIMain aiMain, XMLStreamReader in) throws XMLStreamException { super(aiMain); readFromXML(in); } /** * Disposes this <code>Mission</code>. */ public void dispose() { if (tileImprovement != null) { tileImprovement.setPioneer(null); tileImprovement = null; } super.dispose(); } /** * Sets the <code>TileImprovement</code> which should * be the next target. * * @param tileImprovement The <code>TileImprovement</code>. */ public void setTileImprovement(TileImprovement tileImprovement) { this.tileImprovement = tileImprovement; } private void updateTileImprovement() { if (tileImprovement != null) { return; } final AIPlayer aiPlayer = (AIPlayer) getAIMain().getAIObject(getUnit().getOwner().getID()); final Unit carrier = (getUnit().getLocation() instanceof Unit) ? (Unit) getUnit().getLocation() : null; final Tile startTile; if (getUnit().getTile() == null) { if (getUnit().getLocation() instanceof Unit) { startTile = (Tile) ((Unit) getUnit().getLocation()).getEntryLocation(); } else { startTile = (Tile) getUnit().getOwner().getEntryLocation(); } } else { startTile = getUnit().getTile(); } TileImprovement bestChoice = null; int bestValue = 0; Iterator<TileImprovement> tiIterator = aiPlayer.getTileImprovementIterator(); while (tiIterator.hasNext()) { TileImprovement ti = tiIterator.next(); if (ti.getPioneer() == null) { PathNode path = null; int value; if (startTile != ti.getTarget()) { path = getGame().getMap().findPath(getUnit(), startTile, ti.getTarget(), carrier); if (path != null) { value = ti.getValue() + 10000 - (path.getTotalTurns()*5); /* * Avoid picking a TileImprovement with a path being blocked * by an enemy unit (apply a penalty to the value): */ PathNode pn = path; while (pn != null) { if (pn.getTile().getFirstUnit() != null && pn.getTile().getFirstUnit().getOwner() != getUnit().getOwner()) { value -= 1000; } pn = pn.next; } } else { value = ti.getValue(); } } else { value = ti.getValue() + 10000; } if (value > bestValue) { bestChoice = ti; bestValue = value; } } } if (bestChoice != null) { tileImprovement = bestChoice; bestChoice.setPioneer(getAIUnit()); } } private PathNode findColonyWithTools() { GoalDecider destinationDecider = new GoalDecider() { private PathNode best = null; public PathNode getGoal() { return best; } public boolean hasSubGoals() { return false; } public boolean check(Unit u, PathNode pathNode) { Tile t = pathNode.getTile(); boolean target = false; if (t.getColony() != null && t.getColony().getOwner() == u.getOwner() && t.getColony().getGoodsContainer().getGoodsCount(Goods.TOOLS) >= 20) { AIColony ac = (AIColony) getAIMain().getAIObject(t.getColony()); if (ac.getAvailableTools() >= 20) { target = true; } } if (target) { best = pathNode; } return target; } }; return getGame().getMap().search(getUnit(), destinationDecider, Integer.MAX_VALUE); } /** * Performs this mission. * @param connection The <code>Connection</code> to the server. */ public void doMission(Connection connection) { if (!isValid()) { return; } if (getUnit().getTile() != null) { if (getUnit().getNumberOfTools() == 0) { // Get tools from a Colony. if (getUnit().getColony() == null) { PathNode bestPath = findColonyWithTools(); if (bestPath != null) { int direction = moveTowards(connection, bestPath); if (direction >= 0) { final int mt = getUnit().getMoveType(direction); if (mt != Unit.ILLEGAL_MOVE && mt != Unit.ATTACK) { move(connection, direction); } } } else { skipMission = true; } } if (getUnit().getColony() != null) { AIColony ac = (AIColony) getAIMain().getAIObject(getUnit().getColony()); final int tools = ac.getAvailableTools(); if (tools >= 20) { Element equipUnitElement = Message.createNewRootElement("equipunit"); equipUnitElement.setAttribute("unit", getUnit().getID()); equipUnitElement.setAttribute("type", Integer.toString(Goods.TOOLS)); equipUnitElement.setAttribute("amount", Integer.toString(Math.min(tools - tools % 20, 100))); try { connection.sendAndWait(equipUnitElement); } catch (Exception e) { logger.warning("Could not send equip message."); } } else { skipMission = true; } } return; } } if (tileImprovement == null) { updateTileImprovement(); } if (tileImprovement != null) { if (getUnit().getTile() != null) { if (getUnit().getTile() != tileImprovement.getTarget()) { PathNode pathToTarget = getUnit().findPath(tileImprovement.getTarget()); if (pathToTarget != null) { int direction = moveTowards(connection, pathToTarget); if (direction >= 0 && (getUnit().getMoveType(direction) == Unit.MOVE || getUnit().getMoveType(direction) == Unit.EXPLORE_LOST_CITY_RUMOUR)) { move(connection, direction); } } } if (getUnit().getTile() == tileImprovement.getTarget() + && getUnit().getState() != tileImprovement.getType() && getUnit().checkSetState(tileImprovement.getType())) { Element changeStateElement = Message.createNewRootElement("changeState"); changeStateElement.setAttribute("unit", getUnit().getID()); changeStateElement.setAttribute("state", Integer.toString(tileImprovement.getType())); try { connection.sendAndWait(changeStateElement); } catch (IOException e) { logger.warning("Could not send message!"); } } } } } /** * Returns the destination for this <code>Transportable</code>. * This can either be the target {@link Tile} of the transport * or the target for the entire <code>Transportable</code>'s * mission. The target for the tansport is determined by * {@link TransportMission} in the latter case. * * @return The destination for this <code>Transportable</code>. */ public Tile getTransportDestination() { updateTileImprovement(); if (tileImprovement == null) { return null; } if (getUnit().getLocation() instanceof Unit) { return tileImprovement.getTarget(); } else if (getUnit().getTile() == tileImprovement.getTarget()) { return null; } else if (getUnit().getTile() == null || getUnit().findPath(tileImprovement.getTarget()) == null) { return tileImprovement.getTarget(); } else { return null; } } /** * Returns the priority of getting the unit to the * transport destination. * * @return The priority. */ public int getTransportPriority() { if (getTransportDestination() != null) { return NORMAL_TRANSPORT_PRIORITY; } else { return 0; } } /** * Checks if this mission is still valid to perform. * * @return <code>true</code> if this mission is still valid to perform * and <code>false</code> otherwise. */ public boolean isValid() { updateTileImprovement(); return !skipMission && (tileImprovement != null) && (getUnit().isPioneer() || getUnit().getType() == Unit.HARDY_PIONEER); } /** * Checks if this mission is valid for the given unit. * * @param aiUnit The unit. * @return <code>true</code> if this mission is still valid to perform * and <code>false</code> otherwise. */ public static boolean isValid(AIUnit aiUnit) { AIPlayer aiPlayer = (AIPlayer) aiUnit.getAIMain().getAIObject(aiUnit.getUnit().getOwner().getID()); Iterator<TileImprovement> tiIterator = aiPlayer.getTileImprovementIterator(); while (tiIterator.hasNext()) { TileImprovement ti = tiIterator.next(); if (ti.getPioneer() == null) { return true; } } return false; } /** * Writes all of the <code>AIObject</code>s and other AI-related * information to an XML-stream. * * @param out The target stream. * @throws XMLStreamException if there are any problems writing * to the stream. */ protected void toXMLImpl(XMLStreamWriter out) throws XMLStreamException { out.writeStartElement(getXMLElementTagName()); out.writeAttribute("unit", getUnit().getID()); if (tileImprovement != null) { out.writeAttribute("tileImprovement", tileImprovement.getID()); } out.writeEndElement(); } /** * Reads all the <code>AIObject</code>s and other AI-related information * from XML data. * @param in The input stream with the XML. */ protected void readFromXMLImpl(XMLStreamReader in) throws XMLStreamException { setAIUnit((AIUnit) getAIMain().getAIObject(in.getAttributeValue(null, "unit"))); final String tileImprovementStr = in.getAttributeValue(null, "tileImprovement"); if (tileImprovementStr != null) { tileImprovement = (TileImprovement) getAIMain().getAIObject(tileImprovementStr); if (tileImprovement == null) { tileImprovement = new TileImprovement(getAIMain(), tileImprovementStr); } } else { tileImprovement = null; } in.nextTag(); } /** * Returns the tag name of the root element representing this object. * @return The <code>String</code> "wishRealizationMission". */ public static String getXMLElementTagName() { return "tileImprovementMission"; } /** * Gets debugging information about this mission. * This string is a short representation of this * object's state. * * @return The <code>String</code>: * <ul> * <li>"(x, y) P" (for plowing)</li> * <li>"(x, y) R" (for building road)</li> * <li>"(x, y) Getting tools: (x, y)"</li> * </ul> */ public String getDebuggingInfo() { if (tileImprovement != null) { final String action = (tileImprovement.getType() == Unit.PLOW) ? "P" : "R"; return tileImprovement.getTarget().getPosition().toString() + " " + action; } else { PathNode bestPath = findColonyWithTools(); if (bestPath != null) { return "Getting tools: " + bestPath.getLastNode().getTile().getPosition().toString(); } else { return "No target"; } } } }
true
true
public void doMission(Connection connection) { if (!isValid()) { return; } if (getUnit().getTile() != null) { if (getUnit().getNumberOfTools() == 0) { // Get tools from a Colony. if (getUnit().getColony() == null) { PathNode bestPath = findColonyWithTools(); if (bestPath != null) { int direction = moveTowards(connection, bestPath); if (direction >= 0) { final int mt = getUnit().getMoveType(direction); if (mt != Unit.ILLEGAL_MOVE && mt != Unit.ATTACK) { move(connection, direction); } } } else { skipMission = true; } } if (getUnit().getColony() != null) { AIColony ac = (AIColony) getAIMain().getAIObject(getUnit().getColony()); final int tools = ac.getAvailableTools(); if (tools >= 20) { Element equipUnitElement = Message.createNewRootElement("equipunit"); equipUnitElement.setAttribute("unit", getUnit().getID()); equipUnitElement.setAttribute("type", Integer.toString(Goods.TOOLS)); equipUnitElement.setAttribute("amount", Integer.toString(Math.min(tools - tools % 20, 100))); try { connection.sendAndWait(equipUnitElement); } catch (Exception e) { logger.warning("Could not send equip message."); } } else { skipMission = true; } } return; } } if (tileImprovement == null) { updateTileImprovement(); } if (tileImprovement != null) { if (getUnit().getTile() != null) { if (getUnit().getTile() != tileImprovement.getTarget()) { PathNode pathToTarget = getUnit().findPath(tileImprovement.getTarget()); if (pathToTarget != null) { int direction = moveTowards(connection, pathToTarget); if (direction >= 0 && (getUnit().getMoveType(direction) == Unit.MOVE || getUnit().getMoveType(direction) == Unit.EXPLORE_LOST_CITY_RUMOUR)) { move(connection, direction); } } } if (getUnit().getTile() == tileImprovement.getTarget() && getUnit().checkSetState(tileImprovement.getType())) { Element changeStateElement = Message.createNewRootElement("changeState"); changeStateElement.setAttribute("unit", getUnit().getID()); changeStateElement.setAttribute("state", Integer.toString(tileImprovement.getType())); try { connection.sendAndWait(changeStateElement); } catch (IOException e) { logger.warning("Could not send message!"); } } } } }
public void doMission(Connection connection) { if (!isValid()) { return; } if (getUnit().getTile() != null) { if (getUnit().getNumberOfTools() == 0) { // Get tools from a Colony. if (getUnit().getColony() == null) { PathNode bestPath = findColonyWithTools(); if (bestPath != null) { int direction = moveTowards(connection, bestPath); if (direction >= 0) { final int mt = getUnit().getMoveType(direction); if (mt != Unit.ILLEGAL_MOVE && mt != Unit.ATTACK) { move(connection, direction); } } } else { skipMission = true; } } if (getUnit().getColony() != null) { AIColony ac = (AIColony) getAIMain().getAIObject(getUnit().getColony()); final int tools = ac.getAvailableTools(); if (tools >= 20) { Element equipUnitElement = Message.createNewRootElement("equipunit"); equipUnitElement.setAttribute("unit", getUnit().getID()); equipUnitElement.setAttribute("type", Integer.toString(Goods.TOOLS)); equipUnitElement.setAttribute("amount", Integer.toString(Math.min(tools - tools % 20, 100))); try { connection.sendAndWait(equipUnitElement); } catch (Exception e) { logger.warning("Could not send equip message."); } } else { skipMission = true; } } return; } } if (tileImprovement == null) { updateTileImprovement(); } if (tileImprovement != null) { if (getUnit().getTile() != null) { if (getUnit().getTile() != tileImprovement.getTarget()) { PathNode pathToTarget = getUnit().findPath(tileImprovement.getTarget()); if (pathToTarget != null) { int direction = moveTowards(connection, pathToTarget); if (direction >= 0 && (getUnit().getMoveType(direction) == Unit.MOVE || getUnit().getMoveType(direction) == Unit.EXPLORE_LOST_CITY_RUMOUR)) { move(connection, direction); } } } if (getUnit().getTile() == tileImprovement.getTarget() && getUnit().getState() != tileImprovement.getType() && getUnit().checkSetState(tileImprovement.getType())) { Element changeStateElement = Message.createNewRootElement("changeState"); changeStateElement.setAttribute("unit", getUnit().getID()); changeStateElement.setAttribute("state", Integer.toString(tileImprovement.getType())); try { connection.sendAndWait(changeStateElement); } catch (IOException e) { logger.warning("Could not send message!"); } } } } }
diff --git a/src/hello/FizzBuzz.java b/src/hello/FizzBuzz.java index 748873c..0aabea7 100644 --- a/src/hello/FizzBuzz.java +++ b/src/hello/FizzBuzz.java @@ -1,9 +1,10 @@ package hello; public class FizzBuzz { public String FizzBuzz(int i) { - return "Fizz"; + if (i == 3) return "Fizz"; + return null; } }
true
true
public String FizzBuzz(int i) { return "Fizz"; }
public String FizzBuzz(int i) { if (i == 3) return "Fizz"; return null; }
diff --git a/java/xml/src/main/java/org/pixielib/xml/QParser.java b/java/xml/src/main/java/org/pixielib/xml/QParser.java index 452e3ea..abc57b6 100644 --- a/java/xml/src/main/java/org/pixielib/xml/QParser.java +++ b/java/xml/src/main/java/org/pixielib/xml/QParser.java @@ -1,269 +1,271 @@ package org.pixielib.xml; import java.io.IOException; import java.io.PushbackReader; import java.io.Reader; /** * Simple abstract "Quick & Dirty" SAX-like XML parser * <p/> * This class is useful for keeping track * of the current position in the input stream when * processing a node in the xml tree. */ public abstract class QParser { private static final int BUFFER_SIZE = 8192; // pushback buffer size private static final int UNDEFTAG = 0x0000; // undefined tag private static final int BEGINTAG = 0x0001; // begin tag private static final int ENDTAG = 0x0002; // end tag private static final int EMPTYTAG = 0x0004; // empty tag private static final int PROCTAG = 0x0008; // processing instruction tag private static final int DECLTAG = 0x0010; // declaration tag private static final int EMPTYTAGS = (EMPTYTAG | PROCTAG | DECLTAG); private PushbackReader reader; // pushback reader for parsing private long position; // position in input stream private int type; // tag type public QParser() { } public long getPosition() { return position; } protected void setPosition(long position) { this.position = position; } /** * Parse an input stream * * @param reader, the reader to parse * @throws IOException, if an i/o exception occurs */ public void parse(Reader reader) throws IOException { this.reader = new PushbackReader(reader, BUFFER_SIZE); parse(); } /** * Unget a character from the reader * * @param c the character to unget * @throws IOException, if an i/o exception occurs */ private void unget(int c) throws IOException { reader.unread(c); position--; } protected void parse() throws IOException { - int c; + int c, save; char[] buffer; String tag, name; while ((c = read()) != -1) { buffer = lookahead(3); unget(c); if (c != '<') { // not a tag value(getValue()); continue; } switch (buffer[0]) { case '/': // end tag + save = type; endTag(); - endElement(); + if (save != EMPTYTAG) + endElement(); break; case '!': // xml comment if (buffer[1] == '-' && buffer[2] == '-') { getComment(); type = UNDEFTAG; } // fallthrough default: tag = startTag(); type = tagType(tag); name = tagName(tag); startElement(name, tag); if (type == EMPTYTAG) endElement(); break; } } } private int read() throws IOException { int c = reader.read(); position++; return c; } /** * Look ahead n characters * * @param n, the number of characters to lookahead * @return the char array containing up to n characters * @throws IOException, if an i/o error occurs */ public char[] lookahead(int n) throws IOException { char[] buffer = new char[n]; // doesn't alter position int i, c; for (i = 0; i < n && (c = reader.read()) != -1; i++) { buffer[i] = (char) c; } // unread the characters read reader.unread(buffer, 0, i); return buffer; } public abstract void value(String value); public abstract void startElement(String name, String tag); public abstract void endElement(); public String startTag() throws IOException { StringBuilder tag = new StringBuilder(); int c; while ((c = read()) != -1) { if (c == '>') { tag.append((char) c); break; } tag.append((char) c); } return tag.toString(); } String endTag() throws IOException { if ((type & EMPTYTAGS) != 0) { type = UNDEFTAG; return ""; } StringBuilder tag = new StringBuilder(); int c; while ((c = read()) != -1) { if (c == '>') { tag.append((char) c); break; } tag.append((char) c); } type = UNDEFTAG; return tag.toString(); } /** * Determine the type of a tag * * @param tag the tag to determine * @return the tag type */ private int tagType(String tag) { char[] atag = tag.toCharArray(); for (int i = 0; i < atag.length; i++) { switch (atag[i]) { case '<': if (i < atag.length - 1 && atag[i + 1] == '!') return DECLTAG; if (i < atag.length - 1 && atag[i + 1] == '?') return PROCTAG; if (i < atag.length - 1 && atag[i + 1] == '/') return ENDTAG; break; case '>': if (i > 0 && atag[i - 1] == '/') return EMPTYTAG; return BEGINTAG; default: break; } } return UNDEFTAG; } private String tagName(String tag) { StringBuilder name = new StringBuilder(); char[] atag = tag.toCharArray(); for (char c : atag) { switch (c) { case '\t': case '\n': case '\r': case ' ': case '>': case '/': return name.toString(); case '<': case '!': case '?': continue; default: name.append(c); } } return name.toString(); } private String getComment() throws IOException { StringBuilder comment = new StringBuilder(); int c; char[] buffer; while ((c = read()) != -1) { buffer = lookahead(2); if (c == '-' && buffer[0] == '-' && buffer[1] == '>') { comment.append((char) c); // --> comment.append((char) read()); comment.append((char) read()); break; } comment.append((char) c); } return comment.toString(); } private String getValue() throws IOException { StringBuilder value = new StringBuilder(); int c; while ((c = read()) != -1) { switch (c) { case '<': // tag unget(c); return value.toString(); default: value.append((char) c); } } return value.toString(); } }
false
true
protected void parse() throws IOException { int c; char[] buffer; String tag, name; while ((c = read()) != -1) { buffer = lookahead(3); unget(c); if (c != '<') { // not a tag value(getValue()); continue; } switch (buffer[0]) { case '/': // end tag endTag(); endElement(); break; case '!': // xml comment if (buffer[1] == '-' && buffer[2] == '-') { getComment(); type = UNDEFTAG; } // fallthrough default: tag = startTag(); type = tagType(tag); name = tagName(tag); startElement(name, tag); if (type == EMPTYTAG) endElement(); break; } } }
protected void parse() throws IOException { int c, save; char[] buffer; String tag, name; while ((c = read()) != -1) { buffer = lookahead(3); unget(c); if (c != '<') { // not a tag value(getValue()); continue; } switch (buffer[0]) { case '/': // end tag save = type; endTag(); if (save != EMPTYTAG) endElement(); break; case '!': // xml comment if (buffer[1] == '-' && buffer[2] == '-') { getComment(); type = UNDEFTAG; } // fallthrough default: tag = startTag(); type = tagType(tag); name = tagName(tag); startElement(name, tag); if (type == EMPTYTAG) endElement(); break; } } }
diff --git a/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/SiteHandler.java b/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/SiteHandler.java index 45ca6dfb..7ae3b7af 100644 --- a/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/SiteHandler.java +++ b/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/SiteHandler.java @@ -1,679 +1,680 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.portal.charon.handlers; import java.io.IOException; 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.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.portal.api.Portal; import org.sakaiproject.portal.api.PortalHandlerException; import org.sakaiproject.portal.api.PortalRenderContext; import org.sakaiproject.portal.api.StoredState; import org.sakaiproject.portal.util.PortalSiteHelper; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SitePage; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.alias.cover.AliasService; import org.sakaiproject.entity.cover.EntityManager; import org.sakaiproject.tool.api.Session; import org.sakaiproject.tool.api.ToolException; import org.sakaiproject.user.api.Preferences; import org.sakaiproject.user.cover.PreferencesService; import org.sakaiproject.util.Web; /** * * @author ieb * @since Sakai 2.4 * @version $Rev$ * */ public class SiteHandler extends WorksiteHandler { private static final String INCLUDE_SITE_NAV = "include-site-nav"; private static final String INCLUDE_LOGO = "include-logo"; private static final String INCLUDE_TABS = "include-tabs"; private static final Log log = LogFactory.getLog(SiteHandler.class); private PortalSiteHelper siteHelper = new PortalSiteHelper(); private int configuredTabsToDisplay = 5; private boolean useDHTMLMore = false; public SiteHandler() { urlFragment = "site"; configuredTabsToDisplay = ServerConfigurationService.getInt(Portal.CONFIG_DEFAULT_TABS, 5); useDHTMLMore = Boolean.valueOf(ServerConfigurationService.getBoolean("portal.use.dhtml.more", false)); } @Override public int doGet(String[] parts, HttpServletRequest req, HttpServletResponse res, Session session) throws PortalHandlerException { if ((parts.length >= 2) && (parts[1].equals("site"))) { // This is part of the main portal so we simply remove the attribute session.setAttribute("sakai-controlling-portal",null); try { // recognize an optional page/pageid String pageId = null; if ((parts.length == 5) && (parts[3].equals("page"))) { pageId = parts[4]; } // site might be specified String siteId = null; if (parts.length >= 3) { siteId = parts[2]; } doSite(req, res, session, siteId, pageId, req.getContextPath() + req.getServletPath()); return END; } catch (Exception ex) { throw new PortalHandlerException(ex); } } else { return NEXT; } } public void doSite(HttpServletRequest req, HttpServletResponse res, Session session, String siteId, String pageId, String toolContextPath) throws ToolException, IOException { // default site if not set if (siteId == null) { if (session.getUserId() == null) { siteId = ServerConfigurationService.getGatewaySiteId(); } else { siteId = SiteService.getUserSiteId(session.getUserId()); } } // if no page id, see if there was a last page visited for this site if (pageId == null) { pageId = (String) session.getAttribute(Portal.ATTR_SITE_PAGE + siteId); } // find the site, for visiting Site site = null; try { site = siteHelper.getSiteVisit(siteId); } catch (IdUnusedException e) { // continue on to alias check } catch (PermissionException e) { // if not logged in, give them a chance if (session.getUserId() == null) { StoredState ss = portalService.newStoredState("directtool", "tool"); ss.setRequest(req); ss.setToolContextPath(toolContextPath); portalService.setStoredState(ss); portal.doLogin(req, res, session, req.getPathInfo(), false); return; } // otherwise continue on to alias check } // Now check for site alias if ( site == null ) { try { // First check for site alias if ( siteId!= null && !siteId.equals("") && !SiteService.siteExists(siteId) ) { String refString = AliasService.getTarget(siteId); siteId = EntityManager.newReference(refString).getContainer(); } site = siteHelper.getSiteVisit(siteId); } catch (IdUnusedException e) { portal.doError(req, res, session, Portal.ERROR_SITE); return; } catch (PermissionException e) { // if not logged in, give them a chance if (session.getUserId() == null) { StoredState ss = portalService.newStoredState("directtool", "tool"); ss.setRequest(req); ss.setToolContextPath(toolContextPath); portalService.setStoredState(ss); portal.doLogin(req, res, session, req.getPathInfo(), false); } else { portal.doError(req, res, session, Portal.ERROR_SITE); } return; } } // Try to lookup alias if pageId not found if (pageId != null && !pageId.equals("") && site.getPage(pageId) == null) { try { String refString = AliasService.getTarget(pageId); pageId = EntityManager.newReference(refString).getId(); } catch (IdUnusedException e) { log.warn("Alias does not resolve "+e.getMessage()); } } // Lookup the page in the site - enforcing access control // business rules SitePage page = siteHelper.lookupSitePage(pageId, site); if (page == null) { portal.doError(req, res, session, Portal.ERROR_SITE); return; } // store the last page visited session.setAttribute(Portal.ATTR_SITE_PAGE + siteId, page.getId()); // form a context sensitive title String title = ServerConfigurationService.getString("ui.service") + " : " + site.getTitle() + " : " + page.getTitle(); // start the response String siteType = portal.calcSiteType(siteId); PortalRenderContext rcontext = portal.startPageContext(siteType, title, site .getSkin(), req); // the 'full' top area includeSiteNav(rcontext, req, session, siteId); includeWorksite(rcontext, res, req, session, site, page, toolContextPath, "site"); // Include sub-sites if appropriate // TODO: Thing through whether we want reset tools or not portal.includeSubSites(rcontext, req, session, siteId, req.getContextPath() + req.getServletPath(), "site", /* resetTools */ false ); portal.includeBottom(rcontext); // end the response portal.sendResponse(rcontext, res, "site", null); StoredState ss = portalService.getStoredState(); if (ss != null && toolContextPath.equals(ss.getToolContextPath())) { // This request is the destination of the request portalService.setStoredState(null); } } protected void includeSiteNav(PortalRenderContext rcontext, HttpServletRequest req, Session session, String siteId) { if (rcontext.uses(INCLUDE_SITE_NAV)) { boolean loggedIn = session.getUserId() != null; boolean topLogin = ServerConfigurationService.getBoolean("top.login", true); String siteNavUrl = null; int height = 0; String siteNavClass = null; if (loggedIn) { siteNavUrl = Web.returnUrl(req, "/site_tabs/" + Web.escapeUrl(siteId)); height = 104; siteNavClass = "sitenav-max"; } else { siteNavUrl = Web.returnUrl(req, "/nav_login/" + Web.escapeUrl(siteId)); height = 80; siteNavClass = "sitenav-log"; } String accessibilityURL = ServerConfigurationService .getString("accessibility.url"); rcontext.put("siteNavHasAccessibilityURL", Boolean .valueOf((accessibilityURL != null && accessibilityURL != ""))); rcontext.put("siteNavAccessibilityURL", accessibilityURL); // rcontext.put("siteNavSitAccessability", // Web.escapeHtml(rb.getString("sit_accessibility"))); // rcontext.put("siteNavSitJumpContent", // Web.escapeHtml(rb.getString("sit_jumpcontent"))); // rcontext.put("siteNavSitJumpTools", // Web.escapeHtml(rb.getString("sit_jumptools"))); // rcontext.put("siteNavSitJumpWorksite", // Web.escapeHtml(rb.getString("sit_jumpworksite"))); rcontext.put("siteNavLoggedIn", Boolean.valueOf(loggedIn)); try { if (loggedIn) { includeLogo(rcontext, req, session, siteId); includeTabs(rcontext, req, session, siteId, "site", false); } else { includeLogo(rcontext, req, session, siteId); if (siteHelper.doGatewaySiteList()) includeTabs(rcontext, req, session, siteId, "site", false); } } catch (Exception any) { } } } public void includeLogo(PortalRenderContext rcontext, HttpServletRequest req, Session session, String siteId) throws IOException { if (rcontext.uses(INCLUDE_LOGO)) { String skin = getSiteSkin(siteId); if (skin == null) { skin = ServerConfigurationService.getString("skin.default"); } String skinRepo = ServerConfigurationService.getString("skin.repo"); rcontext.put("logoSkin", skin); rcontext.put("logoSkinRepo", skinRepo); String siteType = portal.calcSiteType(siteId); String cssClass = (siteType != null) ? siteType : "undeterminedSiteType"; rcontext.put("logoSiteType", siteType); rcontext.put("logoSiteClass", cssClass); portal.includeLogin(rcontext, req, session); } } private String getSiteSkin(String siteId) { // First, try to get the skin the default way String skin = SiteService.getSiteSkin(siteId); // If this fails, try to get the real site id if the site is a user site if (skin == null && SiteService.isUserSite(siteId)) { try { String userId = SiteService.getSiteUserId(siteId); String alternateSiteId = SiteService.getUserSiteId(userId); skin = SiteService.getSiteSkin(alternateSiteId); } catch (Exception e) { // Ignore } } return skin; } public void includeTabs(PortalRenderContext rcontext, HttpServletRequest req, Session session, String siteId, String prefix, boolean addLogout) throws IOException { if (rcontext.uses(INCLUDE_TABS)) { // for skinning String siteType = portal.calcSiteType(siteId); String origPrefix = prefix; // If we have turned on auto-state reset on navigation, we generate // the "site-reset" "worksite-reset" and "gallery-reset" urls if ("true".equals(ServerConfigurationService .getString(Portal.CONFIG_AUTO_RESET))) { prefix = prefix + "-reset"; } boolean loggedIn = session.getUserId() != null; // Get the user's My WorkSpace and its ID Site myWorkspaceSite = siteHelper.getMyWorkspace(session); String myWorkspaceSiteId = null; if (myWorkspaceSite != null) { myWorkspaceSiteId = siteHelper.getSiteEffectiveId(myWorkspaceSite); } int tabsToDisplay = configuredTabsToDisplay; if (!loggedIn) { tabsToDisplay = ServerConfigurationService.getInt( "gatewaySiteListDisplayCount", tabsToDisplay); } else { Preferences prefs = PreferencesService .getPreferences(session.getUserId()); ResourceProperties props = prefs.getProperties("sakai:portal:sitenav"); try { tabsToDisplay = (int) props.getLongProperty("tabs"); } catch (Exception any) { } } // Get the list of sites in the right order, // My WorkSpace will be the first in the list List<Site> mySites = siteHelper.getAllSites(req, session, true); // if public workgroup/gateway site is not included, add to list boolean siteFound = false; for ( int i=0; i< mySites.size(); i++ ) { if ( ((Site)mySites.get(i)).getId().equals(siteId) ) { siteFound = true; } } try { if (!siteFound) { mySites.add( SiteService.getSite(siteId) ); } } catch ( IdUnusedException e) { } // ignore // Note that if there are exactly one more site // than tabs allowed - simply put the site on // instead of a dropdown with one site List<Site> moreSites = new ArrayList<Site>(); if (mySites.size() > (tabsToDisplay + 1)) { // Check to see if the selected site is in the first // "tabsToDisplay" tabs boolean found = false; for (int i = 0; i < tabsToDisplay && i < mySites.size(); i++) { Site site = mySites.get(i); String effectiveId = siteHelper.getSiteEffectiveId(site); if (site.getId().equals(siteId) || effectiveId.equals(siteId)) found = true; } // Save space for the current site if (!found) tabsToDisplay = tabsToDisplay - 1; if (tabsToDisplay < 2) tabsToDisplay = 2; // Create the list of "additional sites"- but do not // include the currently selected set in the list Site currentSelectedSite = null; int remove = mySites.size() - tabsToDisplay; for (int i = 0; i < remove; i++) { // We add the site the the drop-down // unless it it the current site in which case // we retain it for later Site site = mySites.get(tabsToDisplay); mySites.remove(tabsToDisplay); String effectiveId = siteHelper.getSiteEffectiveId(site); if (site.getId().equals(siteId) || effectiveId.equals(siteId)) { currentSelectedSite = site; } else { moreSites.add(site); } } // check to see if we need to re-add the current site if ( currentSelectedSite != null ) { mySites.add(currentSelectedSite); } } if (useDHTMLMore) { List<Site> allSites = new ArrayList<Site>(); + allSites.addAll(mySites); allSites.addAll(moreSites); // get Sections Map<String, List> termsToSites = new HashMap<String, List>(); Map<String, List> tabsMoreTerms = new HashMap<String, List>(); for (int i = 0; i < allSites.size(); i++) { Site site = allSites.get(i); ResourceProperties siteProperties = site.getProperties(); String type = site.getType(); String term = null; if ("course".equals(type)) { term = siteProperties.getProperty("term"); } else if ("project".equals(type)) { term = "PROJECTS"; } else if ("portfolio".equals(type)) { term = "PORTFOLIOS"; } else if ("admin".equals(type)) { term = "ADMINISTRATION"; } else { term = "OTHER"; } List<Site> currentList = new ArrayList(); if (termsToSites.containsKey(term)) { currentList = termsToSites.get(term); termsToSites.remove(term); } currentList.add(site); termsToSites.put(term, currentList); } class TitleSorter implements Comparator<Map> { public int compare(Map first, Map second) { if (first == null && second == null) return 0; String firstTitle = (String) first.get("siteTitle"); String secondTitle = (String) second.get("siteTitle"); if (firstTitle != null) return firstTitle.compareToIgnoreCase(secondTitle); return 0; } } Comparator<Map> titleSorter = new TitleSorter(); // now loop through each section and convert the Lists to maps for (String key : termsToSites.keySet()) { List<Site> currentList = termsToSites.get(key); List<Map> temp = portal.convertSitesToMaps(req, currentList, prefix, siteId, myWorkspaceSiteId, /* includeSummary */false, /* expandSite */false, /* resetTools */"true".equals(ServerConfigurationService .getString(Portal.CONFIG_AUTO_RESET)), /* doPages */true, /* toolContextPath */null, loggedIn); Collections.sort(temp, titleSorter); tabsMoreTerms.put(key, temp); } String[] termOrder = ServerConfigurationService .getStrings("portal.term.order"); List<String> tabsMoreSortedTermList = new ArrayList<String>(); // Order term column headers according to order specified in // portal.term.order // Filter out terms for which user is not a member of any sites if (termOrder != null) { for (int i = 0; i < termOrder.length; i++) { if (tabsMoreTerms.containsKey(termOrder[i])) { tabsMoreSortedTermList.add(termOrder[i]); } } } Iterator i = tabsMoreTerms.keySet().iterator(); while (i.hasNext()) { String term = (String) i.next(); if (!tabsMoreSortedTermList.contains(term)) { tabsMoreSortedTermList.add(term); } } rcontext.put("tabsMoreTerms", tabsMoreTerms); rcontext.put("tabsMoreSortedTermList", tabsMoreSortedTermList); } rcontext.put("useDHTMLMore", useDHTMLMore); String cssClass = (siteType != null) ? "siteNavWrap " + siteType : "siteNavWrap"; rcontext.put("tabsCssClass", cssClass); List<Map> l = portal.convertSitesToMaps(req, mySites, prefix, siteId, myWorkspaceSiteId, /* includeSummary */false, /* expandSite */false, /* resetTools */"true".equals(ServerConfigurationService .getString(Portal.CONFIG_AUTO_RESET)), /* doPages */true, /* toolContextPath */null, loggedIn); rcontext.put("tabsSites", l); rcontext.put("tabsMoreSitesShow", Boolean.valueOf(moreSites.size() > 0)); // more dropdown if (moreSites.size() > 0) { List<Map> m = portal.convertSitesToMaps(req, moreSites, prefix, siteId, myWorkspaceSiteId, /* includeSummary */false, /* expandSite */false, /* resetTools */"true".equals(ServerConfigurationService .getString(Portal.CONFIG_AUTO_RESET)), /* doPages */true, /* toolContextPath */null, loggedIn); rcontext.put("tabsMoreSites", m); } rcontext.put("tabsAddLogout", Boolean.valueOf(addLogout)); if (addLogout) { String logoutUrl = Web.serverUrl(req) + ServerConfigurationService.getString("portalPath") + "/logout_gallery"; rcontext.put("tabsLogoutUrl", logoutUrl); // rcontext.put("tabsSitLog", // Web.escapeHtml(rb.getString("sit_log"))); } } } }
true
true
public void includeTabs(PortalRenderContext rcontext, HttpServletRequest req, Session session, String siteId, String prefix, boolean addLogout) throws IOException { if (rcontext.uses(INCLUDE_TABS)) { // for skinning String siteType = portal.calcSiteType(siteId); String origPrefix = prefix; // If we have turned on auto-state reset on navigation, we generate // the "site-reset" "worksite-reset" and "gallery-reset" urls if ("true".equals(ServerConfigurationService .getString(Portal.CONFIG_AUTO_RESET))) { prefix = prefix + "-reset"; } boolean loggedIn = session.getUserId() != null; // Get the user's My WorkSpace and its ID Site myWorkspaceSite = siteHelper.getMyWorkspace(session); String myWorkspaceSiteId = null; if (myWorkspaceSite != null) { myWorkspaceSiteId = siteHelper.getSiteEffectiveId(myWorkspaceSite); } int tabsToDisplay = configuredTabsToDisplay; if (!loggedIn) { tabsToDisplay = ServerConfigurationService.getInt( "gatewaySiteListDisplayCount", tabsToDisplay); } else { Preferences prefs = PreferencesService .getPreferences(session.getUserId()); ResourceProperties props = prefs.getProperties("sakai:portal:sitenav"); try { tabsToDisplay = (int) props.getLongProperty("tabs"); } catch (Exception any) { } } // Get the list of sites in the right order, // My WorkSpace will be the first in the list List<Site> mySites = siteHelper.getAllSites(req, session, true); // if public workgroup/gateway site is not included, add to list boolean siteFound = false; for ( int i=0; i< mySites.size(); i++ ) { if ( ((Site)mySites.get(i)).getId().equals(siteId) ) { siteFound = true; } } try { if (!siteFound) { mySites.add( SiteService.getSite(siteId) ); } } catch ( IdUnusedException e) { } // ignore // Note that if there are exactly one more site // than tabs allowed - simply put the site on // instead of a dropdown with one site List<Site> moreSites = new ArrayList<Site>(); if (mySites.size() > (tabsToDisplay + 1)) { // Check to see if the selected site is in the first // "tabsToDisplay" tabs boolean found = false; for (int i = 0; i < tabsToDisplay && i < mySites.size(); i++) { Site site = mySites.get(i); String effectiveId = siteHelper.getSiteEffectiveId(site); if (site.getId().equals(siteId) || effectiveId.equals(siteId)) found = true; } // Save space for the current site if (!found) tabsToDisplay = tabsToDisplay - 1; if (tabsToDisplay < 2) tabsToDisplay = 2; // Create the list of "additional sites"- but do not // include the currently selected set in the list Site currentSelectedSite = null; int remove = mySites.size() - tabsToDisplay; for (int i = 0; i < remove; i++) { // We add the site the the drop-down // unless it it the current site in which case // we retain it for later Site site = mySites.get(tabsToDisplay); mySites.remove(tabsToDisplay); String effectiveId = siteHelper.getSiteEffectiveId(site); if (site.getId().equals(siteId) || effectiveId.equals(siteId)) { currentSelectedSite = site; } else { moreSites.add(site); } } // check to see if we need to re-add the current site if ( currentSelectedSite != null ) { mySites.add(currentSelectedSite); } } if (useDHTMLMore) { List<Site> allSites = new ArrayList<Site>(); allSites.addAll(moreSites); // get Sections Map<String, List> termsToSites = new HashMap<String, List>(); Map<String, List> tabsMoreTerms = new HashMap<String, List>(); for (int i = 0; i < allSites.size(); i++) { Site site = allSites.get(i); ResourceProperties siteProperties = site.getProperties(); String type = site.getType(); String term = null; if ("course".equals(type)) { term = siteProperties.getProperty("term"); } else if ("project".equals(type)) { term = "PROJECTS"; } else if ("portfolio".equals(type)) { term = "PORTFOLIOS"; } else if ("admin".equals(type)) { term = "ADMINISTRATION"; } else { term = "OTHER"; } List<Site> currentList = new ArrayList(); if (termsToSites.containsKey(term)) { currentList = termsToSites.get(term); termsToSites.remove(term); } currentList.add(site); termsToSites.put(term, currentList); } class TitleSorter implements Comparator<Map> { public int compare(Map first, Map second) { if (first == null && second == null) return 0; String firstTitle = (String) first.get("siteTitle"); String secondTitle = (String) second.get("siteTitle"); if (firstTitle != null) return firstTitle.compareToIgnoreCase(secondTitle); return 0; } } Comparator<Map> titleSorter = new TitleSorter(); // now loop through each section and convert the Lists to maps for (String key : termsToSites.keySet()) { List<Site> currentList = termsToSites.get(key); List<Map> temp = portal.convertSitesToMaps(req, currentList, prefix, siteId, myWorkspaceSiteId, /* includeSummary */false, /* expandSite */false, /* resetTools */"true".equals(ServerConfigurationService .getString(Portal.CONFIG_AUTO_RESET)), /* doPages */true, /* toolContextPath */null, loggedIn); Collections.sort(temp, titleSorter); tabsMoreTerms.put(key, temp); } String[] termOrder = ServerConfigurationService .getStrings("portal.term.order"); List<String> tabsMoreSortedTermList = new ArrayList<String>(); // Order term column headers according to order specified in // portal.term.order // Filter out terms for which user is not a member of any sites if (termOrder != null) { for (int i = 0; i < termOrder.length; i++) { if (tabsMoreTerms.containsKey(termOrder[i])) { tabsMoreSortedTermList.add(termOrder[i]); } } } Iterator i = tabsMoreTerms.keySet().iterator(); while (i.hasNext()) { String term = (String) i.next(); if (!tabsMoreSortedTermList.contains(term)) { tabsMoreSortedTermList.add(term); } } rcontext.put("tabsMoreTerms", tabsMoreTerms); rcontext.put("tabsMoreSortedTermList", tabsMoreSortedTermList); } rcontext.put("useDHTMLMore", useDHTMLMore); String cssClass = (siteType != null) ? "siteNavWrap " + siteType : "siteNavWrap"; rcontext.put("tabsCssClass", cssClass); List<Map> l = portal.convertSitesToMaps(req, mySites, prefix, siteId, myWorkspaceSiteId, /* includeSummary */false, /* expandSite */false, /* resetTools */"true".equals(ServerConfigurationService .getString(Portal.CONFIG_AUTO_RESET)), /* doPages */true, /* toolContextPath */null, loggedIn); rcontext.put("tabsSites", l); rcontext.put("tabsMoreSitesShow", Boolean.valueOf(moreSites.size() > 0)); // more dropdown if (moreSites.size() > 0) { List<Map> m = portal.convertSitesToMaps(req, moreSites, prefix, siteId, myWorkspaceSiteId, /* includeSummary */false, /* expandSite */false, /* resetTools */"true".equals(ServerConfigurationService .getString(Portal.CONFIG_AUTO_RESET)), /* doPages */true, /* toolContextPath */null, loggedIn); rcontext.put("tabsMoreSites", m); } rcontext.put("tabsAddLogout", Boolean.valueOf(addLogout)); if (addLogout) { String logoutUrl = Web.serverUrl(req) + ServerConfigurationService.getString("portalPath") + "/logout_gallery"; rcontext.put("tabsLogoutUrl", logoutUrl); // rcontext.put("tabsSitLog", // Web.escapeHtml(rb.getString("sit_log"))); } } }
public void includeTabs(PortalRenderContext rcontext, HttpServletRequest req, Session session, String siteId, String prefix, boolean addLogout) throws IOException { if (rcontext.uses(INCLUDE_TABS)) { // for skinning String siteType = portal.calcSiteType(siteId); String origPrefix = prefix; // If we have turned on auto-state reset on navigation, we generate // the "site-reset" "worksite-reset" and "gallery-reset" urls if ("true".equals(ServerConfigurationService .getString(Portal.CONFIG_AUTO_RESET))) { prefix = prefix + "-reset"; } boolean loggedIn = session.getUserId() != null; // Get the user's My WorkSpace and its ID Site myWorkspaceSite = siteHelper.getMyWorkspace(session); String myWorkspaceSiteId = null; if (myWorkspaceSite != null) { myWorkspaceSiteId = siteHelper.getSiteEffectiveId(myWorkspaceSite); } int tabsToDisplay = configuredTabsToDisplay; if (!loggedIn) { tabsToDisplay = ServerConfigurationService.getInt( "gatewaySiteListDisplayCount", tabsToDisplay); } else { Preferences prefs = PreferencesService .getPreferences(session.getUserId()); ResourceProperties props = prefs.getProperties("sakai:portal:sitenav"); try { tabsToDisplay = (int) props.getLongProperty("tabs"); } catch (Exception any) { } } // Get the list of sites in the right order, // My WorkSpace will be the first in the list List<Site> mySites = siteHelper.getAllSites(req, session, true); // if public workgroup/gateway site is not included, add to list boolean siteFound = false; for ( int i=0; i< mySites.size(); i++ ) { if ( ((Site)mySites.get(i)).getId().equals(siteId) ) { siteFound = true; } } try { if (!siteFound) { mySites.add( SiteService.getSite(siteId) ); } } catch ( IdUnusedException e) { } // ignore // Note that if there are exactly one more site // than tabs allowed - simply put the site on // instead of a dropdown with one site List<Site> moreSites = new ArrayList<Site>(); if (mySites.size() > (tabsToDisplay + 1)) { // Check to see if the selected site is in the first // "tabsToDisplay" tabs boolean found = false; for (int i = 0; i < tabsToDisplay && i < mySites.size(); i++) { Site site = mySites.get(i); String effectiveId = siteHelper.getSiteEffectiveId(site); if (site.getId().equals(siteId) || effectiveId.equals(siteId)) found = true; } // Save space for the current site if (!found) tabsToDisplay = tabsToDisplay - 1; if (tabsToDisplay < 2) tabsToDisplay = 2; // Create the list of "additional sites"- but do not // include the currently selected set in the list Site currentSelectedSite = null; int remove = mySites.size() - tabsToDisplay; for (int i = 0; i < remove; i++) { // We add the site the the drop-down // unless it it the current site in which case // we retain it for later Site site = mySites.get(tabsToDisplay); mySites.remove(tabsToDisplay); String effectiveId = siteHelper.getSiteEffectiveId(site); if (site.getId().equals(siteId) || effectiveId.equals(siteId)) { currentSelectedSite = site; } else { moreSites.add(site); } } // check to see if we need to re-add the current site if ( currentSelectedSite != null ) { mySites.add(currentSelectedSite); } } if (useDHTMLMore) { List<Site> allSites = new ArrayList<Site>(); allSites.addAll(mySites); allSites.addAll(moreSites); // get Sections Map<String, List> termsToSites = new HashMap<String, List>(); Map<String, List> tabsMoreTerms = new HashMap<String, List>(); for (int i = 0; i < allSites.size(); i++) { Site site = allSites.get(i); ResourceProperties siteProperties = site.getProperties(); String type = site.getType(); String term = null; if ("course".equals(type)) { term = siteProperties.getProperty("term"); } else if ("project".equals(type)) { term = "PROJECTS"; } else if ("portfolio".equals(type)) { term = "PORTFOLIOS"; } else if ("admin".equals(type)) { term = "ADMINISTRATION"; } else { term = "OTHER"; } List<Site> currentList = new ArrayList(); if (termsToSites.containsKey(term)) { currentList = termsToSites.get(term); termsToSites.remove(term); } currentList.add(site); termsToSites.put(term, currentList); } class TitleSorter implements Comparator<Map> { public int compare(Map first, Map second) { if (first == null && second == null) return 0; String firstTitle = (String) first.get("siteTitle"); String secondTitle = (String) second.get("siteTitle"); if (firstTitle != null) return firstTitle.compareToIgnoreCase(secondTitle); return 0; } } Comparator<Map> titleSorter = new TitleSorter(); // now loop through each section and convert the Lists to maps for (String key : termsToSites.keySet()) { List<Site> currentList = termsToSites.get(key); List<Map> temp = portal.convertSitesToMaps(req, currentList, prefix, siteId, myWorkspaceSiteId, /* includeSummary */false, /* expandSite */false, /* resetTools */"true".equals(ServerConfigurationService .getString(Portal.CONFIG_AUTO_RESET)), /* doPages */true, /* toolContextPath */null, loggedIn); Collections.sort(temp, titleSorter); tabsMoreTerms.put(key, temp); } String[] termOrder = ServerConfigurationService .getStrings("portal.term.order"); List<String> tabsMoreSortedTermList = new ArrayList<String>(); // Order term column headers according to order specified in // portal.term.order // Filter out terms for which user is not a member of any sites if (termOrder != null) { for (int i = 0; i < termOrder.length; i++) { if (tabsMoreTerms.containsKey(termOrder[i])) { tabsMoreSortedTermList.add(termOrder[i]); } } } Iterator i = tabsMoreTerms.keySet().iterator(); while (i.hasNext()) { String term = (String) i.next(); if (!tabsMoreSortedTermList.contains(term)) { tabsMoreSortedTermList.add(term); } } rcontext.put("tabsMoreTerms", tabsMoreTerms); rcontext.put("tabsMoreSortedTermList", tabsMoreSortedTermList); } rcontext.put("useDHTMLMore", useDHTMLMore); String cssClass = (siteType != null) ? "siteNavWrap " + siteType : "siteNavWrap"; rcontext.put("tabsCssClass", cssClass); List<Map> l = portal.convertSitesToMaps(req, mySites, prefix, siteId, myWorkspaceSiteId, /* includeSummary */false, /* expandSite */false, /* resetTools */"true".equals(ServerConfigurationService .getString(Portal.CONFIG_AUTO_RESET)), /* doPages */true, /* toolContextPath */null, loggedIn); rcontext.put("tabsSites", l); rcontext.put("tabsMoreSitesShow", Boolean.valueOf(moreSites.size() > 0)); // more dropdown if (moreSites.size() > 0) { List<Map> m = portal.convertSitesToMaps(req, moreSites, prefix, siteId, myWorkspaceSiteId, /* includeSummary */false, /* expandSite */false, /* resetTools */"true".equals(ServerConfigurationService .getString(Portal.CONFIG_AUTO_RESET)), /* doPages */true, /* toolContextPath */null, loggedIn); rcontext.put("tabsMoreSites", m); } rcontext.put("tabsAddLogout", Boolean.valueOf(addLogout)); if (addLogout) { String logoutUrl = Web.serverUrl(req) + ServerConfigurationService.getString("portalPath") + "/logout_gallery"; rcontext.put("tabsLogoutUrl", logoutUrl); // rcontext.put("tabsSitLog", // Web.escapeHtml(rb.getString("sit_log"))); } } }
diff --git a/src/main/java/de/cismet/verdis/gui/KartenPanel.java b/src/main/java/de/cismet/verdis/gui/KartenPanel.java index d4a894c..e0bc068 100644 --- a/src/main/java/de/cismet/verdis/gui/KartenPanel.java +++ b/src/main/java/de/cismet/verdis/gui/KartenPanel.java @@ -1,1970 +1,1968 @@ /*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ /* * Copyright (C) 2010 thorsten * * 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/>. */ /* * KartenPanel.java * * Created on 24.11.2010, 20:42:05 */ package de.cismet.verdis.gui; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Polygon; import de.cismet.cids.dynamics.CidsBean; import de.cismet.cids.dynamics.CidsBeanStore; import de.cismet.cismap.commons.ServiceLayer; import de.cismet.cismap.commons.features.*; import de.cismet.cismap.commons.gui.MappingComponent; import de.cismet.cismap.commons.gui.piccolo.PFeature; import de.cismet.cismap.commons.gui.piccolo.eventlistener.*; import de.cismet.cismap.commons.gui.piccolo.eventlistener.actions.CustomAction; import de.cismet.cismap.commons.interaction.CismapBroker; import de.cismet.cismap.commons.interaction.memento.MementoInterface; import de.cismet.cismap.commons.retrieval.RetrievalEvent; import de.cismet.cismap.commons.retrieval.RetrievalListener; import de.cismet.cismap.navigatorplugin.BeanUpdatingCidsFeature; import de.cismet.cismap.navigatorplugin.CidsFeature; import de.cismet.cismap.tools.gui.CidsBeanDropJPopupMenuButton; import de.cismet.gui.tools.PureNewFeatureWithThickerLineString; import de.cismet.tools.CurrentStackTrace; import de.cismet.tools.StaticDebuggingTools; import de.cismet.tools.StaticDecimalTools; import de.cismet.tools.gui.JPopupMenuButton; import de.cismet.tools.gui.StaticSwingTools; import de.cismet.tools.gui.historybutton.JHistoryButton; import de.cismet.verdis.AppModeListener; import de.cismet.verdis.CidsAppBackend; import de.cismet.verdis.EditModeListener; import de.cismet.verdis.constants.*; import de.cismet.verdis.search.ServerSearchCreateSearchGeometryListener; import edu.umd.cs.piccolo.PCamera; import edu.umd.cs.piccolox.event.PNotification; import java.awt.Event; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.sql.Date; import java.util.*; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.plaf.basic.BasicToggleButtonUI; /** * DOCUMENT ME! * * @author thorsten * @version $Revision$, $Date$ */ public class KartenPanel extends javax.swing.JPanel implements FeatureCollectionListener, RetrievalListener, Observer, CidsBeanStore, EditModeListener, AppModeListener, PropertyChangeListener { //~ Instance fields -------------------------------------------------------- final private HashSet activeRetrievalServices = new HashSet(); private CidsBean kassenzeichenBean = null; private final transient org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(KartenPanel.class); // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JToggleButton cmdALB; private javax.swing.JButton cmdAdd; private javax.swing.JToggleButton cmdAddHandle; private javax.swing.JToggleButton cmdAttachPolyToAlphadata; private javax.swing.JButton cmdBack; private javax.swing.JButton cmdForeground; private javax.swing.JButton cmdForward; private javax.swing.JButton cmdFullPoly; private javax.swing.JButton cmdFullPoly1; private javax.swing.JToggleButton cmdJoinPoly; private javax.swing.JToggleButton cmdMoveHandle; private javax.swing.JToggleButton cmdMovePolygon; private javax.swing.JToggleButton cmdNewLinestring; private javax.swing.JToggleButton cmdNewPoint; private javax.swing.JToggleButton cmdNewPolygon; private javax.swing.JToggleButton cmdOrthogonalRectangle; private javax.swing.JToggleButton cmdPan; private javax.swing.JToggleButton cmdRaisePolygon; private javax.swing.JButton cmdRedo; private javax.swing.JToggleButton cmdRemoveHandle; private javax.swing.JToggleButton cmdRemovePolygon; private javax.swing.JToggleButton cmdRotatePolygon; private javax.swing.JToggleButton cmdSearchFlurstueck; private javax.swing.JButton cmdSearchKassenzeichen; private javax.swing.JToggleButton cmdSelect; private javax.swing.JToggleButton cmdSnap; private javax.swing.JToggleButton cmdSplitPoly; private javax.swing.JButton cmdUndo; private javax.swing.JToggleButton cmdWmsBackground; private javax.swing.JToggleButton cmdZoom; private javax.swing.ButtonGroup handleGroup; private javax.swing.JPanel jPanel2; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JSeparator jSeparator5; private javax.swing.JLabel lblCoord; private javax.swing.JLabel lblInfo; private javax.swing.JLabel lblMeasurement; private javax.swing.JLabel lblScale; private javax.swing.JLabel lblWaiting; private javax.swing.ButtonGroup mainGroup; private de.cismet.cismap.commons.gui.MappingComponent mappingComp; private javax.swing.JRadioButtonMenuItem mniSearchEllipse1; private javax.swing.JRadioButtonMenuItem mniSearchPolygon1; private javax.swing.JRadioButtonMenuItem mniSearchRectangle1; private javax.swing.JPanel panMap; private javax.swing.JPanel panStatus; private javax.swing.JPopupMenu pomScale; private javax.swing.JPopupMenu popMenSearch; private javax.swing.ButtonGroup searchGroup; private javax.swing.JSeparator sep2; private javax.swing.JSeparator sep3; private javax.swing.JSeparator sep4; private javax.swing.JToolBar tobVerdis; // End of variables declaration//GEN-END:variables //~ Constructors ----------------------------------------------------------- /** * Creates new form KartenPanel. */ public KartenPanel() { initComponents(); ((JPopupMenuButton)cmdSearchKassenzeichen).setPopupMenu(popMenSearch); CidsAppBackend.getInstance().setMainMap(mappingComp); CismapBroker.getInstance().setMappingComponent(mappingComp); mappingComp.getFeatureCollection().addFeatureCollectionListener(this); // mappingComp.putInputListener(MappingComponent.ATTACH_POLYGON_TO_ALPHADATA, new AttachFeatureListener()); mappingComp.setBackgroundEnabled(true); // CreateGeometryListener g=new CreateGeometryListener(mappingComp,JLabel.class) { // // // }; // mappingComp.addInputListener("TIM_EASY_CREATOR",) // TIM Easy cmdNewPoint.setVisible(true); ((JHistoryButton) cmdForward).setDirection(JHistoryButton.DIRECTION_FORWARD); ((JHistoryButton) cmdBack).setDirection(JHistoryButton.DIRECTION_BACKWARD); ((JHistoryButton) cmdForward).setHistoryModel(mappingComp); ((JHistoryButton) cmdBack).setHistoryModel(mappingComp); cmdWmsBackground.setSelected(mappingComp.isBackgroundEnabled()); mappingComp.getCamera().addPropertyChangeListener( PCamera.PROPERTY_VIEW_TRANSFORM, new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent evt) { final int sd = (int) (mappingComp.getScaleDenominator() + 0.5); lblScale.setText("1:" + sd); } }); addScalePopupMenu("1:500", 500); addScalePopupMenu("1:750", 750); addScalePopupMenu("1:1000", 1000); addScalePopupMenu("1:1500", 1500); addScalePopupMenu("1:2000", 2000); addScalePopupMenu("1:2500", 2500); addScalePopupMenu("1:5000", 5000); addScalePopupMenu("1:7500", 7500); addScalePopupMenu("1:10000", 10000); if (LOG.isDebugEnabled()) { LOG.debug("Fl\u00E4chen\u00DCbersichtsTabellenPanel als Observer anmelden"); } ((Observable) mappingComp.getMemUndo()).addObserver(this); ((Observable) mappingComp.getMemRedo()).addObserver(this); // if (mappingComp.getFeatureCollection() instanceof DefaultFeatureCollection) { // ((DefaultFeatureCollection) mappingComp.getFeatureCollection()).setSingleSelection(true); // } } //~ Methods ---------------------------------------------------------------- @Override public void propertyChange(PropertyChangeEvent evt) { final Object source = evt.getSource(); final String propName = evt.getPropertyName(); final Object newValue = evt.getNewValue(); if (source == null) { return; } if (source.equals(mappingComp.getInputListener(Main.KASSENZEICHEN_SEARCH_GEOMETRY_LISTENER))) { if (AbstractCreateSearchGeometryListener.PROPERTY_FORGUI_MODE.equals(propName) || AbstractCreateSearchGeometryListener.PROPERTY_MODE.equals(propName)) { mniSearchEllipse1.setSelected(CreateGeometryListener.ELLIPSE.equals(newValue)); mniSearchPolygon1.setSelected(CreateGeometryListener.POLYGON.equals(newValue)); mniSearchRectangle1.setSelected(CreateGeometryListener.RECTANGLE.equals(newValue)); } } } /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The * content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; pomScale = new javax.swing.JPopupMenu(); popMenSearch = new javax.swing.JPopupMenu(); mniSearchRectangle1 = new javax.swing.JRadioButtonMenuItem(); mniSearchPolygon1 = new javax.swing.JRadioButtonMenuItem(); mniSearchEllipse1 = new javax.swing.JRadioButtonMenuItem(); mainGroup = new javax.swing.ButtonGroup(); handleGroup = new javax.swing.ButtonGroup(); searchGroup = new javax.swing.ButtonGroup(); panMap = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); mappingComp = new de.cismet.cismap.commons.gui.MappingComponent(); panStatus = new javax.swing.JPanel(); cmdAdd = new javax.swing.JButton(); lblInfo = new javax.swing.JLabel(); lblCoord = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); lblWaiting = new javax.swing.JLabel(); lblMeasurement = new javax.swing.JLabel(); lblScale = new javax.swing.JLabel(); jSeparator2 = new javax.swing.JSeparator(); tobVerdis = new javax.swing.JToolBar(); cmdFullPoly = new javax.swing.JButton(); cmdFullPoly1 = new javax.swing.JButton(); cmdBack = new JHistoryButton(); cmdForward = new JHistoryButton(); jSeparator5 = new javax.swing.JSeparator(); cmdWmsBackground = new javax.swing.JToggleButton(); cmdForeground = new javax.swing.JButton(); cmdSnap = new javax.swing.JToggleButton(); sep2 = new javax.swing.JSeparator(); cmdZoom = new javax.swing.JToggleButton(); cmdPan = new javax.swing.JToggleButton(); cmdSelect = new javax.swing.JToggleButton(); cmdALB = new javax.swing.JToggleButton(); cmdMovePolygon = new javax.swing.JToggleButton(); cmdNewPolygon = new javax.swing.JToggleButton(); cmdNewLinestring = new javax.swing.JToggleButton(); cmdNewPoint = new javax.swing.JToggleButton(); cmdOrthogonalRectangle = new javax.swing.JToggleButton(); cmdSearchFlurstueck = new javax.swing.JToggleButton(); cmdSearchKassenzeichen = new CidsBeanDropJPopupMenuButton(Main.KASSENZEICHEN_SEARCH_GEOMETRY_LISTENER, mappingComp, null); cmdRaisePolygon = new javax.swing.JToggleButton(); cmdRemovePolygon = new javax.swing.JToggleButton(); cmdAttachPolyToAlphadata = new javax.swing.JToggleButton(); cmdJoinPoly = new javax.swing.JToggleButton(); cmdSplitPoly = new javax.swing.JToggleButton(); sep3 = new javax.swing.JSeparator(); cmdMoveHandle = new javax.swing.JToggleButton(); cmdAddHandle = new javax.swing.JToggleButton(); cmdRemoveHandle = new javax.swing.JToggleButton(); cmdRotatePolygon = new javax.swing.JToggleButton(); sep4 = new javax.swing.JSeparator(); cmdUndo = new javax.swing.JButton(); cmdRedo = new javax.swing.JButton(); popMenSearch.addPopupMenuListener(new javax.swing.event.PopupMenuListener() { public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) { popMenSearchPopupMenuWillBecomeVisible(evt); } }); mniSearchRectangle1.setAction(searchRectangleAction); searchGroup.add(mniSearchRectangle1); mniSearchRectangle1.setSelected(true); mniSearchRectangle1.setText("Rechteck"); mniSearchRectangle1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/rectangleSearch.png"))); // NOI18N popMenSearch.add(mniSearchRectangle1); mniSearchPolygon1.setAction(searchPolygonAction); searchGroup.add(mniSearchPolygon1); mniSearchPolygon1.setText("Polygon"); mniSearchPolygon1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/polygonSearch.png"))); // NOI18N popMenSearch.add(mniSearchPolygon1); mniSearchEllipse1.setAction(searchEllipseAction); searchGroup.add(mniSearchEllipse1); mniSearchEllipse1.setText("Ellipse / Kreis"); mniSearchEllipse1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/ellipseSearch.png"))); // NOI18N popMenSearch.add(mniSearchEllipse1); setLayout(new java.awt.BorderLayout()); panMap.setLayout(new java.awt.BorderLayout()); jPanel2.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(2, 2, 2, 2), javax.swing.BorderFactory.createEtchedBorder()), javax.swing.BorderFactory.createEmptyBorder(4, 4, 1, 4))); jPanel2.setLayout(new java.awt.BorderLayout()); mappingComp.setBorder(javax.swing.BorderFactory.createEtchedBorder()); mappingComp.setInternalLayerWidgetAvailable(true); jPanel2.add(mappingComp, java.awt.BorderLayout.CENTER); panStatus.setBorder(javax.swing.BorderFactory.createEmptyBorder(3, 1, 1, 1)); panStatus.setLayout(new java.awt.GridBagLayout()); cmdAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/statusbar/layersman.png"))); // NOI18N cmdAdd.setBorderPainted(false); cmdAdd.setFocusPainted(false); cmdAdd.setMinimumSize(new java.awt.Dimension(25, 25)); cmdAdd.setPreferredSize(new java.awt.Dimension(25, 25)); cmdAdd.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/statusbar/layersman.png"))); // NOI18N cmdAdd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdAddActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 7; gridBagConstraints.gridy = 0; panStatus.add(cmdAdd, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; panStatus.add(lblInfo, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; panStatus.add(lblCoord, gridBagConstraints); jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); panStatus.add(jSeparator1, gridBagConstraints); lblWaiting.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/exec.png"))); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 6; gridBagConstraints.gridy = 0; panStatus.add(lblWaiting, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 5; gridBagConstraints.gridy = 0; panStatus.add(lblMeasurement, gridBagConstraints); lblScale.setText("1:???"); lblScale.setComponentPopupMenu(pomScale); lblScale.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { lblScaleMousePressed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; panStatus.add(lblScale, gridBagConstraints); jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); panStatus.add(jSeparator2, gridBagConstraints); jPanel2.add(panStatus, java.awt.BorderLayout.SOUTH); panMap.add(jPanel2, java.awt.BorderLayout.CENTER); tobVerdis.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); tobVerdis.setFloatable(false); cmdFullPoly.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/fullPoly.png"))); // NOI18N cmdFullPoly.setToolTipText("Zeige alle Flächen"); cmdFullPoly.setBorderPainted(false); cmdFullPoly.setContentAreaFilled(false); cmdFullPoly.setFocusPainted(false); cmdFullPoly.setFocusable(false); cmdFullPoly.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdFullPolyActionPerformed(evt); } }); tobVerdis.add(cmdFullPoly); cmdFullPoly1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/fullSelPoly.png"))); // NOI18N cmdFullPoly1.setToolTipText("Zoom zur ausgewählten Fläche"); cmdFullPoly1.setBorderPainted(false); cmdFullPoly1.setContentAreaFilled(false); cmdFullPoly1.setFocusPainted(false); cmdFullPoly1.setFocusable(false); cmdFullPoly1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdFullPoly1ActionPerformed(evt); } }); tobVerdis.add(cmdFullPoly1); cmdBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/back.png"))); // NOI18N cmdBack.setToolTipText("Zurück"); cmdBack.setBorderPainted(false); cmdBack.setContentAreaFilled(false); cmdBack.setFocusPainted(false); cmdBack.setFocusable(false); tobVerdis.add(cmdBack); cmdForward.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/fwd.png"))); // NOI18N cmdForward.setToolTipText("Vor"); cmdForward.setBorderPainted(false); cmdForward.setContentAreaFilled(false); cmdForward.setFocusPainted(false); cmdForward.setFocusable(false); tobVerdis.add(cmdForward); jSeparator5.setOrientation(javax.swing.SwingConstants.VERTICAL); jSeparator5.setMaximumSize(new java.awt.Dimension(2, 32767)); tobVerdis.add(jSeparator5); cmdWmsBackground.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/map.png"))); // NOI18N cmdWmsBackground.setToolTipText("Hintergrund an/aus"); cmdWmsBackground.setBorderPainted(false); cmdWmsBackground.setContentAreaFilled(false); cmdWmsBackground.setFocusPainted(false); cmdWmsBackground.setFocusable(false); cmdWmsBackground.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/map_on.png"))); // NOI18N cmdWmsBackground.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdWmsBackgroundActionPerformed(evt); } }); tobVerdis.add(cmdWmsBackground); cmdForeground.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/foreground.png"))); // NOI18N cmdForeground.setToolTipText("Vordergrund an/aus"); cmdForeground.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 3, 1, 3)); cmdForeground.setBorderPainted(false); cmdForeground.setContentAreaFilled(false); cmdForeground.setFocusPainted(false); cmdForeground.setFocusable(false); cmdForeground.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdForeground.setSelected(true); cmdForeground.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/foreground_on.png"))); // NOI18N cmdForeground.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdForeground.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdForegroundActionPerformed(evt); } }); tobVerdis.add(cmdForeground); cmdSnap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/snap.png"))); // NOI18N cmdSnap.setSelected(true); cmdSnap.setToolTipText("Snapping an/aus"); cmdSnap.setBorderPainted(false); cmdSnap.setContentAreaFilled(false); cmdSnap.setFocusPainted(false); cmdSnap.setFocusable(false); cmdSnap.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/snap_selected.png"))); // NOI18N cmdSnap.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdSnapActionPerformed(evt); } }); tobVerdis.add(cmdSnap); sep2.setOrientation(javax.swing.SwingConstants.VERTICAL); sep2.setMaximumSize(new java.awt.Dimension(2, 32767)); tobVerdis.add(sep2); mainGroup.add(cmdZoom); cmdZoom.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/zoom.png"))); // NOI18N cmdZoom.setToolTipText("Zoomen"); cmdZoom.setBorderPainted(false); cmdZoom.setContentAreaFilled(false); cmdZoom.setFocusPainted(false); cmdZoom.setFocusable(false); cmdZoom.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/zoom_selected.png"))); // NOI18N cmdZoom.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdZoomActionPerformed(evt); } }); tobVerdis.add(cmdZoom); mainGroup.add(cmdPan); cmdPan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/move2.png"))); // NOI18N cmdPan.setToolTipText("Verschieben"); cmdPan.setBorderPainted(false); cmdPan.setContentAreaFilled(false); cmdPan.setFocusPainted(false); cmdPan.setFocusable(false); cmdPan.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/move2_selected.png"))); // NOI18N cmdPan.setVerifyInputWhenFocusTarget(false); cmdPan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdPanActionPerformed(evt); } }); tobVerdis.add(cmdPan); mainGroup.add(cmdSelect); cmdSelect.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/select.png"))); // NOI18N cmdSelect.setSelected(true); cmdSelect.setToolTipText("Auswählen"); cmdSelect.setBorderPainted(false); cmdSelect.setContentAreaFilled(false); cmdSelect.setFocusPainted(false); cmdSelect.setFocusable(false); cmdSelect.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/select_selected.png"))); // NOI18N cmdSelect.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdSelectActionPerformed(evt); } }); tobVerdis.add(cmdSelect); mainGroup.add(cmdALB); cmdALB.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/alb.png"))); // NOI18N cmdALB.setToolTipText("ALB"); cmdALB.setBorderPainted(false); cmdALB.setContentAreaFilled(false); cmdALB.setFocusPainted(false); cmdALB.setFocusable(false); cmdALB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdALB.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/alb_selected.png"))); // NOI18N cmdALB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdALB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdALBActionPerformed(evt); } }); tobVerdis.add(cmdALB); mainGroup.add(cmdMovePolygon); cmdMovePolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/movePoly.png"))); // NOI18N cmdMovePolygon.setToolTipText("Polygon verschieben"); cmdMovePolygon.setBorderPainted(false); cmdMovePolygon.setContentAreaFilled(false); cmdMovePolygon.setFocusPainted(false); cmdMovePolygon.setFocusable(false); cmdMovePolygon.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/movePoly_selected.png"))); // NOI18N cmdMovePolygon.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdMovePolygonActionPerformed(evt); } }); tobVerdis.add(cmdMovePolygon); mainGroup.add(cmdNewPolygon); cmdNewPolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/newPoly.png"))); // NOI18N cmdNewPolygon.setToolTipText("neues Polygon"); cmdNewPolygon.setBorderPainted(false); cmdNewPolygon.setContentAreaFilled(false); cmdNewPolygon.setFocusPainted(false); cmdNewPolygon.setFocusable(false); cmdNewPolygon.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/newPoly_selected.png"))); // NOI18N cmdNewPolygon.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdNewPolygonActionPerformed(evt); } }); tobVerdis.add(cmdNewPolygon); mainGroup.add(cmdNewLinestring); cmdNewLinestring.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/newLine.png"))); // NOI18N cmdNewLinestring.setToolTipText("neue Linie"); cmdNewLinestring.setBorderPainted(false); cmdNewLinestring.setContentAreaFilled(false); cmdNewLinestring.setFocusPainted(false); cmdNewLinestring.setFocusable(false); cmdNewLinestring.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdNewLinestring.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/newLine_selected.png"))); // NOI18N cmdNewLinestring.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdNewLinestring.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdNewLinestringActionPerformed(evt); } }); tobVerdis.add(cmdNewLinestring); mainGroup.add(cmdNewPoint); cmdNewPoint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/newPoint.png"))); // NOI18N cmdNewPoint.setToolTipText("neuer Punkt"); cmdNewPoint.setBorderPainted(false); cmdNewPoint.setContentAreaFilled(false); cmdNewPoint.setFocusPainted(false); cmdNewPoint.setFocusable(false); cmdNewPoint.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/newPoint_selected.png"))); // NOI18N cmdNewPoint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdNewPointActionPerformed(evt); } }); tobVerdis.add(cmdNewPoint); mainGroup.add(cmdOrthogonalRectangle); cmdOrthogonalRectangle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/rechtwDreieck.png"))); // NOI18N cmdOrthogonalRectangle.setToolTipText("Rechteckige Fläche"); cmdOrthogonalRectangle.setBorderPainted(false); cmdOrthogonalRectangle.setContentAreaFilled(false); cmdOrthogonalRectangle.setFocusPainted(false); cmdOrthogonalRectangle.setFocusable(false); cmdOrthogonalRectangle.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdOrthogonalRectangle.setMaximumSize(new java.awt.Dimension(28, 20)); cmdOrthogonalRectangle.setPreferredSize(new java.awt.Dimension(28, 20)); cmdOrthogonalRectangle.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/rechtwDreieck_selected.png"))); // NOI18N cmdOrthogonalRectangle.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdOrthogonalRectangle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdOrthogonalRectangleActionPerformed(evt); } }); tobVerdis.add(cmdOrthogonalRectangle); mainGroup.add(cmdSearchFlurstueck); cmdSearchFlurstueck.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/alk.png"))); // NOI18N cmdSearchFlurstueck.setToolTipText("Alkis Renderer"); cmdSearchFlurstueck.setBorderPainted(false); cmdSearchFlurstueck.setContentAreaFilled(false); cmdSearchFlurstueck.setFocusPainted(false); cmdSearchFlurstueck.setFocusable(false); cmdSearchFlurstueck.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdSearchFlurstueck.setMaximumSize(new java.awt.Dimension(28, 20)); cmdSearchFlurstueck.setPreferredSize(new java.awt.Dimension(28, 20)); cmdSearchFlurstueck.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/alk_selected.png"))); // NOI18N cmdSearchFlurstueck.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdSearchFlurstueck.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdSearchFlurstueckActionPerformed(evt); } }); tobVerdis.add(cmdSearchFlurstueck); cmdSearchKassenzeichen.setAction(searchAction); cmdSearchKassenzeichen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/kassenzeichenSearchRectangle.png"))); // NOI18N cmdSearchKassenzeichen.setToolTipText("Kassenzeichen-Suche"); cmdSearchKassenzeichen.setBorderPainted(false); mainGroup.add(cmdSearchKassenzeichen); cmdSearchKassenzeichen.setContentAreaFilled(false); cmdSearchKassenzeichen.setFocusPainted(false); cmdSearchKassenzeichen.setFocusable(false); cmdSearchKassenzeichen.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdSearchKassenzeichen.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/kassenzeichenSearchRectangle_selected.png"))); // NOI18N cmdSearchKassenzeichen.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdSearchKassenzeichen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdSearchKassenzeichenActionPerformed(evt); } }); - if (StaticDebuggingTools.checkHomeForFile("cismetVerdisTest")) { - tobVerdis.add(cmdSearchKassenzeichen); - } + tobVerdis.add(cmdSearchKassenzeichen); mainGroup.add(cmdRaisePolygon); cmdRaisePolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/raisePoly.png"))); // NOI18N cmdRaisePolygon.setToolTipText("Polygon hochholen"); cmdRaisePolygon.setBorderPainted(false); cmdRaisePolygon.setContentAreaFilled(false); cmdRaisePolygon.setFocusPainted(false); cmdRaisePolygon.setFocusable(false); cmdRaisePolygon.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/raisePoly_selected.png"))); // NOI18N cmdRaisePolygon.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdRaisePolygonActionPerformed(evt); } }); tobVerdis.add(cmdRaisePolygon); mainGroup.add(cmdRemovePolygon); cmdRemovePolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/removePoly.png"))); // NOI18N cmdRemovePolygon.setToolTipText("Polygon entfernen"); cmdRemovePolygon.setBorderPainted(false); cmdRemovePolygon.setContentAreaFilled(false); cmdRemovePolygon.setFocusPainted(false); cmdRemovePolygon.setFocusable(false); cmdRemovePolygon.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/removePoly_selected.png"))); // NOI18N cmdRemovePolygon.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdRemovePolygonActionPerformed(evt); } }); tobVerdis.add(cmdRemovePolygon); mainGroup.add(cmdAttachPolyToAlphadata); cmdAttachPolyToAlphadata.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/polygonAttachment.png"))); // NOI18N cmdAttachPolyToAlphadata.setToolTipText("Polygon zuordnen"); cmdAttachPolyToAlphadata.setBorderPainted(false); cmdAttachPolyToAlphadata.setContentAreaFilled(false); cmdAttachPolyToAlphadata.setFocusPainted(false); cmdAttachPolyToAlphadata.setFocusable(false); cmdAttachPolyToAlphadata.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/polygonAttachment_selected.png"))); // NOI18N cmdAttachPolyToAlphadata.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdAttachPolyToAlphadataActionPerformed(evt); } }); tobVerdis.add(cmdAttachPolyToAlphadata); mainGroup.add(cmdJoinPoly); cmdJoinPoly.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/joinPoly.png"))); // NOI18N cmdJoinPoly.setToolTipText("Polygone zusammenfassen"); cmdJoinPoly.setBorderPainted(false); cmdJoinPoly.setContentAreaFilled(false); cmdJoinPoly.setFocusPainted(false); cmdJoinPoly.setFocusable(false); cmdJoinPoly.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/joinPoly_selected.png"))); // NOI18N cmdJoinPoly.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdJoinPolyActionPerformed(evt); } }); tobVerdis.add(cmdJoinPoly); mainGroup.add(cmdSplitPoly); cmdSplitPoly.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/splitPoly.png"))); // NOI18N cmdSplitPoly.setToolTipText("Polygon splitten"); cmdSplitPoly.setBorderPainted(false); cmdSplitPoly.setContentAreaFilled(false); cmdSplitPoly.setFocusPainted(false); cmdSplitPoly.setFocusable(false); cmdSplitPoly.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/splitPoly_selected.png"))); // NOI18N cmdSplitPoly.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdSplitPolyActionPerformed(evt); } }); tobVerdis.add(cmdSplitPoly); sep3.setOrientation(javax.swing.SwingConstants.VERTICAL); sep3.setMaximumSize(new java.awt.Dimension(2, 32767)); tobVerdis.add(sep3); handleGroup.add(cmdMoveHandle); cmdMoveHandle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/moveHandle.png"))); // NOI18N cmdMoveHandle.setSelected(true); cmdMoveHandle.setToolTipText("Handle verschieben"); cmdMoveHandle.setBorderPainted(false); cmdMoveHandle.setContentAreaFilled(false); cmdMoveHandle.setFocusPainted(false); cmdMoveHandle.setFocusable(false); cmdMoveHandle.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/moveHandle_selected.png"))); // NOI18N cmdMoveHandle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdMoveHandleActionPerformed(evt); } }); tobVerdis.add(cmdMoveHandle); handleGroup.add(cmdAddHandle); cmdAddHandle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/addHandle.png"))); // NOI18N cmdAddHandle.setToolTipText("Handle hinzufügen"); cmdAddHandle.setBorderPainted(false); cmdAddHandle.setContentAreaFilled(false); cmdAddHandle.setFocusPainted(false); cmdAddHandle.setFocusable(false); cmdAddHandle.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/addHandle_selected.png"))); // NOI18N cmdAddHandle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdAddHandleActionPerformed(evt); } }); tobVerdis.add(cmdAddHandle); handleGroup.add(cmdRemoveHandle); cmdRemoveHandle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/removeHandle.png"))); // NOI18N cmdRemoveHandle.setToolTipText("Handle entfernen"); cmdRemoveHandle.setBorderPainted(false); cmdRemoveHandle.setContentAreaFilled(false); cmdRemoveHandle.setFocusPainted(false); cmdRemoveHandle.setFocusable(false); cmdRemoveHandle.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/removeHandle_selected.png"))); // NOI18N cmdRemoveHandle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdRemoveHandleActionPerformed(evt); } }); tobVerdis.add(cmdRemoveHandle); handleGroup.add(cmdRotatePolygon); cmdRotatePolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/rotate16.png"))); // NOI18N cmdRotatePolygon.setToolTipText("Rotiere Polygon"); cmdRotatePolygon.setBorderPainted(false); cmdRotatePolygon.setContentAreaFilled(false); cmdRotatePolygon.setFocusPainted(false); cmdRotatePolygon.setFocusable(false); cmdRotatePolygon.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/rotate16_selected.png"))); // NOI18N cmdRotatePolygon.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdRotatePolygonActionPerformed(evt); } }); tobVerdis.add(cmdRotatePolygon); sep4.setOrientation(javax.swing.SwingConstants.VERTICAL); sep4.setMaximumSize(new java.awt.Dimension(2, 32767)); tobVerdis.add(sep4); cmdUndo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/undo.png"))); // NOI18N cmdUndo.setToolTipText("Undo"); cmdUndo.setBorderPainted(false); cmdUndo.setContentAreaFilled(false); cmdUndo.setEnabled(false); cmdUndo.setFocusPainted(false); cmdUndo.setFocusable(false); cmdUndo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdUndo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdUndoActionPerformed(evt); } }); tobVerdis.add(cmdUndo); cmdRedo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/redo.png"))); // NOI18N cmdRedo.setBorderPainted(false); cmdRedo.setContentAreaFilled(false); cmdRedo.setEnabled(false); cmdRedo.setFocusPainted(false); cmdRedo.setFocusable(false); cmdRedo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdRedo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdRedo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdRedoActionPerformed(evt); } }); tobVerdis.add(cmdRedo); panMap.add(tobVerdis, java.awt.BorderLayout.NORTH); add(panMap, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdAddActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdAddActionPerformed try { mappingComp.showInternalLayerWidget(!mappingComp.isInternalLayerWidgetVisible(), 500); } catch (Throwable t) { LOG.error("Fehler beim Anzeigen des Layersteuerelements", t); } }//GEN-LAST:event_cmdAddActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void lblScaleMousePressed(final java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblScaleMousePressed if (evt.isPopupTrigger()) { pomScale.setVisible(true); } }//GEN-LAST:event_lblScaleMousePressed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdFullPolyActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdFullPolyActionPerformed mappingComp.zoomToFullFeatureCollectionBounds(); }//GEN-LAST:event_cmdFullPolyActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdFullPoly1ActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdFullPoly1ActionPerformed mappingComp.zoomToSelectedNode(); }//GEN-LAST:event_cmdFullPoly1ActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdWmsBackgroundActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdWmsBackgroundActionPerformed if (mappingComp.isBackgroundEnabled()) { mappingComp.setBackgroundEnabled(false); cmdWmsBackground.setSelected(false); } else { mappingComp.setBackgroundEnabled(true); cmdWmsBackground.setSelected(true); mappingComp.queryServices(); } }//GEN-LAST:event_cmdWmsBackgroundActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdForegroundActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdForegroundActionPerformed if (mappingComp.isFeatureCollectionVisible()) { mappingComp.setFeatureCollectionVisibility(false); cmdForeground.setSelected(false); } else { mappingComp.setFeatureCollectionVisibility(true); cmdForeground.setSelected(true); } }//GEN-LAST:event_cmdForegroundActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdSnapActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdSnapActionPerformed mappingComp.setSnappingEnabled(cmdSnap.isSelected()); mappingComp.setVisualizeSnappingEnabled(cmdSnap.isSelected()); mappingComp.setInGlueIdenticalPointsMode(cmdSnap.isSelected()); }//GEN-LAST:event_cmdSnapActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdMoveHandleActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdMoveHandleActionPerformed mappingComp.setHandleInteractionMode(MappingComponent.MOVE_HANDLE); }//GEN-LAST:event_cmdMoveHandleActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdAddHandleActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdAddHandleActionPerformed mappingComp.setHandleInteractionMode(MappingComponent.ADD_HANDLE); }//GEN-LAST:event_cmdAddHandleActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdRemoveHandleActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdRemoveHandleActionPerformed mappingComp.setHandleInteractionMode(MappingComponent.REMOVE_HANDLE); }//GEN-LAST:event_cmdRemoveHandleActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdRotatePolygonActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdRotatePolygonActionPerformed mappingComp.setHandleInteractionMode(MappingComponent.ROTATE_POLYGON); }//GEN-LAST:event_cmdRotatePolygonActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdUndoActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdUndoActionPerformed LOG.info("UNDO"); final CustomAction a = mappingComp.getMemUndo().getLastAction(); if (LOG.isDebugEnabled()) { LOG.debug("... Aktion ausf\u00FChren: " + a.info()); } try { a.doAction(); } catch (Exception e) { LOG.error("Error beim Ausf\u00FChren der Aktion", e); } final CustomAction inverse = a.getInverse(); mappingComp.getMemRedo().addAction(inverse); if (LOG.isDebugEnabled()) { LOG.debug("... neue Aktion auf REDO-Stack: " + inverse); LOG.debug("... fertig"); } }//GEN-LAST:event_cmdUndoActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdRedoActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdRedoActionPerformed LOG.info("REDO"); final CustomAction a = mappingComp.getMemRedo().getLastAction(); if (LOG.isDebugEnabled()) { LOG.debug("... Aktion ausf\u00FChren: " + a.info()); } try { a.doAction(); } catch (Exception e) { LOG.error("Error beim Ausf\u00FChren der Aktion", e); } final CustomAction inverse = a.getInverse(); mappingComp.getMemUndo().addAction(inverse); if (LOG.isDebugEnabled()) { LOG.debug("... neue Aktion auf UNDO-Stack: " + inverse); LOG.debug("... fertig"); } }//GEN-LAST:event_cmdRedoActionPerformed private void popMenSearchPopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_popMenSearchPopupMenuWillBecomeVisible }//GEN-LAST:event_popMenSearchPopupMenuWillBecomeVisible /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdSplitPolyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdSplitPolyActionPerformed mappingComp.setInteractionMode(MappingComponent.SPLIT_POLYGON); cmdMoveHandleActionPerformed(null); }//GEN-LAST:event_cmdSplitPolyActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdJoinPolyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdJoinPolyActionPerformed mappingComp.setInteractionMode(MappingComponent.JOIN_POLYGONS); }//GEN-LAST:event_cmdJoinPolyActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdAttachPolyToAlphadataActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdAttachPolyToAlphadataActionPerformed mappingComp.setInteractionMode(MappingComponent.ATTACH_POLYGON_TO_ALPHADATA); }//GEN-LAST:event_cmdAttachPolyToAlphadataActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdRemovePolygonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdRemovePolygonActionPerformed mappingComp.setInteractionMode(MappingComponent.REMOVE_POLYGON); }//GEN-LAST:event_cmdRemovePolygonActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdRaisePolygonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdRaisePolygonActionPerformed mappingComp.setInteractionMode(MappingComponent.RAISE_POLYGON); }//GEN-LAST:event_cmdRaisePolygonActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdNewPointActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdNewPointActionPerformed mappingComp.setInteractionMode(MappingComponent.NEW_POLYGON); ((CreateGeometryListener) mappingComp.getInputListener(MappingComponent.NEW_POLYGON)).setMode( CreateGeometryListener.POINT); }//GEN-LAST:event_cmdNewPointActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdPanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdPanActionPerformed mappingComp.setInteractionMode(MappingComponent.PAN); }//GEN-LAST:event_cmdPanActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdSelectActionPerformed mappingComp.setInteractionMode(MappingComponent.SELECT); cmdMoveHandleActionPerformed(null); }//GEN-LAST:event_cmdSelectActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdALBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdALBActionPerformed mappingComp.setInteractionMode(MappingComponent.CUSTOM_FEATUREINFO); cmdALB.isSelected(); }//GEN-LAST:event_cmdALBActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdMovePolygonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdMovePolygonActionPerformed mappingComp.setInteractionMode(MappingComponent.MOVE_POLYGON); }//GEN-LAST:event_cmdMovePolygonActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdNewPolygonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdNewPolygonActionPerformed mappingComp.setInteractionMode(MappingComponent.NEW_POLYGON); ((CreateGeometryListener) mappingComp.getInputListener(MappingComponent.NEW_POLYGON)).setMode( CreateGeometryListener.POLYGON); ((CreateGeometryListener) mappingComp.getInputListener(MappingComponent.NEW_POLYGON)).setGeometryFeatureClass(PureNewFeature.class); }//GEN-LAST:event_cmdNewPolygonActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdNewLinestringActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdNewLinestringActionPerformed mappingComp.setInteractionMode(MappingComponent.NEW_POLYGON); ((CreateGeometryListener) mappingComp.getInputListener(MappingComponent.NEW_POLYGON)).setMode( CreateGeometryListener.LINESTRING); ((CreateGeometryListener) mappingComp.getInputListener(MappingComponent.NEW_POLYGON)).setGeometryFeatureClass( PureNewFeatureWithThickerLineString.class); }//GEN-LAST:event_cmdNewLinestringActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdOrthogonalRectangleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdOrthogonalRectangleActionPerformed mappingComp.setInteractionMode(MappingComponent.NEW_POLYGON); ((CreateGeometryListener) mappingComp.getInputListener(MappingComponent.NEW_POLYGON)).setMode( CreateGeometryListener.RECTANGLE_FROM_LINE); }//GEN-LAST:event_cmdOrthogonalRectangleActionPerformed private void cmdSearchFlurstueckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdSearchFlurstueckActionPerformed mappingComp.setInteractionMode(Main.FLURSTUECK_SEARCH_GEOMETRY_LISTENER); }//GEN-LAST:event_cmdSearchFlurstueckActionPerformed private void cmdSearchKassenzeichenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdSearchKassenzeichenActionPerformed }//GEN-LAST:event_cmdSearchKassenzeichenActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void cmdZoomActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdZoomActionPerformed mappingComp.setInteractionMode(MappingComponent.ZOOM); }//GEN-LAST:event_cmdZoomActionPerformed /** * DOCUMENT ME! * * @param text DOCUMENT ME! * @param scaleDenominator DOCUMENT ME! */ private void addScalePopupMenu(final String text, final double scaleDenominator) { final JMenuItem jmi = new JMenuItem(text); jmi.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { mappingComp.gotoBoundingBoxWithHistory(mappingComp.getBoundingBoxFromScale(scaleDenominator)); } }); pomScale.add(jmi); } @Override public void allFeaturesRemoved(final FeatureCollectionEvent fce) { } @Override public void featureCollectionChanged() { } @Override public void featureReconsiderationRequested(final FeatureCollectionEvent fce) { } @Override public void featureSelectionChanged(final FeatureCollectionEvent fce) { refreshMeasurementsInStatus(); } @Override public void featuresAdded(final FeatureCollectionEvent fce) { } @Override public void featuresChanged(final FeatureCollectionEvent fce) { if (LOG.isDebugEnabled()) { LOG.debug("FeatureChanged"); } if (mappingComp.getInteractionMode().equals(MappingComponent.NEW_POLYGON)) { refreshMeasurementsInStatus(fce.getEventFeatures()); } else { refreshMeasurementsInStatus(); } } @Override public void featuresRemoved(final FeatureCollectionEvent fce) { } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalAborted(final RetrievalEvent e) { activeRetrievalServices.remove(((ServiceLayer) e.getRetrievalService()).getName()); checkProgress(); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalComplete(final RetrievalEvent e) { activeRetrievalServices.remove(((ServiceLayer) e.getRetrievalService()).getName()); checkProgress(); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalError(final RetrievalEvent e) { activeRetrievalServices.remove(((ServiceLayer) e.getRetrievalService()).getName()); checkProgress(); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalProgress(final RetrievalEvent e) { activeRetrievalServices.remove(((ServiceLayer) e.getRetrievalService()).getName()); checkProgress(); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalStarted(final RetrievalEvent e) { activeRetrievalServices.add(((ServiceLayer) e.getRetrievalService()).getName()); checkProgress(); } /** * DOCUMENT ME! */ private void checkProgress() { // log.debug(activeRetrievalServices); if (activeRetrievalServices.size() > 0) { setWaiting(true); } else { setWaiting(false); } } @Override public void update(final Observable o, final Object arg) { if (o.equals(mappingComp.getMemUndo())) { if (arg.equals(MementoInterface.ACTIVATE) && !cmdUndo.isEnabled()) { if (LOG.isDebugEnabled()) { LOG.debug("UNDO-Button aktivieren"); } EventQueue.invokeLater(new Runnable() { @Override public void run() { cmdUndo.setEnabled(true); } }); } else if (arg.equals(MementoInterface.DEACTIVATE) && cmdUndo.isEnabled()) { if (LOG.isDebugEnabled()) { LOG.debug("UNDO-Button deaktivieren"); } EventQueue.invokeLater(new Runnable() { @Override public void run() { cmdUndo.setEnabled(false); } }); } } else if (o.equals(mappingComp.getMemRedo())) { if (arg.equals(MementoInterface.ACTIVATE) && !cmdRedo.isEnabled()) { if (LOG.isDebugEnabled()) { LOG.debug("REDO-Button aktivieren"); } EventQueue.invokeLater(new Runnable() { @Override public void run() { cmdRedo.setEnabled(true); } }); } else if (arg.equals(MementoInterface.DEACTIVATE) && cmdRedo.isEnabled()) { if (LOG.isDebugEnabled()) { LOG.debug("REDO-Button deaktivieren"); } EventQueue.invokeLater(new Runnable() { @Override public void run() { cmdRedo.setEnabled(false); } }); } } } /** * DOCUMENT ME! * * @param wait DOCUMENT ME! */ private void setWaiting(final boolean wait) { lblWaiting.setVisible(wait); } /** * DOCUMENT ME! */ public void refreshMeasurementsInStatus() { final Collection<Feature> selectedFeatures = mappingComp.getFeatureCollection().getSelectedFeatures(); final Collection<Feature> cidsFeatures = new ArrayList<Feature>(); for (final Feature feature : selectedFeatures) { if (feature instanceof CidsFeature || feature instanceof PureNewFeature) { cidsFeatures.add(feature); } } refreshMeasurementsInStatus(cidsFeatures); } @Override public void setEnabled(final boolean b) { this.cmdMovePolygon.setVisible(b); this.cmdRemovePolygon.setVisible(b); this.cmdAttachPolyToAlphadata.setVisible(b); this.cmdJoinPoly.setVisible(b); this.sep3.setVisible(b); this.cmdMoveHandle.setVisible(b); this.cmdAddHandle.setVisible(b); this.cmdRemoveHandle.setVisible(b); this.cmdSplitPoly.setVisible(b); this.cmdRaisePolygon.setVisible(b); this.sep4.setVisible(b); } /** * DOCUMENT ME! * * @param cf DOCUMENT ME! */ public void refreshMeasurementsInStatus(final Collection<Feature> cf) { if (CidsAppBackend.getInstance().getMode().equals(CidsAppBackend.Mode.REGEN)) { double umfang = 0.0; double area = 0.0; for (final Feature f : cf) { if ((f != null) && (f.getGeometry() != null)) { area += f.getGeometry().getArea(); umfang += f.getGeometry().getLength(); } } if ((area == 0.0 && umfang == 0.0) || cf.isEmpty()) { lblMeasurement.setText(""); } else { // vor dem runden erst zweistellig abschneiden (damit nicht aufgerundet wird) final double areadd = ((double)(Math.ceil(area * 100))) / 100; final double umfangdd = ((double)(Math.ceil(umfang * 100))) / 100; lblMeasurement.setText("Fl\u00E4che: " + StaticDecimalTools.round(areadd) + " Umfang: " + StaticDecimalTools.round(umfangdd)); } } else if (CidsAppBackend.getInstance().getMode().equals(CidsAppBackend.Mode.ESW)) { double length = 0.0; for (final Feature f : cf) { if ((f != null) && (f.getGeometry() != null)) { length += f.getGeometry().getLength(); } } // vor dem runden erst zweistellig abschneiden (damit nicht aufgerundet wird) final double lengthdd = ((double)(Math.ceil(length * 100))) / 100; lblMeasurement.setText("L\u00E4nge: " + StaticDecimalTools.round(lengthdd)); } } /** * piccolo reflection methods. * * @param notification DOCUMENT ME! */ public void coordinatesChanged(final PNotification notification) { final Object o = notification.getObject(); if (o instanceof SimpleMoveListener) { final double x = ((SimpleMoveListener) o).getXCoord(); final double y = ((SimpleMoveListener) o).getYCoord(); lblCoord.setText(MappingComponent.getCoordinateString(x, y)); // + "... " +test); final PFeature pf = ((SimpleMoveListener) o).getUnderlyingPFeature(); if ((pf != null) && (pf.getFeature() instanceof PostgisFeature) && (pf.getVisible() == true) && (pf.getParent() != null) && (pf.getParent().getVisible() == true)) { lblInfo.setText(((PostgisFeature) pf.getFeature()).getObjectName()); } else if ((pf != null) && (pf.getFeature() instanceof CidsFeature)) { final CidsFeature cf = (CidsFeature) pf.getFeature(); if (cf.getMetaClass().getName().toLowerCase().equals(VerdisMetaClassConstants.MC_FLAECHE.toLowerCase())) { final CidsBean cb = (CidsBean) cf.getMetaObject().getBean(); final int kassenzeichenNummer = (Integer) getCidsBean().getProperty(KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER); final String bezeichnung = (String) cb.getProperty(RegenFlaechenPropertyConstants.PROP__FLAECHENBEZEICHNUNG); lblInfo.setText("Kassenzeichen: " + Integer.toString(kassenzeichenNummer) + "::" + bezeichnung); } } else { lblInfo.setText(""); } } } /** * DOCUMENT ME! * * @param notification DOCUMENT ME! */ public void joinPolygons(final PNotification notification) { if (CidsAppBackend.getInstance().getMode().equals(CidsAppBackend.Mode.REGEN)) { PFeature one; PFeature two; one = mappingComp.getSelectedNode(); two = null; final Object o = notification.getObject(); if (o instanceof JoinPolygonsListener) { final JoinPolygonsListener listener = ((JoinPolygonsListener) o); final PFeature joinCandidate = listener.getFeatureRequestedForJoin(); if ((joinCandidate.getFeature() instanceof CidsFeature) || (joinCandidate.getFeature() instanceof PureNewFeature)) { if ((listener.getModifier() & Event.CTRL_MASK) != 0) { if ((one != null) && (joinCandidate != one)) { if ((one.getFeature() instanceof PureNewFeature) && (joinCandidate.getFeature() instanceof CidsFeature)) { two = one; one = joinCandidate; one.setSelected(true); two.setSelected(false); mappingComp.getFeatureCollection().select(one.getFeature()); } else { two = joinCandidate; } try { final Geometry backup = one.getFeature().getGeometry(); final Geometry newGeom = one.getFeature().getGeometry().union(two.getFeature().getGeometry()); if (newGeom.getGeometryType().equalsIgnoreCase("Multipolygon")) { JOptionPane.showMessageDialog(StaticSwingTools.getParentFrame(this), "Es k\u00F6nnen nur Polygone zusammengefasst werden, die aneinander angrenzen oder sich \u00FCberlappen.", "Zusammenfassung nicht m\u00F6glich", JOptionPane.WARNING_MESSAGE, null); return; } if (newGeom.getGeometryType().equalsIgnoreCase("Polygon") && (((Polygon) newGeom).getNumInteriorRing() > 0)) { JOptionPane.showMessageDialog(StaticSwingTools.getParentFrame(this), "Polygone k\u00F6nnen nur dann zusammengefasst werden, wenn dadurch kein Loch entsteht.", "Zusammenfassung nicht m\u00F6glich", JOptionPane.WARNING_MESSAGE, null); return; } if ((one != null) && (two != null) && (one.getFeature() instanceof CidsFeature) && (two.getFeature() instanceof CidsFeature)) { final CidsFeature cfOne = (CidsFeature) one.getFeature(); final CidsFeature cfTwo = (CidsFeature) two.getFeature(); final CidsBean cbOne = cfOne.getMetaObject().getBean(); final CidsBean cbTwo = cfTwo.getMetaObject().getBean(); final int artOne = (Integer) cbOne.getProperty(RegenFlaechenPropertyConstants.PROP__FLAECHENINFO__FLAECHENART__ID); final int artTwo = (Integer) cbTwo.getProperty(RegenFlaechenPropertyConstants.PROP__FLAECHENINFO__FLAECHENART__ID); final int gradOne = (Integer) cbOne.getProperty(RegenFlaechenPropertyConstants.PROP__FLAECHENINFO__ANSCHLUSSGRAD__ID); final int gradTwo = (Integer) cbTwo.getProperty(RegenFlaechenPropertyConstants.PROP__FLAECHENINFO__ANSCHLUSSGRAD__ID); if (artOne != artTwo || gradOne != gradTwo) { JOptionPane.showMessageDialog(StaticSwingTools.getParentFrame(this), "Fl\u00E4chen k\u00F6nnen nur zusammengefasst werden, wenn Fl\u00E4chenart und Anschlussgrad gleich sind.", "Zusammenfassung nicht m\u00F6glich", JOptionPane.WARNING_MESSAGE, null); return; } final Integer anteilOne = (Integer) cbOne.getProperty(RegenFlaechenPropertyConstants.PROP__ANTEIL); final Integer anteilTwo = (Integer) cbTwo.getProperty(RegenFlaechenPropertyConstants.PROP__ANTEIL); // Check machen ob eine Fl\u00E4che eine Teilfl\u00E4che ist if (anteilOne != null || anteilTwo != null) { JOptionPane.showMessageDialog(StaticSwingTools.getParentFrame(this), "Fl\u00E4chen die von Teileigentum betroffen sind k\u00F6nnen nicht zusammengefasst werden.", "Zusammenfassung nicht m\u00F6glich", JOptionPane.WARNING_MESSAGE, null); return; } Main.getCurrentInstance().getRegenFlaechenTabellenPanel().removeBean(cbTwo); cbOne.setProperty(RegenFlaechenPropertyConstants.PROP__FLAECHENINFO__GROESSE_GRAFIK, new Integer((int) (newGeom.getArea()))); final String bemerkungOne = (String) cbOne.getProperty(RegenFlaechenPropertyConstants.PROP__BEMERKUNG); if (bemerkungOne != null && bemerkungOne.trim().length() > 0) { cbOne.setProperty(RegenFlaechenPropertyConstants.PROP__BEMERKUNG, bemerkungOne + "\n"); } cbOne.setProperty(RegenFlaechenPropertyConstants.PROP__BEMERKUNG, getJoinBackupString(cbTwo)); final boolean sperreOne = cbOne.getProperty(RegenFlaechenPropertyConstants.PROP__SPERRE) != null && (Boolean) cbOne.getProperty(RegenFlaechenPropertyConstants.PROP__SPERRE); final boolean sperreTwo = cbTwo.getProperty(RegenFlaechenPropertyConstants.PROP__SPERRE) != null && (Boolean) cbTwo.getProperty(RegenFlaechenPropertyConstants.PROP__SPERRE); if (!sperreOne && sperreTwo) { cbOne.setProperty(RegenFlaechenPropertyConstants.PROP__SPERRE, true); cbOne.setProperty(RegenFlaechenPropertyConstants.PROP__BEMERKUNG_SPERRE, "JOIN::" + cbTwo.getProperty(RegenFlaechenPropertyConstants.PROP__BEMERKUNG_SPERRE)); } } if (one.getFeature() instanceof CidsFeature) { final CidsFeature cfOne = (CidsFeature) one.getFeature(); final CidsBean cbOne = cfOne.getMetaObject().getBean(); // Eine vorhandene Fl\u00E4che und eine neuangelegt wurden gejoint RegenFlaechenDetailsPanel.setGeometry(newGeom, cbOne); cbOne.setProperty(RegenFlaechenPropertyConstants.PROP__FLAECHENINFO__GROESSE_GRAFIK, (int) newGeom.getArea()); } if (LOG.isDebugEnabled()) { LOG.debug("newGeom ist vom Typ:" + newGeom.getGeometryType()); } one.getFeature().setGeometry(newGeom); if (!(one.getFeature().getGeometry().equals(backup))) { two.removeFromParent(); two = null; } one.visualize(); } catch (Exception e) { LOG.error("one: " + one + "\n two: " + two, e); } return; } } else { final PFeature pf = joinCandidate; if (one != null) { one.setSelected(false); } one = pf; if (one.getFeature() instanceof CidsFeature) { final CidsFeature flaecheFeature = (CidsFeature) one.getFeature(); mappingComp.getFeatureCollection().select(flaecheFeature); } else { mappingComp.getFeatureCollection().unselectAll(); } } } } } } private static String getJoinBackupString(CidsBean flaecheBean) { final String bezeichnung = (String) flaecheBean.getProperty(RegenFlaechenPropertyConstants.PROP__FLAECHENBEZEICHNUNG); final String gr_grafik = Integer.toString((Integer) flaecheBean.getProperty(RegenFlaechenPropertyConstants.PROP__FLAECHENINFO__GROESSE_GRAFIK)); final String gr_korrektur = Integer.toString((Integer) flaecheBean.getProperty(RegenFlaechenPropertyConstants.PROP__FLAECHENINFO__GROESSE_KORREKTUR)); final String erfassungsdatum = ((Date) flaecheBean.getProperty(KassenzeichenPropertyConstants.PROP__DATUM_ERFASSUNG)).toString(); final String veranlagungsdatum = (String) flaecheBean.getProperty(RegenFlaechenPropertyConstants.PROP__DATUM_VERANLAGUNG); final String sperre = Boolean.toString(flaecheBean.getProperty(RegenFlaechenPropertyConstants.PROP__SPERRE) != null && (Boolean) flaecheBean.getProperty(RegenFlaechenPropertyConstants.PROP__SPERRE)); final String bem_sperre = (String) flaecheBean.getProperty(RegenFlaechenPropertyConstants.PROP__BEMERKUNG_SPERRE); final String feb_id = (String) flaecheBean.getProperty(RegenFlaechenPropertyConstants.PROP__FEB_ID); final String bemerkung = (String) flaecheBean.getProperty(RegenFlaechenPropertyConstants.PROP__BEMERKUNG); String ret = "<JOIN "; ret += "bez=\"" + bezeichnung + "\" gr=\"" + gr_grafik + "\" grk=\"" + gr_korrektur + "\" edat=\"" + erfassungsdatum + "\" vdat=\"" + veranlagungsdatum + "\" sp=\"" + sperre + "\" spbem=\"" + bem_sperre + "\" febid=\"" + feb_id + " >\n"; ret += bemerkung; if ((bemerkung != null) && (bemerkung.trim().length() > 0) && !bemerkung.endsWith("\n")) { ret += "\n"; } ret += "</JOIN>"; return ret; } @Override public CidsBean getCidsBean() { return kassenzeichenBean; } private void refreshInMap(final boolean withZoom) { final FeatureCollection featureCollection = mappingComp.getFeatureCollection(); final boolean editable = CidsAppBackend.getInstance().isEditable(); featureCollection.removeAllFeatures(); final CidsBean cidsBean = getCidsBean(); if (cidsBean != null) { switch (CidsAppBackend.getInstance().getMode()) { case ALLGEMEIN: { final Feature add = new BeanUpdatingCidsFeature(cidsBean, KassenzeichenPropertyConstants.PROP__GEOMETRIE__GEO_FIELD); add.setEditable(editable); featureCollection.addFeature(add); } break; case REGEN: { final List<CidsBean> flaechen = (List<CidsBean>) cidsBean.getProperty(KassenzeichenPropertyConstants.PROP__FLAECHEN); for (final CidsBean flaeche : flaechen) { final Feature add = new BeanUpdatingCidsFeature(flaeche, RegenFlaechenPropertyConstants.PROP__FLAECHENINFO__GEOMETRIE__GEO_FIELD); add.setEditable(editable); featureCollection.addFeature(add); } } break; case ESW: { final List<CidsBean> fronten = (List<CidsBean>) cidsBean.getProperty(KassenzeichenPropertyConstants.PROP__FRONTEN); for (final CidsBean front : fronten) { final Feature add = new BeanUpdatingCidsFeature(front, FrontinfoPropertyConstants.PROP__GEOMETRIE + PropertyConstants.DOT + GeomPropertyConstants.PROP__GEO_FIELD); add.setEditable(editable); featureCollection.addFeature(add); } } break; } if (withZoom) { mappingComp.zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, mappingComp.isFixedMapScale()); } } } @Override public void setCidsBean(final CidsBean cidsBean) { final CidsBean oldCidsBean = kassenzeichenBean; kassenzeichenBean = cidsBean; refreshInMap(cidsBean != null && !cidsBean.equals(oldCidsBean)); } @Override public void editModeChanged() { final boolean b = CidsAppBackend.getInstance().isEditable(); final List<Feature> all = mappingComp.getFeatureCollection().getAllFeatures(); for (final Feature f : all) { f.setEditable(b); } CidsAppBackend.getInstance().getMainMap().setReadOnly(!b); } @Override public void appModeChanged() { refreshInMap(true); lblMeasurement.setText(""); } public void changeSelectedButtonAccordingToInteractionMode() { final String im = mappingComp.getInteractionMode(); if (LOG.isDebugEnabled()) { LOG.debug("changeSelectedButtonAccordingToInteractionMode: " + mappingComp.getInteractionMode(), new CurrentStackTrace()); } if (im.equals(MappingComponent.ZOOM)) { cmdZoom.setSelected(true); } if (im.equals(MappingComponent.CUSTOM_FEATUREINFO)) { cmdALB.setSelected(true); } else if (im.equals(MappingComponent.PAN)) { cmdPan.setSelected(true); } else if (im.equals(MappingComponent.SELECT)) { cmdSelect.setSelected(true); } else if (im.equals(MappingComponent.NEW_POLYGON)) { if (((CreateGeometryListener) mappingComp.getInputListener(MappingComponent.NEW_POLYGON)).getMode().equals( CreateGeometryListener.POINT)) { cmdNewPoint.setSelected(true); } else if (((CreateGeometryListener) mappingComp.getInputListener(MappingComponent.NEW_POLYGON)).getMode().equals(CreateGeometryListener.POLYGON)) { cmdNewPolygon.setSelected(true); } else { cmdSelect.setSelected(true); } } else { cmdSelect.setSelected(true); } if (mappingComp.isSnappingEnabled()) { cmdSnap.setSelected(true); } else { cmdSnap.setSelected(false); } } public void selectionChanged(final PNotification notfication) { final Object o = notfication.getObject(); if (o instanceof SelectionListener || o instanceof FeatureMoveListener || o instanceof SplitPolygonListener) { PFeature pf = null; if (o instanceof SelectionListener) { pf = ((SelectionListener) o).getSelectedPFeature(); if (((SelectionListener) o).getClickCount() > 1 && pf.getFeature() instanceof PostgisFeature) { if (LOG.isDebugEnabled()) { LOG.debug("SelectionchangedListener: clickCOunt:" + ((SelectionListener) o).getClickCount()); } final PostgisFeature postgisFeature = ((PostgisFeature) pf.getFeature()); try { if (pf.getVisible() == true && pf.getParent().getVisible() == true && postgisFeature.getFeatureType().equalsIgnoreCase("KASSENZEICHEN")) { Main.getCurrentInstance().getKzPanel().gotoKassenzeichen(postgisFeature.getGroupingKey()); } } catch (Exception e) { LOG.info("Fehler beim gotoKassenzeichen", e); } } } } } public void featureDeleteRequested(final PNotification notfication) { final Object o = notfication.getObject(); if (o instanceof DeleteFeatureListener) { final DeleteFeatureListener dfl = (DeleteFeatureListener) o; final PFeature pf = dfl.getFeatureRequestedForDeletion(); if (pf.getFeature() instanceof CidsFeature) { try { final CidsFeature cf = (CidsFeature) pf.getFeature(); final CidsBean cb = cf.getMetaObject().getBean(); cb.setProperty(RegenFlaechenPropertyConstants.PROP__FLAECHENINFO__GEOMETRIE, null); } catch (Exception ex) { LOG.error("error while removing feature", ex); } } } } public void splitPolygon(final PNotification notification) { if (CidsAppBackend.getInstance().getMode().equals(CidsAppBackend.Mode.REGEN)) { final Object o = notification.getObject(); if (o instanceof SplitPolygonListener) { final SplitPolygonListener l = (SplitPolygonListener) o; final PFeature pf = l.getFeatureClickedOn(); if (pf.getFeature() instanceof CidsFeature) { if (LOG.isDebugEnabled()) { LOG.debug("Split"); } final CidsFeature cf = (CidsFeature) pf.getFeature(); final CidsBean cb = cf.getMetaObject().getBean(); try { cb.setProperty(RegenFlaechenPropertyConstants.PROP__FLAECHENINFO__GEOMETRIE, null); } catch (Exception ex) { LOG.error("error while removing geometry", ex); } } final Feature[] f_arr = pf.split(); if (f_arr != null) { mappingComp.getFeatureCollection().removeFeature(pf.getFeature()); final boolean editable = CidsAppBackend.getInstance().isEditable(); f_arr[0].setEditable(editable); f_arr[1].setEditable(editable); mappingComp.getFeatureCollection().addFeature(f_arr[0]); mappingComp.getFeatureCollection().addFeature(f_arr[1]); cmdAttachPolyToAlphadataActionPerformed(null); } } } } private Action searchAction = new AbstractAction() { @Override public void actionPerformed(final ActionEvent e) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { if (LOG.isDebugEnabled()) { LOG.debug("searchAction"); // NOI18N } EventQueue.invokeLater(new Runnable() { @Override public void run() { mappingComp.setInteractionMode(Main.KASSENZEICHEN_SEARCH_GEOMETRY_LISTENER); if (mniSearchRectangle1.isSelected()) { mainGroup.clearSelection(); cmdSearchKassenzeichen.setSelected(true); ((ServerSearchCreateSearchGeometryListener)mappingComp.getInputListener( Main.KASSENZEICHEN_SEARCH_GEOMETRY_LISTENER)).setMode( CreateGeometryListener.RECTANGLE); } else if (mniSearchPolygon1.isSelected()) { mainGroup.clearSelection(); cmdSearchKassenzeichen.setSelected(true); ((ServerSearchCreateSearchGeometryListener)mappingComp.getInputListener( Main.KASSENZEICHEN_SEARCH_GEOMETRY_LISTENER)).setMode( CreateGeometryListener.POLYGON); } else if (mniSearchEllipse1.isSelected()) { mainGroup.clearSelection(); cmdSearchKassenzeichen.setSelected(true); ((ServerSearchCreateSearchGeometryListener)mappingComp.getInputListener( Main.KASSENZEICHEN_SEARCH_GEOMETRY_LISTENER)).setMode( CreateGeometryListener.ELLIPSE); } } }); } }); } }; private Action searchRectangleAction = new AbstractAction() { @Override public void actionPerformed(final ActionEvent e) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { if (LOG.isDebugEnabled()) { LOG.debug("searchRectangleAction"); // NOI18N } cmdSearchKassenzeichen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/kassenzeichenSearchRectangle.png"))); // NOI18N cmdSearchKassenzeichen.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/kassenzeichenSearchRectangle_selected.png"))); // NOI18N mainGroup.clearSelection(); cmdSearchKassenzeichen.setSelected(true); EventQueue.invokeLater(new Runnable() { @Override public void run() { mappingComp.setInteractionMode(Main.KASSENZEICHEN_SEARCH_GEOMETRY_LISTENER); ((ServerSearchCreateSearchGeometryListener)mappingComp.getInputListener( Main.KASSENZEICHEN_SEARCH_GEOMETRY_LISTENER)).setMode( ServerSearchCreateSearchGeometryListener.RECTANGLE); } }); } }); } }; private Action searchPolygonAction = new AbstractAction() { @Override public void actionPerformed(final ActionEvent e) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { if (LOG.isDebugEnabled()) { LOG.debug("searchPolygonAction"); // NOI18N } mainGroup.clearSelection(); cmdSearchKassenzeichen.setSelected(true); cmdSearchKassenzeichen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/kassenzeichenSearchPolygon.png"))); // NOI18N cmdSearchKassenzeichen.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/kassenzeichenSearchPolygon_selected.png"))); // NOI18N EventQueue.invokeLater(new Runnable() { @Override public void run() { mappingComp.setInteractionMode(Main.KASSENZEICHEN_SEARCH_GEOMETRY_LISTENER); ((ServerSearchCreateSearchGeometryListener)mappingComp.getInputListener( Main.KASSENZEICHEN_SEARCH_GEOMETRY_LISTENER)).setMode( ServerSearchCreateSearchGeometryListener.POLYGON); } }); } }); } }; private Action searchEllipseAction = new AbstractAction() { @Override public void actionPerformed(final ActionEvent e) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { if (LOG.isDebugEnabled()) { LOG.debug("searchEllipseAction"); // NOI18N } mainGroup.clearSelection(); cmdSearchKassenzeichen.setSelected(true); cmdSearchKassenzeichen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/kassenzeichenSearchEllipse.png"))); // NOI18N cmdSearchKassenzeichen.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/kassenzeichenSearchEllipse_selected.png"))); // NOI18N EventQueue.invokeLater(new Runnable() { @Override public void run() { mappingComp.setInteractionMode(Main.KASSENZEICHEN_SEARCH_GEOMETRY_LISTENER); ((ServerSearchCreateSearchGeometryListener)mappingComp.getInputListener( Main.KASSENZEICHEN_SEARCH_GEOMETRY_LISTENER)).setMode( ServerSearchCreateSearchGeometryListener.ELLIPSE); } }); } }); } }; }
true
true
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; pomScale = new javax.swing.JPopupMenu(); popMenSearch = new javax.swing.JPopupMenu(); mniSearchRectangle1 = new javax.swing.JRadioButtonMenuItem(); mniSearchPolygon1 = new javax.swing.JRadioButtonMenuItem(); mniSearchEllipse1 = new javax.swing.JRadioButtonMenuItem(); mainGroup = new javax.swing.ButtonGroup(); handleGroup = new javax.swing.ButtonGroup(); searchGroup = new javax.swing.ButtonGroup(); panMap = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); mappingComp = new de.cismet.cismap.commons.gui.MappingComponent(); panStatus = new javax.swing.JPanel(); cmdAdd = new javax.swing.JButton(); lblInfo = new javax.swing.JLabel(); lblCoord = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); lblWaiting = new javax.swing.JLabel(); lblMeasurement = new javax.swing.JLabel(); lblScale = new javax.swing.JLabel(); jSeparator2 = new javax.swing.JSeparator(); tobVerdis = new javax.swing.JToolBar(); cmdFullPoly = new javax.swing.JButton(); cmdFullPoly1 = new javax.swing.JButton(); cmdBack = new JHistoryButton(); cmdForward = new JHistoryButton(); jSeparator5 = new javax.swing.JSeparator(); cmdWmsBackground = new javax.swing.JToggleButton(); cmdForeground = new javax.swing.JButton(); cmdSnap = new javax.swing.JToggleButton(); sep2 = new javax.swing.JSeparator(); cmdZoom = new javax.swing.JToggleButton(); cmdPan = new javax.swing.JToggleButton(); cmdSelect = new javax.swing.JToggleButton(); cmdALB = new javax.swing.JToggleButton(); cmdMovePolygon = new javax.swing.JToggleButton(); cmdNewPolygon = new javax.swing.JToggleButton(); cmdNewLinestring = new javax.swing.JToggleButton(); cmdNewPoint = new javax.swing.JToggleButton(); cmdOrthogonalRectangle = new javax.swing.JToggleButton(); cmdSearchFlurstueck = new javax.swing.JToggleButton(); cmdSearchKassenzeichen = new CidsBeanDropJPopupMenuButton(Main.KASSENZEICHEN_SEARCH_GEOMETRY_LISTENER, mappingComp, null); cmdRaisePolygon = new javax.swing.JToggleButton(); cmdRemovePolygon = new javax.swing.JToggleButton(); cmdAttachPolyToAlphadata = new javax.swing.JToggleButton(); cmdJoinPoly = new javax.swing.JToggleButton(); cmdSplitPoly = new javax.swing.JToggleButton(); sep3 = new javax.swing.JSeparator(); cmdMoveHandle = new javax.swing.JToggleButton(); cmdAddHandle = new javax.swing.JToggleButton(); cmdRemoveHandle = new javax.swing.JToggleButton(); cmdRotatePolygon = new javax.swing.JToggleButton(); sep4 = new javax.swing.JSeparator(); cmdUndo = new javax.swing.JButton(); cmdRedo = new javax.swing.JButton(); popMenSearch.addPopupMenuListener(new javax.swing.event.PopupMenuListener() { public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) { popMenSearchPopupMenuWillBecomeVisible(evt); } }); mniSearchRectangle1.setAction(searchRectangleAction); searchGroup.add(mniSearchRectangle1); mniSearchRectangle1.setSelected(true); mniSearchRectangle1.setText("Rechteck"); mniSearchRectangle1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/rectangleSearch.png"))); // NOI18N popMenSearch.add(mniSearchRectangle1); mniSearchPolygon1.setAction(searchPolygonAction); searchGroup.add(mniSearchPolygon1); mniSearchPolygon1.setText("Polygon"); mniSearchPolygon1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/polygonSearch.png"))); // NOI18N popMenSearch.add(mniSearchPolygon1); mniSearchEllipse1.setAction(searchEllipseAction); searchGroup.add(mniSearchEllipse1); mniSearchEllipse1.setText("Ellipse / Kreis"); mniSearchEllipse1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/ellipseSearch.png"))); // NOI18N popMenSearch.add(mniSearchEllipse1); setLayout(new java.awt.BorderLayout()); panMap.setLayout(new java.awt.BorderLayout()); jPanel2.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(2, 2, 2, 2), javax.swing.BorderFactory.createEtchedBorder()), javax.swing.BorderFactory.createEmptyBorder(4, 4, 1, 4))); jPanel2.setLayout(new java.awt.BorderLayout()); mappingComp.setBorder(javax.swing.BorderFactory.createEtchedBorder()); mappingComp.setInternalLayerWidgetAvailable(true); jPanel2.add(mappingComp, java.awt.BorderLayout.CENTER); panStatus.setBorder(javax.swing.BorderFactory.createEmptyBorder(3, 1, 1, 1)); panStatus.setLayout(new java.awt.GridBagLayout()); cmdAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/statusbar/layersman.png"))); // NOI18N cmdAdd.setBorderPainted(false); cmdAdd.setFocusPainted(false); cmdAdd.setMinimumSize(new java.awt.Dimension(25, 25)); cmdAdd.setPreferredSize(new java.awt.Dimension(25, 25)); cmdAdd.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/statusbar/layersman.png"))); // NOI18N cmdAdd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdAddActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 7; gridBagConstraints.gridy = 0; panStatus.add(cmdAdd, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; panStatus.add(lblInfo, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; panStatus.add(lblCoord, gridBagConstraints); jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); panStatus.add(jSeparator1, gridBagConstraints); lblWaiting.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/exec.png"))); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 6; gridBagConstraints.gridy = 0; panStatus.add(lblWaiting, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 5; gridBagConstraints.gridy = 0; panStatus.add(lblMeasurement, gridBagConstraints); lblScale.setText("1:???"); lblScale.setComponentPopupMenu(pomScale); lblScale.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { lblScaleMousePressed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; panStatus.add(lblScale, gridBagConstraints); jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); panStatus.add(jSeparator2, gridBagConstraints); jPanel2.add(panStatus, java.awt.BorderLayout.SOUTH); panMap.add(jPanel2, java.awt.BorderLayout.CENTER); tobVerdis.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); tobVerdis.setFloatable(false); cmdFullPoly.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/fullPoly.png"))); // NOI18N cmdFullPoly.setToolTipText("Zeige alle Flächen"); cmdFullPoly.setBorderPainted(false); cmdFullPoly.setContentAreaFilled(false); cmdFullPoly.setFocusPainted(false); cmdFullPoly.setFocusable(false); cmdFullPoly.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdFullPolyActionPerformed(evt); } }); tobVerdis.add(cmdFullPoly); cmdFullPoly1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/fullSelPoly.png"))); // NOI18N cmdFullPoly1.setToolTipText("Zoom zur ausgewählten Fläche"); cmdFullPoly1.setBorderPainted(false); cmdFullPoly1.setContentAreaFilled(false); cmdFullPoly1.setFocusPainted(false); cmdFullPoly1.setFocusable(false); cmdFullPoly1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdFullPoly1ActionPerformed(evt); } }); tobVerdis.add(cmdFullPoly1); cmdBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/back.png"))); // NOI18N cmdBack.setToolTipText("Zurück"); cmdBack.setBorderPainted(false); cmdBack.setContentAreaFilled(false); cmdBack.setFocusPainted(false); cmdBack.setFocusable(false); tobVerdis.add(cmdBack); cmdForward.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/fwd.png"))); // NOI18N cmdForward.setToolTipText("Vor"); cmdForward.setBorderPainted(false); cmdForward.setContentAreaFilled(false); cmdForward.setFocusPainted(false); cmdForward.setFocusable(false); tobVerdis.add(cmdForward); jSeparator5.setOrientation(javax.swing.SwingConstants.VERTICAL); jSeparator5.setMaximumSize(new java.awt.Dimension(2, 32767)); tobVerdis.add(jSeparator5); cmdWmsBackground.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/map.png"))); // NOI18N cmdWmsBackground.setToolTipText("Hintergrund an/aus"); cmdWmsBackground.setBorderPainted(false); cmdWmsBackground.setContentAreaFilled(false); cmdWmsBackground.setFocusPainted(false); cmdWmsBackground.setFocusable(false); cmdWmsBackground.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/map_on.png"))); // NOI18N cmdWmsBackground.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdWmsBackgroundActionPerformed(evt); } }); tobVerdis.add(cmdWmsBackground); cmdForeground.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/foreground.png"))); // NOI18N cmdForeground.setToolTipText("Vordergrund an/aus"); cmdForeground.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 3, 1, 3)); cmdForeground.setBorderPainted(false); cmdForeground.setContentAreaFilled(false); cmdForeground.setFocusPainted(false); cmdForeground.setFocusable(false); cmdForeground.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdForeground.setSelected(true); cmdForeground.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/foreground_on.png"))); // NOI18N cmdForeground.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdForeground.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdForegroundActionPerformed(evt); } }); tobVerdis.add(cmdForeground); cmdSnap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/snap.png"))); // NOI18N cmdSnap.setSelected(true); cmdSnap.setToolTipText("Snapping an/aus"); cmdSnap.setBorderPainted(false); cmdSnap.setContentAreaFilled(false); cmdSnap.setFocusPainted(false); cmdSnap.setFocusable(false); cmdSnap.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/snap_selected.png"))); // NOI18N cmdSnap.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdSnapActionPerformed(evt); } }); tobVerdis.add(cmdSnap); sep2.setOrientation(javax.swing.SwingConstants.VERTICAL); sep2.setMaximumSize(new java.awt.Dimension(2, 32767)); tobVerdis.add(sep2); mainGroup.add(cmdZoom); cmdZoom.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/zoom.png"))); // NOI18N cmdZoom.setToolTipText("Zoomen"); cmdZoom.setBorderPainted(false); cmdZoom.setContentAreaFilled(false); cmdZoom.setFocusPainted(false); cmdZoom.setFocusable(false); cmdZoom.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/zoom_selected.png"))); // NOI18N cmdZoom.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdZoomActionPerformed(evt); } }); tobVerdis.add(cmdZoom); mainGroup.add(cmdPan); cmdPan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/move2.png"))); // NOI18N cmdPan.setToolTipText("Verschieben"); cmdPan.setBorderPainted(false); cmdPan.setContentAreaFilled(false); cmdPan.setFocusPainted(false); cmdPan.setFocusable(false); cmdPan.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/move2_selected.png"))); // NOI18N cmdPan.setVerifyInputWhenFocusTarget(false); cmdPan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdPanActionPerformed(evt); } }); tobVerdis.add(cmdPan); mainGroup.add(cmdSelect); cmdSelect.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/select.png"))); // NOI18N cmdSelect.setSelected(true); cmdSelect.setToolTipText("Auswählen"); cmdSelect.setBorderPainted(false); cmdSelect.setContentAreaFilled(false); cmdSelect.setFocusPainted(false); cmdSelect.setFocusable(false); cmdSelect.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/select_selected.png"))); // NOI18N cmdSelect.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdSelectActionPerformed(evt); } }); tobVerdis.add(cmdSelect); mainGroup.add(cmdALB); cmdALB.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/alb.png"))); // NOI18N cmdALB.setToolTipText("ALB"); cmdALB.setBorderPainted(false); cmdALB.setContentAreaFilled(false); cmdALB.setFocusPainted(false); cmdALB.setFocusable(false); cmdALB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdALB.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/alb_selected.png"))); // NOI18N cmdALB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdALB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdALBActionPerformed(evt); } }); tobVerdis.add(cmdALB); mainGroup.add(cmdMovePolygon); cmdMovePolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/movePoly.png"))); // NOI18N cmdMovePolygon.setToolTipText("Polygon verschieben"); cmdMovePolygon.setBorderPainted(false); cmdMovePolygon.setContentAreaFilled(false); cmdMovePolygon.setFocusPainted(false); cmdMovePolygon.setFocusable(false); cmdMovePolygon.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/movePoly_selected.png"))); // NOI18N cmdMovePolygon.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdMovePolygonActionPerformed(evt); } }); tobVerdis.add(cmdMovePolygon); mainGroup.add(cmdNewPolygon); cmdNewPolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/newPoly.png"))); // NOI18N cmdNewPolygon.setToolTipText("neues Polygon"); cmdNewPolygon.setBorderPainted(false); cmdNewPolygon.setContentAreaFilled(false); cmdNewPolygon.setFocusPainted(false); cmdNewPolygon.setFocusable(false); cmdNewPolygon.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/newPoly_selected.png"))); // NOI18N cmdNewPolygon.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdNewPolygonActionPerformed(evt); } }); tobVerdis.add(cmdNewPolygon); mainGroup.add(cmdNewLinestring); cmdNewLinestring.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/newLine.png"))); // NOI18N cmdNewLinestring.setToolTipText("neue Linie"); cmdNewLinestring.setBorderPainted(false); cmdNewLinestring.setContentAreaFilled(false); cmdNewLinestring.setFocusPainted(false); cmdNewLinestring.setFocusable(false); cmdNewLinestring.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdNewLinestring.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/newLine_selected.png"))); // NOI18N cmdNewLinestring.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdNewLinestring.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdNewLinestringActionPerformed(evt); } }); tobVerdis.add(cmdNewLinestring); mainGroup.add(cmdNewPoint); cmdNewPoint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/newPoint.png"))); // NOI18N cmdNewPoint.setToolTipText("neuer Punkt"); cmdNewPoint.setBorderPainted(false); cmdNewPoint.setContentAreaFilled(false); cmdNewPoint.setFocusPainted(false); cmdNewPoint.setFocusable(false); cmdNewPoint.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/newPoint_selected.png"))); // NOI18N cmdNewPoint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdNewPointActionPerformed(evt); } }); tobVerdis.add(cmdNewPoint); mainGroup.add(cmdOrthogonalRectangle); cmdOrthogonalRectangle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/rechtwDreieck.png"))); // NOI18N cmdOrthogonalRectangle.setToolTipText("Rechteckige Fläche"); cmdOrthogonalRectangle.setBorderPainted(false); cmdOrthogonalRectangle.setContentAreaFilled(false); cmdOrthogonalRectangle.setFocusPainted(false); cmdOrthogonalRectangle.setFocusable(false); cmdOrthogonalRectangle.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdOrthogonalRectangle.setMaximumSize(new java.awt.Dimension(28, 20)); cmdOrthogonalRectangle.setPreferredSize(new java.awt.Dimension(28, 20)); cmdOrthogonalRectangle.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/rechtwDreieck_selected.png"))); // NOI18N cmdOrthogonalRectangle.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdOrthogonalRectangle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdOrthogonalRectangleActionPerformed(evt); } }); tobVerdis.add(cmdOrthogonalRectangle); mainGroup.add(cmdSearchFlurstueck); cmdSearchFlurstueck.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/alk.png"))); // NOI18N cmdSearchFlurstueck.setToolTipText("Alkis Renderer"); cmdSearchFlurstueck.setBorderPainted(false); cmdSearchFlurstueck.setContentAreaFilled(false); cmdSearchFlurstueck.setFocusPainted(false); cmdSearchFlurstueck.setFocusable(false); cmdSearchFlurstueck.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdSearchFlurstueck.setMaximumSize(new java.awt.Dimension(28, 20)); cmdSearchFlurstueck.setPreferredSize(new java.awt.Dimension(28, 20)); cmdSearchFlurstueck.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/alk_selected.png"))); // NOI18N cmdSearchFlurstueck.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdSearchFlurstueck.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdSearchFlurstueckActionPerformed(evt); } }); tobVerdis.add(cmdSearchFlurstueck); cmdSearchKassenzeichen.setAction(searchAction); cmdSearchKassenzeichen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/kassenzeichenSearchRectangle.png"))); // NOI18N cmdSearchKassenzeichen.setToolTipText("Kassenzeichen-Suche"); cmdSearchKassenzeichen.setBorderPainted(false); mainGroup.add(cmdSearchKassenzeichen); cmdSearchKassenzeichen.setContentAreaFilled(false); cmdSearchKassenzeichen.setFocusPainted(false); cmdSearchKassenzeichen.setFocusable(false); cmdSearchKassenzeichen.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdSearchKassenzeichen.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/kassenzeichenSearchRectangle_selected.png"))); // NOI18N cmdSearchKassenzeichen.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdSearchKassenzeichen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdSearchKassenzeichenActionPerformed(evt); } }); if (StaticDebuggingTools.checkHomeForFile("cismetVerdisTest")) { tobVerdis.add(cmdSearchKassenzeichen); } mainGroup.add(cmdRaisePolygon); cmdRaisePolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/raisePoly.png"))); // NOI18N cmdRaisePolygon.setToolTipText("Polygon hochholen"); cmdRaisePolygon.setBorderPainted(false); cmdRaisePolygon.setContentAreaFilled(false); cmdRaisePolygon.setFocusPainted(false); cmdRaisePolygon.setFocusable(false); cmdRaisePolygon.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/raisePoly_selected.png"))); // NOI18N cmdRaisePolygon.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdRaisePolygonActionPerformed(evt); } }); tobVerdis.add(cmdRaisePolygon); mainGroup.add(cmdRemovePolygon); cmdRemovePolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/removePoly.png"))); // NOI18N cmdRemovePolygon.setToolTipText("Polygon entfernen"); cmdRemovePolygon.setBorderPainted(false); cmdRemovePolygon.setContentAreaFilled(false); cmdRemovePolygon.setFocusPainted(false); cmdRemovePolygon.setFocusable(false); cmdRemovePolygon.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/removePoly_selected.png"))); // NOI18N cmdRemovePolygon.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdRemovePolygonActionPerformed(evt); } }); tobVerdis.add(cmdRemovePolygon); mainGroup.add(cmdAttachPolyToAlphadata); cmdAttachPolyToAlphadata.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/polygonAttachment.png"))); // NOI18N cmdAttachPolyToAlphadata.setToolTipText("Polygon zuordnen"); cmdAttachPolyToAlphadata.setBorderPainted(false); cmdAttachPolyToAlphadata.setContentAreaFilled(false); cmdAttachPolyToAlphadata.setFocusPainted(false); cmdAttachPolyToAlphadata.setFocusable(false); cmdAttachPolyToAlphadata.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/polygonAttachment_selected.png"))); // NOI18N cmdAttachPolyToAlphadata.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdAttachPolyToAlphadataActionPerformed(evt); } }); tobVerdis.add(cmdAttachPolyToAlphadata); mainGroup.add(cmdJoinPoly); cmdJoinPoly.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/joinPoly.png"))); // NOI18N cmdJoinPoly.setToolTipText("Polygone zusammenfassen"); cmdJoinPoly.setBorderPainted(false); cmdJoinPoly.setContentAreaFilled(false); cmdJoinPoly.setFocusPainted(false); cmdJoinPoly.setFocusable(false); cmdJoinPoly.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/joinPoly_selected.png"))); // NOI18N cmdJoinPoly.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdJoinPolyActionPerformed(evt); } }); tobVerdis.add(cmdJoinPoly); mainGroup.add(cmdSplitPoly); cmdSplitPoly.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/splitPoly.png"))); // NOI18N cmdSplitPoly.setToolTipText("Polygon splitten"); cmdSplitPoly.setBorderPainted(false); cmdSplitPoly.setContentAreaFilled(false); cmdSplitPoly.setFocusPainted(false); cmdSplitPoly.setFocusable(false); cmdSplitPoly.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/splitPoly_selected.png"))); // NOI18N cmdSplitPoly.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdSplitPolyActionPerformed(evt); } }); tobVerdis.add(cmdSplitPoly); sep3.setOrientation(javax.swing.SwingConstants.VERTICAL); sep3.setMaximumSize(new java.awt.Dimension(2, 32767)); tobVerdis.add(sep3); handleGroup.add(cmdMoveHandle); cmdMoveHandle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/moveHandle.png"))); // NOI18N cmdMoveHandle.setSelected(true); cmdMoveHandle.setToolTipText("Handle verschieben"); cmdMoveHandle.setBorderPainted(false); cmdMoveHandle.setContentAreaFilled(false); cmdMoveHandle.setFocusPainted(false); cmdMoveHandle.setFocusable(false); cmdMoveHandle.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/moveHandle_selected.png"))); // NOI18N cmdMoveHandle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdMoveHandleActionPerformed(evt); } }); tobVerdis.add(cmdMoveHandle); handleGroup.add(cmdAddHandle); cmdAddHandle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/addHandle.png"))); // NOI18N cmdAddHandle.setToolTipText("Handle hinzufügen"); cmdAddHandle.setBorderPainted(false); cmdAddHandle.setContentAreaFilled(false); cmdAddHandle.setFocusPainted(false); cmdAddHandle.setFocusable(false); cmdAddHandle.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/addHandle_selected.png"))); // NOI18N cmdAddHandle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdAddHandleActionPerformed(evt); } }); tobVerdis.add(cmdAddHandle); handleGroup.add(cmdRemoveHandle); cmdRemoveHandle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/removeHandle.png"))); // NOI18N cmdRemoveHandle.setToolTipText("Handle entfernen"); cmdRemoveHandle.setBorderPainted(false); cmdRemoveHandle.setContentAreaFilled(false); cmdRemoveHandle.setFocusPainted(false); cmdRemoveHandle.setFocusable(false); cmdRemoveHandle.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/removeHandle_selected.png"))); // NOI18N cmdRemoveHandle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdRemoveHandleActionPerformed(evt); } }); tobVerdis.add(cmdRemoveHandle); handleGroup.add(cmdRotatePolygon); cmdRotatePolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/rotate16.png"))); // NOI18N cmdRotatePolygon.setToolTipText("Rotiere Polygon"); cmdRotatePolygon.setBorderPainted(false); cmdRotatePolygon.setContentAreaFilled(false); cmdRotatePolygon.setFocusPainted(false); cmdRotatePolygon.setFocusable(false); cmdRotatePolygon.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/rotate16_selected.png"))); // NOI18N cmdRotatePolygon.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdRotatePolygonActionPerformed(evt); } }); tobVerdis.add(cmdRotatePolygon); sep4.setOrientation(javax.swing.SwingConstants.VERTICAL); sep4.setMaximumSize(new java.awt.Dimension(2, 32767)); tobVerdis.add(sep4); cmdUndo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/undo.png"))); // NOI18N cmdUndo.setToolTipText("Undo"); cmdUndo.setBorderPainted(false); cmdUndo.setContentAreaFilled(false); cmdUndo.setEnabled(false); cmdUndo.setFocusPainted(false); cmdUndo.setFocusable(false); cmdUndo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdUndo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdUndoActionPerformed(evt); } }); tobVerdis.add(cmdUndo); cmdRedo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/redo.png"))); // NOI18N cmdRedo.setBorderPainted(false); cmdRedo.setContentAreaFilled(false); cmdRedo.setEnabled(false); cmdRedo.setFocusPainted(false); cmdRedo.setFocusable(false); cmdRedo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdRedo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdRedo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdRedoActionPerformed(evt); } }); tobVerdis.add(cmdRedo); panMap.add(tobVerdis, java.awt.BorderLayout.NORTH); add(panMap, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; pomScale = new javax.swing.JPopupMenu(); popMenSearch = new javax.swing.JPopupMenu(); mniSearchRectangle1 = new javax.swing.JRadioButtonMenuItem(); mniSearchPolygon1 = new javax.swing.JRadioButtonMenuItem(); mniSearchEllipse1 = new javax.swing.JRadioButtonMenuItem(); mainGroup = new javax.swing.ButtonGroup(); handleGroup = new javax.swing.ButtonGroup(); searchGroup = new javax.swing.ButtonGroup(); panMap = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); mappingComp = new de.cismet.cismap.commons.gui.MappingComponent(); panStatus = new javax.swing.JPanel(); cmdAdd = new javax.swing.JButton(); lblInfo = new javax.swing.JLabel(); lblCoord = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); lblWaiting = new javax.swing.JLabel(); lblMeasurement = new javax.swing.JLabel(); lblScale = new javax.swing.JLabel(); jSeparator2 = new javax.swing.JSeparator(); tobVerdis = new javax.swing.JToolBar(); cmdFullPoly = new javax.swing.JButton(); cmdFullPoly1 = new javax.swing.JButton(); cmdBack = new JHistoryButton(); cmdForward = new JHistoryButton(); jSeparator5 = new javax.swing.JSeparator(); cmdWmsBackground = new javax.swing.JToggleButton(); cmdForeground = new javax.swing.JButton(); cmdSnap = new javax.swing.JToggleButton(); sep2 = new javax.swing.JSeparator(); cmdZoom = new javax.swing.JToggleButton(); cmdPan = new javax.swing.JToggleButton(); cmdSelect = new javax.swing.JToggleButton(); cmdALB = new javax.swing.JToggleButton(); cmdMovePolygon = new javax.swing.JToggleButton(); cmdNewPolygon = new javax.swing.JToggleButton(); cmdNewLinestring = new javax.swing.JToggleButton(); cmdNewPoint = new javax.swing.JToggleButton(); cmdOrthogonalRectangle = new javax.swing.JToggleButton(); cmdSearchFlurstueck = new javax.swing.JToggleButton(); cmdSearchKassenzeichen = new CidsBeanDropJPopupMenuButton(Main.KASSENZEICHEN_SEARCH_GEOMETRY_LISTENER, mappingComp, null); cmdRaisePolygon = new javax.swing.JToggleButton(); cmdRemovePolygon = new javax.swing.JToggleButton(); cmdAttachPolyToAlphadata = new javax.swing.JToggleButton(); cmdJoinPoly = new javax.swing.JToggleButton(); cmdSplitPoly = new javax.swing.JToggleButton(); sep3 = new javax.swing.JSeparator(); cmdMoveHandle = new javax.swing.JToggleButton(); cmdAddHandle = new javax.swing.JToggleButton(); cmdRemoveHandle = new javax.swing.JToggleButton(); cmdRotatePolygon = new javax.swing.JToggleButton(); sep4 = new javax.swing.JSeparator(); cmdUndo = new javax.swing.JButton(); cmdRedo = new javax.swing.JButton(); popMenSearch.addPopupMenuListener(new javax.swing.event.PopupMenuListener() { public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) { popMenSearchPopupMenuWillBecomeVisible(evt); } }); mniSearchRectangle1.setAction(searchRectangleAction); searchGroup.add(mniSearchRectangle1); mniSearchRectangle1.setSelected(true); mniSearchRectangle1.setText("Rechteck"); mniSearchRectangle1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/rectangleSearch.png"))); // NOI18N popMenSearch.add(mniSearchRectangle1); mniSearchPolygon1.setAction(searchPolygonAction); searchGroup.add(mniSearchPolygon1); mniSearchPolygon1.setText("Polygon"); mniSearchPolygon1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/polygonSearch.png"))); // NOI18N popMenSearch.add(mniSearchPolygon1); mniSearchEllipse1.setAction(searchEllipseAction); searchGroup.add(mniSearchEllipse1); mniSearchEllipse1.setText("Ellipse / Kreis"); mniSearchEllipse1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/ellipseSearch.png"))); // NOI18N popMenSearch.add(mniSearchEllipse1); setLayout(new java.awt.BorderLayout()); panMap.setLayout(new java.awt.BorderLayout()); jPanel2.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(2, 2, 2, 2), javax.swing.BorderFactory.createEtchedBorder()), javax.swing.BorderFactory.createEmptyBorder(4, 4, 1, 4))); jPanel2.setLayout(new java.awt.BorderLayout()); mappingComp.setBorder(javax.swing.BorderFactory.createEtchedBorder()); mappingComp.setInternalLayerWidgetAvailable(true); jPanel2.add(mappingComp, java.awt.BorderLayout.CENTER); panStatus.setBorder(javax.swing.BorderFactory.createEmptyBorder(3, 1, 1, 1)); panStatus.setLayout(new java.awt.GridBagLayout()); cmdAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/statusbar/layersman.png"))); // NOI18N cmdAdd.setBorderPainted(false); cmdAdd.setFocusPainted(false); cmdAdd.setMinimumSize(new java.awt.Dimension(25, 25)); cmdAdd.setPreferredSize(new java.awt.Dimension(25, 25)); cmdAdd.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/statusbar/layersman.png"))); // NOI18N cmdAdd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdAddActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 7; gridBagConstraints.gridy = 0; panStatus.add(cmdAdd, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; panStatus.add(lblInfo, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; panStatus.add(lblCoord, gridBagConstraints); jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); panStatus.add(jSeparator1, gridBagConstraints); lblWaiting.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/exec.png"))); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 6; gridBagConstraints.gridy = 0; panStatus.add(lblWaiting, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 5; gridBagConstraints.gridy = 0; panStatus.add(lblMeasurement, gridBagConstraints); lblScale.setText("1:???"); lblScale.setComponentPopupMenu(pomScale); lblScale.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { lblScaleMousePressed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; panStatus.add(lblScale, gridBagConstraints); jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); panStatus.add(jSeparator2, gridBagConstraints); jPanel2.add(panStatus, java.awt.BorderLayout.SOUTH); panMap.add(jPanel2, java.awt.BorderLayout.CENTER); tobVerdis.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); tobVerdis.setFloatable(false); cmdFullPoly.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/fullPoly.png"))); // NOI18N cmdFullPoly.setToolTipText("Zeige alle Flächen"); cmdFullPoly.setBorderPainted(false); cmdFullPoly.setContentAreaFilled(false); cmdFullPoly.setFocusPainted(false); cmdFullPoly.setFocusable(false); cmdFullPoly.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdFullPolyActionPerformed(evt); } }); tobVerdis.add(cmdFullPoly); cmdFullPoly1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/fullSelPoly.png"))); // NOI18N cmdFullPoly1.setToolTipText("Zoom zur ausgewählten Fläche"); cmdFullPoly1.setBorderPainted(false); cmdFullPoly1.setContentAreaFilled(false); cmdFullPoly1.setFocusPainted(false); cmdFullPoly1.setFocusable(false); cmdFullPoly1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdFullPoly1ActionPerformed(evt); } }); tobVerdis.add(cmdFullPoly1); cmdBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/back.png"))); // NOI18N cmdBack.setToolTipText("Zurück"); cmdBack.setBorderPainted(false); cmdBack.setContentAreaFilled(false); cmdBack.setFocusPainted(false); cmdBack.setFocusable(false); tobVerdis.add(cmdBack); cmdForward.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/fwd.png"))); // NOI18N cmdForward.setToolTipText("Vor"); cmdForward.setBorderPainted(false); cmdForward.setContentAreaFilled(false); cmdForward.setFocusPainted(false); cmdForward.setFocusable(false); tobVerdis.add(cmdForward); jSeparator5.setOrientation(javax.swing.SwingConstants.VERTICAL); jSeparator5.setMaximumSize(new java.awt.Dimension(2, 32767)); tobVerdis.add(jSeparator5); cmdWmsBackground.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/map.png"))); // NOI18N cmdWmsBackground.setToolTipText("Hintergrund an/aus"); cmdWmsBackground.setBorderPainted(false); cmdWmsBackground.setContentAreaFilled(false); cmdWmsBackground.setFocusPainted(false); cmdWmsBackground.setFocusable(false); cmdWmsBackground.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/map_on.png"))); // NOI18N cmdWmsBackground.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdWmsBackgroundActionPerformed(evt); } }); tobVerdis.add(cmdWmsBackground); cmdForeground.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/foreground.png"))); // NOI18N cmdForeground.setToolTipText("Vordergrund an/aus"); cmdForeground.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 3, 1, 3)); cmdForeground.setBorderPainted(false); cmdForeground.setContentAreaFilled(false); cmdForeground.setFocusPainted(false); cmdForeground.setFocusable(false); cmdForeground.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdForeground.setSelected(true); cmdForeground.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/foreground_on.png"))); // NOI18N cmdForeground.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdForeground.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdForegroundActionPerformed(evt); } }); tobVerdis.add(cmdForeground); cmdSnap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/snap.png"))); // NOI18N cmdSnap.setSelected(true); cmdSnap.setToolTipText("Snapping an/aus"); cmdSnap.setBorderPainted(false); cmdSnap.setContentAreaFilled(false); cmdSnap.setFocusPainted(false); cmdSnap.setFocusable(false); cmdSnap.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/snap_selected.png"))); // NOI18N cmdSnap.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdSnapActionPerformed(evt); } }); tobVerdis.add(cmdSnap); sep2.setOrientation(javax.swing.SwingConstants.VERTICAL); sep2.setMaximumSize(new java.awt.Dimension(2, 32767)); tobVerdis.add(sep2); mainGroup.add(cmdZoom); cmdZoom.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/zoom.png"))); // NOI18N cmdZoom.setToolTipText("Zoomen"); cmdZoom.setBorderPainted(false); cmdZoom.setContentAreaFilled(false); cmdZoom.setFocusPainted(false); cmdZoom.setFocusable(false); cmdZoom.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/zoom_selected.png"))); // NOI18N cmdZoom.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdZoomActionPerformed(evt); } }); tobVerdis.add(cmdZoom); mainGroup.add(cmdPan); cmdPan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/move2.png"))); // NOI18N cmdPan.setToolTipText("Verschieben"); cmdPan.setBorderPainted(false); cmdPan.setContentAreaFilled(false); cmdPan.setFocusPainted(false); cmdPan.setFocusable(false); cmdPan.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/move2_selected.png"))); // NOI18N cmdPan.setVerifyInputWhenFocusTarget(false); cmdPan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdPanActionPerformed(evt); } }); tobVerdis.add(cmdPan); mainGroup.add(cmdSelect); cmdSelect.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/select.png"))); // NOI18N cmdSelect.setSelected(true); cmdSelect.setToolTipText("Auswählen"); cmdSelect.setBorderPainted(false); cmdSelect.setContentAreaFilled(false); cmdSelect.setFocusPainted(false); cmdSelect.setFocusable(false); cmdSelect.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/select_selected.png"))); // NOI18N cmdSelect.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdSelectActionPerformed(evt); } }); tobVerdis.add(cmdSelect); mainGroup.add(cmdALB); cmdALB.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/alb.png"))); // NOI18N cmdALB.setToolTipText("ALB"); cmdALB.setBorderPainted(false); cmdALB.setContentAreaFilled(false); cmdALB.setFocusPainted(false); cmdALB.setFocusable(false); cmdALB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdALB.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/alb_selected.png"))); // NOI18N cmdALB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdALB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdALBActionPerformed(evt); } }); tobVerdis.add(cmdALB); mainGroup.add(cmdMovePolygon); cmdMovePolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/movePoly.png"))); // NOI18N cmdMovePolygon.setToolTipText("Polygon verschieben"); cmdMovePolygon.setBorderPainted(false); cmdMovePolygon.setContentAreaFilled(false); cmdMovePolygon.setFocusPainted(false); cmdMovePolygon.setFocusable(false); cmdMovePolygon.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/movePoly_selected.png"))); // NOI18N cmdMovePolygon.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdMovePolygonActionPerformed(evt); } }); tobVerdis.add(cmdMovePolygon); mainGroup.add(cmdNewPolygon); cmdNewPolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/newPoly.png"))); // NOI18N cmdNewPolygon.setToolTipText("neues Polygon"); cmdNewPolygon.setBorderPainted(false); cmdNewPolygon.setContentAreaFilled(false); cmdNewPolygon.setFocusPainted(false); cmdNewPolygon.setFocusable(false); cmdNewPolygon.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/newPoly_selected.png"))); // NOI18N cmdNewPolygon.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdNewPolygonActionPerformed(evt); } }); tobVerdis.add(cmdNewPolygon); mainGroup.add(cmdNewLinestring); cmdNewLinestring.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/newLine.png"))); // NOI18N cmdNewLinestring.setToolTipText("neue Linie"); cmdNewLinestring.setBorderPainted(false); cmdNewLinestring.setContentAreaFilled(false); cmdNewLinestring.setFocusPainted(false); cmdNewLinestring.setFocusable(false); cmdNewLinestring.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdNewLinestring.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/newLine_selected.png"))); // NOI18N cmdNewLinestring.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdNewLinestring.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdNewLinestringActionPerformed(evt); } }); tobVerdis.add(cmdNewLinestring); mainGroup.add(cmdNewPoint); cmdNewPoint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/newPoint.png"))); // NOI18N cmdNewPoint.setToolTipText("neuer Punkt"); cmdNewPoint.setBorderPainted(false); cmdNewPoint.setContentAreaFilled(false); cmdNewPoint.setFocusPainted(false); cmdNewPoint.setFocusable(false); cmdNewPoint.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/newPoint_selected.png"))); // NOI18N cmdNewPoint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdNewPointActionPerformed(evt); } }); tobVerdis.add(cmdNewPoint); mainGroup.add(cmdOrthogonalRectangle); cmdOrthogonalRectangle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/rechtwDreieck.png"))); // NOI18N cmdOrthogonalRectangle.setToolTipText("Rechteckige Fläche"); cmdOrthogonalRectangle.setBorderPainted(false); cmdOrthogonalRectangle.setContentAreaFilled(false); cmdOrthogonalRectangle.setFocusPainted(false); cmdOrthogonalRectangle.setFocusable(false); cmdOrthogonalRectangle.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdOrthogonalRectangle.setMaximumSize(new java.awt.Dimension(28, 20)); cmdOrthogonalRectangle.setPreferredSize(new java.awt.Dimension(28, 20)); cmdOrthogonalRectangle.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/rechtwDreieck_selected.png"))); // NOI18N cmdOrthogonalRectangle.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdOrthogonalRectangle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdOrthogonalRectangleActionPerformed(evt); } }); tobVerdis.add(cmdOrthogonalRectangle); mainGroup.add(cmdSearchFlurstueck); cmdSearchFlurstueck.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/alk.png"))); // NOI18N cmdSearchFlurstueck.setToolTipText("Alkis Renderer"); cmdSearchFlurstueck.setBorderPainted(false); cmdSearchFlurstueck.setContentAreaFilled(false); cmdSearchFlurstueck.setFocusPainted(false); cmdSearchFlurstueck.setFocusable(false); cmdSearchFlurstueck.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdSearchFlurstueck.setMaximumSize(new java.awt.Dimension(28, 20)); cmdSearchFlurstueck.setPreferredSize(new java.awt.Dimension(28, 20)); cmdSearchFlurstueck.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/alk_selected.png"))); // NOI18N cmdSearchFlurstueck.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdSearchFlurstueck.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdSearchFlurstueckActionPerformed(evt); } }); tobVerdis.add(cmdSearchFlurstueck); cmdSearchKassenzeichen.setAction(searchAction); cmdSearchKassenzeichen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/kassenzeichenSearchRectangle.png"))); // NOI18N cmdSearchKassenzeichen.setToolTipText("Kassenzeichen-Suche"); cmdSearchKassenzeichen.setBorderPainted(false); mainGroup.add(cmdSearchKassenzeichen); cmdSearchKassenzeichen.setContentAreaFilled(false); cmdSearchKassenzeichen.setFocusPainted(false); cmdSearchKassenzeichen.setFocusable(false); cmdSearchKassenzeichen.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdSearchKassenzeichen.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/kassenzeichenSearchRectangle_selected.png"))); // NOI18N cmdSearchKassenzeichen.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdSearchKassenzeichen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdSearchKassenzeichenActionPerformed(evt); } }); tobVerdis.add(cmdSearchKassenzeichen); mainGroup.add(cmdRaisePolygon); cmdRaisePolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/raisePoly.png"))); // NOI18N cmdRaisePolygon.setToolTipText("Polygon hochholen"); cmdRaisePolygon.setBorderPainted(false); cmdRaisePolygon.setContentAreaFilled(false); cmdRaisePolygon.setFocusPainted(false); cmdRaisePolygon.setFocusable(false); cmdRaisePolygon.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/raisePoly_selected.png"))); // NOI18N cmdRaisePolygon.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdRaisePolygonActionPerformed(evt); } }); tobVerdis.add(cmdRaisePolygon); mainGroup.add(cmdRemovePolygon); cmdRemovePolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/removePoly.png"))); // NOI18N cmdRemovePolygon.setToolTipText("Polygon entfernen"); cmdRemovePolygon.setBorderPainted(false); cmdRemovePolygon.setContentAreaFilled(false); cmdRemovePolygon.setFocusPainted(false); cmdRemovePolygon.setFocusable(false); cmdRemovePolygon.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/removePoly_selected.png"))); // NOI18N cmdRemovePolygon.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdRemovePolygonActionPerformed(evt); } }); tobVerdis.add(cmdRemovePolygon); mainGroup.add(cmdAttachPolyToAlphadata); cmdAttachPolyToAlphadata.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/polygonAttachment.png"))); // NOI18N cmdAttachPolyToAlphadata.setToolTipText("Polygon zuordnen"); cmdAttachPolyToAlphadata.setBorderPainted(false); cmdAttachPolyToAlphadata.setContentAreaFilled(false); cmdAttachPolyToAlphadata.setFocusPainted(false); cmdAttachPolyToAlphadata.setFocusable(false); cmdAttachPolyToAlphadata.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/polygonAttachment_selected.png"))); // NOI18N cmdAttachPolyToAlphadata.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdAttachPolyToAlphadataActionPerformed(evt); } }); tobVerdis.add(cmdAttachPolyToAlphadata); mainGroup.add(cmdJoinPoly); cmdJoinPoly.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/joinPoly.png"))); // NOI18N cmdJoinPoly.setToolTipText("Polygone zusammenfassen"); cmdJoinPoly.setBorderPainted(false); cmdJoinPoly.setContentAreaFilled(false); cmdJoinPoly.setFocusPainted(false); cmdJoinPoly.setFocusable(false); cmdJoinPoly.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/joinPoly_selected.png"))); // NOI18N cmdJoinPoly.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdJoinPolyActionPerformed(evt); } }); tobVerdis.add(cmdJoinPoly); mainGroup.add(cmdSplitPoly); cmdSplitPoly.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/splitPoly.png"))); // NOI18N cmdSplitPoly.setToolTipText("Polygon splitten"); cmdSplitPoly.setBorderPainted(false); cmdSplitPoly.setContentAreaFilled(false); cmdSplitPoly.setFocusPainted(false); cmdSplitPoly.setFocusable(false); cmdSplitPoly.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/splitPoly_selected.png"))); // NOI18N cmdSplitPoly.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdSplitPolyActionPerformed(evt); } }); tobVerdis.add(cmdSplitPoly); sep3.setOrientation(javax.swing.SwingConstants.VERTICAL); sep3.setMaximumSize(new java.awt.Dimension(2, 32767)); tobVerdis.add(sep3); handleGroup.add(cmdMoveHandle); cmdMoveHandle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/moveHandle.png"))); // NOI18N cmdMoveHandle.setSelected(true); cmdMoveHandle.setToolTipText("Handle verschieben"); cmdMoveHandle.setBorderPainted(false); cmdMoveHandle.setContentAreaFilled(false); cmdMoveHandle.setFocusPainted(false); cmdMoveHandle.setFocusable(false); cmdMoveHandle.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/moveHandle_selected.png"))); // NOI18N cmdMoveHandle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdMoveHandleActionPerformed(evt); } }); tobVerdis.add(cmdMoveHandle); handleGroup.add(cmdAddHandle); cmdAddHandle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/addHandle.png"))); // NOI18N cmdAddHandle.setToolTipText("Handle hinzufügen"); cmdAddHandle.setBorderPainted(false); cmdAddHandle.setContentAreaFilled(false); cmdAddHandle.setFocusPainted(false); cmdAddHandle.setFocusable(false); cmdAddHandle.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/addHandle_selected.png"))); // NOI18N cmdAddHandle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdAddHandleActionPerformed(evt); } }); tobVerdis.add(cmdAddHandle); handleGroup.add(cmdRemoveHandle); cmdRemoveHandle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/removeHandle.png"))); // NOI18N cmdRemoveHandle.setToolTipText("Handle entfernen"); cmdRemoveHandle.setBorderPainted(false); cmdRemoveHandle.setContentAreaFilled(false); cmdRemoveHandle.setFocusPainted(false); cmdRemoveHandle.setFocusable(false); cmdRemoveHandle.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/removeHandle_selected.png"))); // NOI18N cmdRemoveHandle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdRemoveHandleActionPerformed(evt); } }); tobVerdis.add(cmdRemoveHandle); handleGroup.add(cmdRotatePolygon); cmdRotatePolygon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/rotate16.png"))); // NOI18N cmdRotatePolygon.setToolTipText("Rotiere Polygon"); cmdRotatePolygon.setBorderPainted(false); cmdRotatePolygon.setContentAreaFilled(false); cmdRotatePolygon.setFocusPainted(false); cmdRotatePolygon.setFocusable(false); cmdRotatePolygon.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/rotate16_selected.png"))); // NOI18N cmdRotatePolygon.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdRotatePolygonActionPerformed(evt); } }); tobVerdis.add(cmdRotatePolygon); sep4.setOrientation(javax.swing.SwingConstants.VERTICAL); sep4.setMaximumSize(new java.awt.Dimension(2, 32767)); tobVerdis.add(sep4); cmdUndo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/undo.png"))); // NOI18N cmdUndo.setToolTipText("Undo"); cmdUndo.setBorderPainted(false); cmdUndo.setContentAreaFilled(false); cmdUndo.setEnabled(false); cmdUndo.setFocusPainted(false); cmdUndo.setFocusable(false); cmdUndo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdUndo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdUndoActionPerformed(evt); } }); tobVerdis.add(cmdUndo); cmdRedo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/verdis/res/images/toolbar/redo.png"))); // NOI18N cmdRedo.setBorderPainted(false); cmdRedo.setContentAreaFilled(false); cmdRedo.setEnabled(false); cmdRedo.setFocusPainted(false); cmdRedo.setFocusable(false); cmdRedo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); cmdRedo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cmdRedo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdRedoActionPerformed(evt); } }); tobVerdis.add(cmdRedo); panMap.add(tobVerdis, java.awt.BorderLayout.NORTH); add(panMap, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents
diff --git a/ComicReader/src/com/blogspot/applications4android/comicreader/core/ComicClassList.java b/ComicReader/src/com/blogspot/applications4android/comicreader/core/ComicClassList.java index ff34cf7..d989740 100755 --- a/ComicReader/src/com/blogspot/applications4android/comicreader/core/ComicClassList.java +++ b/ComicReader/src/com/blogspot/applications4android/comicreader/core/ComicClassList.java @@ -1,622 +1,623 @@ package com.blogspot.applications4android.comicreader.core; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.blogspot.applications4android.comicreader.exceptions.ComicNotFoundException; import com.blogspot.applications4android.comicreader.exceptions.ComicSDCardFull; import com.blogspot.applications4android.comicreader.exceptions.ComicSortException; import android.content.res.AssetManager; import android.util.Log; /** * Class which manages the list of comics */ public class ComicClassList { /** json file containing the list of supported classes */ public static final String CLASSES = "classes.json"; /** json file containing the list of selected classes */ public static final String SELECTED = "selected.json"; /** sorting in ASCII order */ public static final int SORT_ALPHABETICAL = 1; /** sorting in ASCII order but ignoring the articles */ public static final int SORT_IGNORE_ARTICLES = 2; /** sorting with editorial comics at the last */ public static final int SORT_EDITORIAL_LAST = 3; /** sorting in newly added first order */ public static final int SORT_NEWEST_FIRST = 4; /** sorting in selected first order */ public static final int SORT_SELECTED_FIRST = 5; /** sorting in most unread strips order */ public static final int SORT_MOST_UNREAD_FIRST = 6; /** for logging purposes only */ private static final String TAG = "ComicClassList"; /** package to which all these classes are part of */ private String mPkg; /** list of all comics read from json file */ private ComicClass[] mClasses; /** hashmap for these classes */ private HashMap<String, Integer> mIdxs; /** file which stores the selected comics list */ private File mSel; //// NOTE NOTE NOTE NOTE //// /// Before releasing to market, do remember to set the below flag to 'true'!!!!!!!! /** flag which will tell whether to use the below array to filtering the comics! */ private static boolean FILTER_COMICS = false; /** list of comics that cannot be shown to the users! */ private static final String[] FILTER_COMICS_LIST = { "Cyanide and Happiness" }; /** * Constructor * @param mgr the asset manager * @throws JSONException * @throws IOException * @throws ComicNotFoundException */ public ComicClassList(AssetManager mgr) throws IOException, JSONException, ComicNotFoundException { File sel = new File(FileUtils.getComicRoot(), SELECTED); _init_(mgr, CLASSES, sel); } /** * Constructor * @param mgr asset manager * @param path path to json file wrt assets * @throws JSONException * @throws IOException * @throws ComicNotFoundException */ public ComicClassList(AssetManager mgr, String path) throws IOException, JSONException, ComicNotFoundException { File sel = new File(FileUtils.getComicRoot(), SELECTED); _init_(mgr, path, sel); } /** * Constructor * @param mgr asset manager * @param path path to json file wrt assets * @param selected file containing the list of selected comics * @throws JSONException * @throws IOException * @throws ComicNotFoundException */ public ComicClassList(AssetManager mgr, String path, File selected) throws IOException, JSONException, ComicNotFoundException { _init_(mgr, path, selected); } /** * Gets the package to which all the classes belong to * @return package name */ public String getPackage() { return mPkg; } /** * Gets the number of comics in the list * @return number of comics */ public int length() { return mClasses.length; } /** * Sort the classes according to the pre-defined types * @param type sorting type * @throws ComicSortException */ public void sortClasses(int type) throws ComicSortException { if(mClasses.length <= 0) { Log.d(TAG, "sortClasses: nothing to sort..."); return; } switch(type) { case SORT_ALPHABETICAL: Arrays.sort(mClasses, new AsciiComparator()); break; case SORT_IGNORE_ARTICLES: Arrays.sort(mClasses, new IgnoreArticlesComparator()); break; case SORT_EDITORIAL_LAST: Arrays.sort(mClasses, new EditorialLastComparator()); break; case SORT_NEWEST_FIRST: Arrays.sort(mClasses, new NewestFirstComparator()); break; case SORT_SELECTED_FIRST: Arrays.sort(mClasses, new SelectedFirstComparator()); break; case SORT_MOST_UNREAD_FIRST: Arrays.sort(mClasses, new NumUnreadStripsComparator()); break; default: throw new ComicSortException("Bad sort-type passed! type="+type); } int i = 0; for(ComicClass clz : mClasses) { mIdxs.put(clz.mName, i); ++i; } } /** * get the comic class object from the index * @param idx index * @return comic class object * @throws ComicNotFoundException */ public ComicClass getComicClassFromIndex(int idx) throws ComicNotFoundException { if((idx < 0) || (idx >= mClasses.length)) { ComicNotFoundException cnf = new ComicNotFoundException("Bad Index passed for 'getComicFromIndex'! idx="+idx+"len="+mClasses.length); throw cnf; } return mClasses[idx]; } /** * Helper function to load the comic object * @param idx location where it is stored in ComicClassList * @return Comic Object * @throws ComicNotFoundException */ private Comic getComicObject(int idx) throws ComicNotFoundException { try { String fname = mPkg + "." + mClasses[idx].mClass; Log.d(TAG, "Trying to load class="+fname); Class<?> comicClass = Class.forName(fname); Comic com = (Comic)comicClass.newInstance(); com.setComicName(mClasses[idx].mName); Log.d(TAG, "Successfully loaded class="+fname); return com; } catch(Exception e) { ComicNotFoundException cnf = new ComicNotFoundException("Comic for idx="+idx+" could not be found!"); throw cnf; } } /** * Get the comic object from the index * @param idx comic index * @return comic object * @throws ComicNotFoundException */ // TODO: add unit-tests public Comic getComicFromIndex(int idx) throws ComicNotFoundException { if((idx < 0) || (idx >= mClasses.length)) { ComicNotFoundException cnf = new ComicNotFoundException("Bad Index passed for 'getComicFromIndex'! idx="+idx+"len="+mClasses.length); throw cnf; } return getComicObject(idx); } /** * Get the comic object from the title * @param title comic english name * @return comic object * @throws ComicNotFoundException */ // TODO: add unit-tests public Comic getComicFromTitle(String title) throws ComicNotFoundException { Log.d(TAG, "getting comic for title="+title); return getComicFromIndex(getComicIndexFromTitle(title)); } /** * Get the comic next to the one wrt the input title * @param title comic english name * @return comic object * @throws ComicNotFoundException */ // TODO: add unit-tests public Comic getNextComic(String title) throws ComicNotFoundException { int i = getComicIndexFromTitle(title); i = (i >= (mClasses.length - 1))? 0 : (i + 1); return getComicFromIndex(i); } /** * Get the comic next to the one wrt the input title * @param title comic english name * @return comic object * @throws ComicNotFoundException */ // TODO: add unit-tests public Comic getNextMyComic(String title) throws ComicNotFoundException { int f = getComicIndexFromTitle(title); int j = mClasses.length; for(int i=f+1;i<j;++i) { if(mClasses[i].mSel) { return getComicFromIndex(i); } } for(int i=0;i<f;++i) { if(mClasses[i].mSel) { return getComicFromIndex(i); } } return getComicFromIndex(f); } /** * Get the comic previous to the one wrt the input title * @param title comic english name * @return comic object * @throws ComicNotFoundException */ // TODO: add unit-tests public Comic getPreviousComic(String title) throws ComicNotFoundException { int i = getComicIndexFromTitle(title); i = (i <= 0)? (mClasses.length - 1) : (i - 1); return getComicFromIndex(i); } /** * Get the comic previous to the one wrt the input title * @param title comic english name * @return comic object * @throws ComicNotFoundException */ // TODO: add unit-tests public Comic getPreviousMyComic(String title) throws ComicNotFoundException { int f = getComicIndexFromTitle(title); for(int i=f-1;i>=0;--i) { if(mClasses[i].mSel) { return getComicFromIndex(i); } } for(int i=mClasses.length-1;i>f;--i) { if(mClasses[i].mSel) { return getComicFromIndex(i); } } return getComicFromIndex(f); } /** * Return the index of the comic in the list from its title * @param title comic english name * @return index if found, else -1 */ public int getComicIndexFromTitle(String title) { if(!mIdxs.containsKey(title)) { return -1; } return mIdxs.get(title); } /** * Returns the list of selected comic indices * @return list */ public int[] getSelectedComicList() { int num = numSelected(); if(num <= 0) { return null; } int[] sel = new int[num]; int i = 0; int j = 0; for(ComicClass clz : mClasses) { if(clz.mSel) { sel[j] = i; ++j; } ++i; } return sel; } /** * Set the comic to be selected * @param title comic english name * @param value true if it is to be selected * @throws ComicNotFoundException */ public void setSelected(String title, boolean value) throws ComicNotFoundException { int idx = getComicIndexFromTitle(title); if(idx >= 0) { mClasses[idx].mSel = value; } } /** * Tells whether the comic in the current index is selected or not * @param idx index * @return true if it is selected * @throws ComicNotFoundException */ public boolean isSelected(int idx) throws ComicNotFoundException { if((idx < 0) || (idx >= mClasses.length)) { ComicNotFoundException cnf = new ComicNotFoundException("Bad Index passed for 'isSelected'! idx="+idx+"len="+mClasses.length); throw cnf; } return mClasses[idx].mSel; } /** * Toggle the select bit for the given comic * @param idx comic index * @throws ComicNotFoundException */ public void toggleSelected(int idx) throws ComicNotFoundException { if((idx < 0) || (idx >= mClasses.length)) { ComicNotFoundException cnf = new ComicNotFoundException("Bad Index passed for 'toggleSelected'! idx="+idx+"len="+mClasses.length); throw cnf; } mClasses[idx].mSel = (mClasses[idx].mSel)? false : true; } /** * Set all the comics to be selected * @param value true if it is to be selected */ public void setAllSelected(boolean value) { for(ComicClass clz : mClasses) { clz.mSel = value; } } /** * Number of comics selected so far * @return number */ public int numSelected() { int i = 0; for(ComicClass clz : mClasses) { if(clz.mSel) { ++i; } } return i; } /** * Store the selected comics into the json file * @throws IOException * @throws ComicSDCardFull */ public void storeSelected() throws IOException, ComicSDCardFull { StringBuilder sb = new StringBuilder(); sb.append("{\n"); { sb.append("\"selected\" : [ "); int i = 0; for(ComicClass clz : mClasses) { if(clz.mSel) { if(i == 0) { sb.append("\"" + clz.mName + "\""); } else { sb.append(", \"" + clz.mName + "\""); } ++i; } } sb.append(" ]\n"); } sb.append("}\n"); FileUtils.storeString(sb.toString(), mSel); Log.d(TAG, "Stored the selected comics to file '" + mSel.getPath() + "'"); } /** * File which stores the list of selected comics * @return file */ public File selectedFile() { return mSel; } /** * Initializer * @param mgr asset manager * @param path path to json file wrt assets * @param selected file containing the list of selected comics * @throws JSONException * @throws IOException * @throws ComicNotFoundException */ private void _init_(AssetManager mgr, String path, File selected) throws IOException, JSONException, ComicNotFoundException { // selected JSONArray selArr = null; // by somehow if the selected.json was empty, then this can cause parse error if(selected.exists() && (selected.length() <= 0)) { selected.delete(); } if(selected.exists()) { String sel = FileUtils.slurp(new FileInputStream(selected)); JSONObject selRoot = new JSONObject(sel); selArr = selRoot.getJSONArray("selected"); } // parse the file String data = FileUtils.slurp(path, mgr); JSONObject root = new JSONObject(data); JSONArray classes = root.getJSONArray("classes"); int numClasses = classes.length(); ArrayList<ComicClass> com_arr = new ArrayList<ComicClass>(); // set fields mPkg = root.getString("package"); mIdxs = new HashMap<String, Integer>(); mSel = selected; int j = 0; for(int i=0;i<numClasses;i++) { JSONObject clz = classes.getJSONObject(i); String key = clz.getString("name"); if(!_canAdd(key)) { Log.d(TAG, "Not adding the comic '" + key + "' to the list..."); continue; } ComicClass cl = new ComicClass(); cl.mClass = clz.getString("class"); cl.mName = key; cl.mPref = clz.getString("pref"); if(clz.has("new") && clz.getString("new").equals("1")) { cl.mNew = true; } else { cl.mNew = false; } cl.mSel = false; com_arr.add(cl); mIdxs.put(key, j); j++; } mClasses = new ComicClass[com_arr.size()]; com_arr.toArray(mClasses); if(selArr != null) { int num = selArr.length(); for(int i=0;i<num;++i) { String s = selArr.getString(i); setSelected(s, true); } } + numClasses = mClasses.length; for(int i=0;i<numClasses;++i) { if(!mClasses[i].mSel) { continue; } Comic com = getComicObject(i); mClasses[i].mUnread = com.readOnlyUnread(); } } /** * Function to tell whether this comic can be added to comic-class-list. * @param name comic name * @return true if it can be added, else false */ private boolean _canAdd(String name) { if(!FILTER_COMICS) { return true; } for(String dont : FILTER_COMICS_LIST) { if(name.compareTo(dont) == 0) { return false; } } return true; } ////// COMPARATOR CLASSES FOR SORTING THE COMICS ////// /** For sorting classes based on ASCII comparison */ private class AsciiComparator implements Comparator<ComicClass> { @Override public int compare(ComicClass a, ComicClass b) { String sa = a.mName; String sb = b.mName; return sa.compareTo(sb); } } /** For sorting classes based on number of unread strips */ private class NumUnreadStripsComparator implements Comparator<ComicClass> { @Override public int compare(ComicClass a, ComicClass b) { if(a.mUnread == b.mUnread) { String sa = a.mName; String sb = b.mName; return sa.compareTo(sb); } if(a.mUnread > b.mUnread) { return -1; } return 1; } } /** For sorting editorial comics to last */ private class EditorialLastComparator implements Comparator<ComicClass> { @Override public int compare(ComicClass a, ComicClass b) { String sa = a.mName; String sb = b.mName; boolean ea = _isEditorial(sa); boolean eb = _isEditorial(sb); if(ea && !eb) { return 1; } if(!ea && eb) { return -1; } return sa.compareTo(sb); } private boolean _isEditorial(String a) { return (a.indexOf("Editorial : ") == 0); } } /** For sorting classes based on newest first */ private class NewestFirstComparator implements Comparator<ComicClass> { @Override public int compare(ComicClass a, ComicClass b) { if(a.mNew && !b.mNew) { return -1; } if(!a.mNew && b.mNew) { return 1; } String sa = a.mName; String sb = b.mName; return sa.compareTo(sb); } } /** For sorting classes based on selected first */ private class SelectedFirstComparator implements Comparator<ComicClass> { @Override public int compare(ComicClass a, ComicClass b) { if(a.mSel && !b.mSel) { return -1; } if(!a.mSel && b.mSel) { return 1; } String sa = a.mName; String sb = b.mName; return sa.compareTo(sb); } } /** For sorting classes based on ignore articles */ private class IgnoreArticlesComparator implements Comparator<ComicClass> { @Override public int compare(ComicClass a, ComicClass b) { String sa = _ignoreArticle(a.mName); String sb = _ignoreArticle(b.mName); return sa.compareTo(sb); } private String _ignoreArticle(String a) { if(a.indexOf("A ") == 0) { return a.substring(2); } if(a.indexOf("An ") == 0) { return a.substring(3); } if(a.indexOf("The ") == 0) { return a.substring(4); } return a; } } ////// COMPARATOR CLASSES FOR SORTING THE COMICS ////// }
true
true
private void _init_(AssetManager mgr, String path, File selected) throws IOException, JSONException, ComicNotFoundException { // selected JSONArray selArr = null; // by somehow if the selected.json was empty, then this can cause parse error if(selected.exists() && (selected.length() <= 0)) { selected.delete(); } if(selected.exists()) { String sel = FileUtils.slurp(new FileInputStream(selected)); JSONObject selRoot = new JSONObject(sel); selArr = selRoot.getJSONArray("selected"); } // parse the file String data = FileUtils.slurp(path, mgr); JSONObject root = new JSONObject(data); JSONArray classes = root.getJSONArray("classes"); int numClasses = classes.length(); ArrayList<ComicClass> com_arr = new ArrayList<ComicClass>(); // set fields mPkg = root.getString("package"); mIdxs = new HashMap<String, Integer>(); mSel = selected; int j = 0; for(int i=0;i<numClasses;i++) { JSONObject clz = classes.getJSONObject(i); String key = clz.getString("name"); if(!_canAdd(key)) { Log.d(TAG, "Not adding the comic '" + key + "' to the list..."); continue; } ComicClass cl = new ComicClass(); cl.mClass = clz.getString("class"); cl.mName = key; cl.mPref = clz.getString("pref"); if(clz.has("new") && clz.getString("new").equals("1")) { cl.mNew = true; } else { cl.mNew = false; } cl.mSel = false; com_arr.add(cl); mIdxs.put(key, j); j++; } mClasses = new ComicClass[com_arr.size()]; com_arr.toArray(mClasses); if(selArr != null) { int num = selArr.length(); for(int i=0;i<num;++i) { String s = selArr.getString(i); setSelected(s, true); } } for(int i=0;i<numClasses;++i) { if(!mClasses[i].mSel) { continue; } Comic com = getComicObject(i); mClasses[i].mUnread = com.readOnlyUnread(); } }
private void _init_(AssetManager mgr, String path, File selected) throws IOException, JSONException, ComicNotFoundException { // selected JSONArray selArr = null; // by somehow if the selected.json was empty, then this can cause parse error if(selected.exists() && (selected.length() <= 0)) { selected.delete(); } if(selected.exists()) { String sel = FileUtils.slurp(new FileInputStream(selected)); JSONObject selRoot = new JSONObject(sel); selArr = selRoot.getJSONArray("selected"); } // parse the file String data = FileUtils.slurp(path, mgr); JSONObject root = new JSONObject(data); JSONArray classes = root.getJSONArray("classes"); int numClasses = classes.length(); ArrayList<ComicClass> com_arr = new ArrayList<ComicClass>(); // set fields mPkg = root.getString("package"); mIdxs = new HashMap<String, Integer>(); mSel = selected; int j = 0; for(int i=0;i<numClasses;i++) { JSONObject clz = classes.getJSONObject(i); String key = clz.getString("name"); if(!_canAdd(key)) { Log.d(TAG, "Not adding the comic '" + key + "' to the list..."); continue; } ComicClass cl = new ComicClass(); cl.mClass = clz.getString("class"); cl.mName = key; cl.mPref = clz.getString("pref"); if(clz.has("new") && clz.getString("new").equals("1")) { cl.mNew = true; } else { cl.mNew = false; } cl.mSel = false; com_arr.add(cl); mIdxs.put(key, j); j++; } mClasses = new ComicClass[com_arr.size()]; com_arr.toArray(mClasses); if(selArr != null) { int num = selArr.length(); for(int i=0;i<num;++i) { String s = selArr.getString(i); setSelected(s, true); } } numClasses = mClasses.length; for(int i=0;i<numClasses;++i) { if(!mClasses[i].mSel) { continue; } Comic com = getComicObject(i); mClasses[i].mUnread = com.readOnlyUnread(); } }
diff --git a/bundles/org.eclipse.e4.core.contexts/src/org/eclipse/e4/core/internal/contexts/ContextObjectSupplier.java b/bundles/org.eclipse.e4.core.contexts/src/org/eclipse/e4/core/internal/contexts/ContextObjectSupplier.java index a43d4581e..edd0d1e6e 100644 --- a/bundles/org.eclipse.e4.core.contexts/src/org/eclipse/e4/core/internal/contexts/ContextObjectSupplier.java +++ b/bundles/org.eclipse.e4.core.contexts/src/org/eclipse/e4/core/internal/contexts/ContextObjectSupplier.java @@ -1,191 +1,194 @@ /******************************************************************************* * Copyright (c) 2009, 2010 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.e4.core.internal.contexts; import javax.inject.Named; import org.eclipse.e4.core.contexts.ContextChangeEvent; import org.eclipse.e4.core.contexts.IEclipseContext; import org.eclipse.e4.core.contexts.IRunAndTrack; import org.eclipse.e4.core.di.AbstractObjectSupplier; import org.eclipse.e4.core.di.IInjector; import org.eclipse.e4.core.di.IObjectDescriptor; import org.eclipse.e4.core.di.IRequestor; public class ContextObjectSupplier extends AbstractObjectSupplier { static private class ContextInjectionListener implements IRunAndTrackObject { final private Object[] result; final private String[] keys; final private IInjector injector; final private IRequestor requestor; final private IEclipseContext context; public ContextInjectionListener(IEclipseContext context, Object[] result, String[] keys, IInjector injector, IRequestor requestor) { this.result = result; this.keys = keys; this.injector = injector; this.requestor = requestor; this.context = context; } public boolean notify(ContextChangeEvent event) { if (event.getEventType() == ContextChangeEvent.INITIAL) { // needs to be done inside runnable to establish dependencies for (int i = 0; i < keys.length; i++) { if (keys[i] == null) continue; if (context.containsKey(keys[i])) result[i] = context.get(keys[i]); else result[i] = IInjector.NOT_A_VALUE; // TBD make sure this still creates // dependency on the key } return true; } - IEclipseContext originatingContext = event.getContext(); - ContextObjectSupplier originatingSupplier = getObjectSupplier(originatingContext, injector); if (event.getEventType() == ContextChangeEvent.DISPOSE) { + IEclipseContext originatingContext = event.getContext(); + ContextObjectSupplier originatingSupplier = getObjectSupplier(originatingContext, injector); injector.disposed(originatingSupplier); return false; } else if (event.getEventType() == ContextChangeEvent.UNINJECTED) { + IEclipseContext originatingContext = event.getContext(); + ContextObjectSupplier originatingSupplier = getObjectSupplier(originatingContext, injector); injector.uninject(event.getArguments()[0], originatingSupplier); return false; } else { - injector.update(new IRequestor[] { requestor }, originatingSupplier); + ContextObjectSupplier supplier = getObjectSupplier(context, injector); + injector.update(new IRequestor[] { requestor }, supplier); } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((context == null) ? 0 : context.hashCode()); result = prime * result + ((injector == null) ? 0 : injector.hashCode()); result = prime * result + ((requestor == null) ? 0 : requestor.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ContextInjectionListener other = (ContextInjectionListener) obj; if (context == null) { if (other.context != null) return false; } else if (!context.equals(other.context)) return false; if (injector == null) { if (other.injector != null) return false; } else if (!injector.equals(other.injector)) return false; if (requestor == null) { if (other.requestor != null) return false; } else if (!requestor.equals(other.requestor)) return false; return true; } public Object getObject() { // XXX remove? // TODO Auto-generated method stub return null; } public boolean batchProcess() { return requestor.shouldGroupUpdates(); } } final static private String ECLIPSE_CONTEXT_NAME = IEclipseContext.class.getName(); final private IEclipseContext context; public ContextObjectSupplier(IEclipseContext context, IInjector injector) { super(injector); this.context = context; } public IEclipseContext getContext() { return context; } @Override public Object get(IObjectDescriptor descriptor, IRequestor requestor) { // This method is rarely or never used on the primary supplier if (descriptor == null) return IInjector.NOT_A_VALUE; Object[] result = get(new IObjectDescriptor[] { descriptor }, requestor); if (result == null) return null; return result[0]; } @Override public Object[] get(IObjectDescriptor[] descriptors, final IRequestor requestor) { final Object[] result = new Object[descriptors.length]; final String[] keys = new String[descriptors.length]; for (int i = 0; i < descriptors.length; i++) { keys[i] = (descriptors[i] == null) ? null : getKey(descriptors[i]); if (ECLIPSE_CONTEXT_NAME.equals(keys[i])) { result[i] = context; keys[i] = null; } } if (requestor != null && requestor.shouldTrack()) { // only track if requested IRunAndTrack trackable = new ContextInjectionListener(context, result, keys, injector, requestor); context.runAndTrack(trackable, null); } else { for (int i = 0; i < descriptors.length; i++) { if (keys[i] == null) continue; if (context.containsKey(keys[i])) result[i] = context.get(keys[i]); else result[i] = IInjector.NOT_A_VALUE; } } return result; } private String getKey(IObjectDescriptor descriptor) { if (descriptor.hasQualifier(Named.class.getName())) return descriptor.getQualifierValue(Named.class.getName()); Class<?> elementClass = descriptor.getElementClass(); if (elementClass != null) return elementClass.getName(); return null; } static public ContextObjectSupplier getObjectSupplier(IEclipseContext context, IInjector injector) { String key = ContextObjectSupplier.class.getName(); if (context.containsKey(key, true)) return (ContextObjectSupplier) context.get(key); ContextObjectSupplier objectSupplier = new ContextObjectSupplier(context, injector); context.set(key, objectSupplier); return objectSupplier; } }
false
true
public boolean notify(ContextChangeEvent event) { if (event.getEventType() == ContextChangeEvent.INITIAL) { // needs to be done inside runnable to establish dependencies for (int i = 0; i < keys.length; i++) { if (keys[i] == null) continue; if (context.containsKey(keys[i])) result[i] = context.get(keys[i]); else result[i] = IInjector.NOT_A_VALUE; // TBD make sure this still creates // dependency on the key } return true; } IEclipseContext originatingContext = event.getContext(); ContextObjectSupplier originatingSupplier = getObjectSupplier(originatingContext, injector); if (event.getEventType() == ContextChangeEvent.DISPOSE) { injector.disposed(originatingSupplier); return false; } else if (event.getEventType() == ContextChangeEvent.UNINJECTED) { injector.uninject(event.getArguments()[0], originatingSupplier); return false; } else { injector.update(new IRequestor[] { requestor }, originatingSupplier); } return true; }
public boolean notify(ContextChangeEvent event) { if (event.getEventType() == ContextChangeEvent.INITIAL) { // needs to be done inside runnable to establish dependencies for (int i = 0; i < keys.length; i++) { if (keys[i] == null) continue; if (context.containsKey(keys[i])) result[i] = context.get(keys[i]); else result[i] = IInjector.NOT_A_VALUE; // TBD make sure this still creates // dependency on the key } return true; } if (event.getEventType() == ContextChangeEvent.DISPOSE) { IEclipseContext originatingContext = event.getContext(); ContextObjectSupplier originatingSupplier = getObjectSupplier(originatingContext, injector); injector.disposed(originatingSupplier); return false; } else if (event.getEventType() == ContextChangeEvent.UNINJECTED) { IEclipseContext originatingContext = event.getContext(); ContextObjectSupplier originatingSupplier = getObjectSupplier(originatingContext, injector); injector.uninject(event.getArguments()[0], originatingSupplier); return false; } else { ContextObjectSupplier supplier = getObjectSupplier(context, injector); injector.update(new IRequestor[] { requestor }, supplier); } return true; }
diff --git a/src/rapidshare/cz/vity/freerapid/plugins/services/rapidshare/RapidShareRunner.java b/src/rapidshare/cz/vity/freerapid/plugins/services/rapidshare/RapidShareRunner.java index 272e983f..25381739 100644 --- a/src/rapidshare/cz/vity/freerapid/plugins/services/rapidshare/RapidShareRunner.java +++ b/src/rapidshare/cz/vity/freerapid/plugins/services/rapidshare/RapidShareRunner.java @@ -1,204 +1,205 @@ package cz.vity.freerapid.plugins.services.rapidshare; import cz.vity.freerapid.plugins.exceptions.*; import cz.vity.freerapid.plugins.webclient.AbstractRunner; import cz.vity.freerapid.plugins.webclient.utils.PlugUtils; import org.apache.commons.httpclient.HttpMethod; import java.net.InetAddress; import java.net.URL; import java.net.UnknownHostException; import java.util.logging.Logger; import java.util.regex.Matcher; /** * @author Ladislav Vitasek, ntoskrnl */ class RapidShareRunner extends AbstractRunner { private final static Logger logger = Logger.getLogger(RapidShareRunner.class.getName()); private final static String SERVICE_WEB = "http://rapidshare.com/"; private final static int INTERVAL = 10000; private String fileID; private String fileName; private long lastRunCheck; @Override public void runCheck() throws Exception { super.runCheck(); checkURL(); final HttpMethod method = getMethodBuilder() .setReferer(SERVICE_WEB) .setAction("https://api.rapidshare.com/cgi-bin/rsapi.cgi") .setParameter("sub", "download") .setParameter("fileid", fileID) .setAndEncodeParameter("filename", fileName) .setParameter("try", "1") .setParameter("cbf", "RSAPIDispatcher") .setParameter("cbid", "1") .toGetMethod(); if (makeRedirectedRequest(method)) { checkFileProblems(); } else { checkFileProblems(); throw new ServiceConnectionProblemException(); } lastRunCheck = System.currentTimeMillis(); } @Override public void run() throws Exception { super.run(); if (System.currentTimeMillis() >= lastRunCheck + INTERVAL) { logger.info("Doing runCheck..."); runCheck(); } checkProblems(); final Matcher matcher = getMatcherAgainstContent("DL:(.+?),(.+?),(\\d+)"); if (!matcher.find()) { throw new PluginImplementationException("Error parsing API response"); } final int wait = Integer.parseInt(matcher.group(3)); final String host = translateToIP(matcher.group(1)); final HttpMethod method = getMethodBuilder() .setReferer(SERVICE_WEB) .setAction("http://" + host + "/cgi-bin/rsapi.cgi") .setParameter("sub", "download") .setParameter("editparentlocation", "1") .setParameter("bin", "1") .setParameter("fileid", fileID) .setAndEncodeParameter("filename", fileName) .setParameter("dlauth", matcher.group(2)) .toGetMethod(); downloadTask.sleep(wait + 1); if (!tryDownloadAndSaveFile(method)) { checkProblems(); throw new ServiceConnectionProblemException("Error starting download"); } } private void checkURL() throws Exception { Matcher matcher = PlugUtils.matcher("!download(?:%7C|\\|)(?:[^%\\|]+)(?:%7C|\\|)(\\d+)(?:%7C|\\|)([^%\\|]+)", fileURL); if (matcher.find()) { fileURL = "http://rapidshare.com/files/" + matcher.group(1) + "/" + matcher.group(2); httpFile.setNewURL(new URL(fileURL)); } matcher = PlugUtils.matcher("/files/(\\d+)/(.+)", fileURL); if (!matcher.find()) { throw new PluginImplementationException("Error parsing file URL"); } fileID = matcher.group(1); fileName = matcher.group(2); httpFile.setFileName(fileName); } private void checkProblems() throws ErrorDuringDownloadingException { checkFileProblems(); final String content = getContentAsString(); if (content.contains("You need RapidPro to download more files from your IP address") || content.contains("All free download slots are full")) { throw new ServiceConnectionProblemException("All free download slots are full"); } Matcher matcher = getMatcherAgainstContent("You need to wait (\\d+) seconds[^\"']*"); if (matcher.find()) { throw new YouHaveToWaitException(matcher.group(), Integer.parseInt(matcher.group(1)) + 10); } if (content.contains("Please stop flooding our download servers")) { throw new YouHaveToWaitException("RapidShare server says: Please stop flooding our download servers", 360); } if (content.contains("IP address modified") || content.contains("Download auth invalid") || content.contains("Download session expired") || content.contains("Download session invalid") || content.contains("Download session modified") || content.contains("Download ticket not ready") || content.contains("download: session invalid")) { throw new ServiceConnectionProblemException("Temporary server problem"); } if (content.contains("Secure download link modified") || content.contains("Secured link expired") || content.contains("Secured link modified")) { throw new ServiceConnectionProblemException("The file was requested using an invalid secure link"); } } private void checkFileProblems() throws ErrorDuringDownloadingException { final String content = getContentAsString(); Matcher matcher = getMatcherAgainstContent("File deleted R(\\d+)"); if (matcher.find()) { final int r = Integer.parseInt(matcher.group(1)); if (r == 1 || r == 2) { throw new URLNotAvailableAnymoreException("The file was deleted by the owner"); } if (r == 3 || r == 5) { throw new URLNotAvailableAnymoreException("The file was deleted due to no downloads in a longer period"); } if (r == 4 || r == 8) { throw new URLNotAvailableAnymoreException("The file is suspected to be contrary to our terms and conditions and has been locked up for clarification"); } if (r >= 10 && r <= 15) { throw new URLNotAvailableAnymoreException("This file is marked as illegal"); } } if (content.contains("File deleted") || content.contains("File not found") + || content.contains("Folder not found") || content.contains("File physically not found")) { throw new URLNotAvailableAnymoreException("File not found"); } if (content.contains("This file is too big to download it for free")) { throw new NotRecoverableDownloadException("This file is too big to download it for free"); } if (content.contains("This file is marked as illegal")) { throw new URLNotAvailableAnymoreException("This file is marked as illegal"); } if (content.contains("File incomplete") || content.contains("raid error on server")) { throw new URLNotAvailableAnymoreException("File corrupted or incomplete"); } if (content.contains("SSL downloads are only available for RapidPro customers")) { throw new NotRecoverableDownloadException("SSL downloads are only available for RapidPro customers"); } matcher = getMatcherAgainstContent("ERROR:([^\"']+)"); if (matcher.find()) { throw new NotRecoverableDownloadException("RapidShare error: " + matcher.group(1)); } } private static String translateToIP(String s) { //implemented http://wordrider.net/forum/read.php?11,3017,3028#msg-3028 int i1 = s.toLowerCase().indexOf("http://"); if (i1 == 0) { i1 += "http://".length(); final int i2 = s.indexOf('/', i1); if (i2 > 0) { final String subs = s.substring(i1, i2); String ip = hostToIP(subs); logger.info("Changing " + subs + " to " + ip); s = new StringBuilder(s).replace(i1, i2, ip).toString(); } } return s; } private static String hostToIP(final String value) { try { InetAddress addr = InetAddress.getByName(value); byte[] ipAddr = addr.getAddress(); // Convert to dot representation StringBuilder ipAddrStr = new StringBuilder(15); final int length = ipAddr.length; for (int i = 0; i < length; i++) { if (i > 0) { ipAddrStr.append('.'); } ipAddrStr.append(ipAddr[i] & 0xFF); } return ipAddrStr.toString(); } catch (UnknownHostException e) { return value; } } }
true
true
private void checkFileProblems() throws ErrorDuringDownloadingException { final String content = getContentAsString(); Matcher matcher = getMatcherAgainstContent("File deleted R(\\d+)"); if (matcher.find()) { final int r = Integer.parseInt(matcher.group(1)); if (r == 1 || r == 2) { throw new URLNotAvailableAnymoreException("The file was deleted by the owner"); } if (r == 3 || r == 5) { throw new URLNotAvailableAnymoreException("The file was deleted due to no downloads in a longer period"); } if (r == 4 || r == 8) { throw new URLNotAvailableAnymoreException("The file is suspected to be contrary to our terms and conditions and has been locked up for clarification"); } if (r >= 10 && r <= 15) { throw new URLNotAvailableAnymoreException("This file is marked as illegal"); } } if (content.contains("File deleted") || content.contains("File not found") || content.contains("File physically not found")) { throw new URLNotAvailableAnymoreException("File not found"); } if (content.contains("This file is too big to download it for free")) { throw new NotRecoverableDownloadException("This file is too big to download it for free"); } if (content.contains("This file is marked as illegal")) { throw new URLNotAvailableAnymoreException("This file is marked as illegal"); } if (content.contains("File incomplete") || content.contains("raid error on server")) { throw new URLNotAvailableAnymoreException("File corrupted or incomplete"); } if (content.contains("SSL downloads are only available for RapidPro customers")) { throw new NotRecoverableDownloadException("SSL downloads are only available for RapidPro customers"); } matcher = getMatcherAgainstContent("ERROR:([^\"']+)"); if (matcher.find()) { throw new NotRecoverableDownloadException("RapidShare error: " + matcher.group(1)); } }
private void checkFileProblems() throws ErrorDuringDownloadingException { final String content = getContentAsString(); Matcher matcher = getMatcherAgainstContent("File deleted R(\\d+)"); if (matcher.find()) { final int r = Integer.parseInt(matcher.group(1)); if (r == 1 || r == 2) { throw new URLNotAvailableAnymoreException("The file was deleted by the owner"); } if (r == 3 || r == 5) { throw new URLNotAvailableAnymoreException("The file was deleted due to no downloads in a longer period"); } if (r == 4 || r == 8) { throw new URLNotAvailableAnymoreException("The file is suspected to be contrary to our terms and conditions and has been locked up for clarification"); } if (r >= 10 && r <= 15) { throw new URLNotAvailableAnymoreException("This file is marked as illegal"); } } if (content.contains("File deleted") || content.contains("File not found") || content.contains("Folder not found") || content.contains("File physically not found")) { throw new URLNotAvailableAnymoreException("File not found"); } if (content.contains("This file is too big to download it for free")) { throw new NotRecoverableDownloadException("This file is too big to download it for free"); } if (content.contains("This file is marked as illegal")) { throw new URLNotAvailableAnymoreException("This file is marked as illegal"); } if (content.contains("File incomplete") || content.contains("raid error on server")) { throw new URLNotAvailableAnymoreException("File corrupted or incomplete"); } if (content.contains("SSL downloads are only available for RapidPro customers")) { throw new NotRecoverableDownloadException("SSL downloads are only available for RapidPro customers"); } matcher = getMatcherAgainstContent("ERROR:([^\"']+)"); if (matcher.find()) { throw new NotRecoverableDownloadException("RapidShare error: " + matcher.group(1)); } }
diff --git a/VSS-web/src/main/java/com/team33/controllers/BrowseVideosController.java b/VSS-web/src/main/java/com/team33/controllers/BrowseVideosController.java index ce792ec..e5aa452 100644 --- a/VSS-web/src/main/java/com/team33/controllers/BrowseVideosController.java +++ b/VSS-web/src/main/java/com/team33/controllers/BrowseVideosController.java @@ -1,79 +1,80 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team33.controllers; import com.team33.entities.VideoInfo; import com.team33.services.BrowseService; import com.team33.services.VideoAccessService; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * * @author Mark */ @Controller public class BrowseVideosController { @Autowired private BrowseService browseService; @Autowired private VideoAccessService videoAccessService; public void setBrowseService(BrowseService browseService){ this.browseService = browseService; } public void setVideoAccessService(VideoAccessService videoAccessService) { this.videoAccessService = videoAccessService; } @RequestMapping(value = "/browseVideos", method = RequestMethod.GET) public String getVideos(Map<String,Object> map) { /*List<Object> list = new ArrayList<Object>(); list.add(new DummyVideoInfo("The Lion King", "Mufasa dies.", "G", "Family")); list.add(new DummyVideoInfo("Top Gun", "Goose dies.", "PG-13", "Action")); list.add(new DummyVideoInfo("Final Destination", "They all die.", "14A", "Horror")); map.put("videoInfoList", list);*/ List<VideoInfo> list = this.browseService.displayAllVideoContent(); map.put("videoInfoList", list); + System.out.println("Done Add to List : " + list.size()); return "/browseVideos"; } public class DummyVideoInfo { String name; String description; String screenRating; String genre; public DummyVideoInfo(String name, String description, String screenRating, String genre) { this.name = name; this.description = description; this.screenRating = screenRating; this.genre = genre; } public String getName() { return name; } public String getDescription() { return description; } public String getScreenRating() { return screenRating; } public String getGenre() { return genre; } } }
true
true
public String getVideos(Map<String,Object> map) { /*List<Object> list = new ArrayList<Object>(); list.add(new DummyVideoInfo("The Lion King", "Mufasa dies.", "G", "Family")); list.add(new DummyVideoInfo("Top Gun", "Goose dies.", "PG-13", "Action")); list.add(new DummyVideoInfo("Final Destination", "They all die.", "14A", "Horror")); map.put("videoInfoList", list);*/ List<VideoInfo> list = this.browseService.displayAllVideoContent(); map.put("videoInfoList", list); return "/browseVideos"; }
public String getVideos(Map<String,Object> map) { /*List<Object> list = new ArrayList<Object>(); list.add(new DummyVideoInfo("The Lion King", "Mufasa dies.", "G", "Family")); list.add(new DummyVideoInfo("Top Gun", "Goose dies.", "PG-13", "Action")); list.add(new DummyVideoInfo("Final Destination", "They all die.", "14A", "Horror")); map.put("videoInfoList", list);*/ List<VideoInfo> list = this.browseService.displayAllVideoContent(); map.put("videoInfoList", list); System.out.println("Done Add to List : " + list.size()); return "/browseVideos"; }
diff --git a/OsceManager/src/main/java/ch/unibas/medizin/osce/server/util/file/XmlUtil.java b/OsceManager/src/main/java/ch/unibas/medizin/osce/server/util/file/XmlUtil.java index f4cc2291..e34b3a45 100644 --- a/OsceManager/src/main/java/ch/unibas/medizin/osce/server/util/file/XmlUtil.java +++ b/OsceManager/src/main/java/ch/unibas/medizin/osce/server/util/file/XmlUtil.java @@ -1,320 +1,320 @@ package ch.unibas.medizin.osce.server.util.file; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.OutputStream; import java.util.Iterator; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import ch.unibas.medizin.osce.domain.CheckList; import ch.unibas.medizin.osce.domain.ChecklistCriteria; import ch.unibas.medizin.osce.domain.ChecklistOption; import ch.unibas.medizin.osce.domain.ChecklistQuestion; import ch.unibas.medizin.osce.domain.ChecklistTopic; import ch.unibas.medizin.osce.domain.StandardizedRole; import ch.unibas.medizin.osce.server.OsMaFilePathConstant; import ch.unibas.medizin.osce.server.bean.Oscedata; public class XmlUtil { private static Logger log = Logger.getLogger(XmlUtil.class); public XmlUtil(){ } public String writeXml(Long standardiedRoleId, OutputStream os) { try { StandardizedRole standardizedRole = StandardizedRole.findStandardizedRole(standardiedRoleId); CheckList checkList = standardizedRole.getCheckList(); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element pListElement = doc.createElement("plist"); doc.appendChild(pListElement); pListElement.setAttribute("version", "1.0"); Element rootElement = doc.createElement("dict"); pListElement.appendChild(rootElement); Element checklistTitle = doc.createElement("key"); checklistTitle.appendChild(doc.createTextNode("Title")); rootElement.appendChild(checklistTitle); Element checklistTitleValue = doc.createElement("string"); checklistTitleValue.appendChild(doc.createCDATASection(checkList.getTitle() == null ? "" : checkList.getTitle())); rootElement.appendChild(checklistTitleValue); Element checklistId = doc.createElement("key"); checklistId.appendChild(doc.createTextNode("FormId")); rootElement.appendChild(checklistId); Element checklistIdVal = doc.createElement("string"); checklistIdVal.appendChild(doc.createCDATASection(checkList.getId().toString())); rootElement.appendChild(checklistIdVal); Element topicKey = doc.createElement("key"); topicKey.appendChild(doc.createTextNode("Topics")); rootElement.appendChild(topicKey); Iterator<ChecklistTopic> checklistTopicItr = checkList.getCheckListTopics().iterator(); Element topicArray = doc.createElement("array"); rootElement.appendChild(topicArray); int ctr = 1; while (checklistTopicItr.hasNext()) { Element topicDict = doc.createElement("dict"); topicArray.appendChild(topicDict); ChecklistTopic checklistTopic = checklistTopicItr.next(); Element topicTitle = doc.createElement("key"); topicTitle.appendChild(doc.createTextNode("Title")); topicDict.appendChild(topicTitle); Element topicTitleVal = doc.createElement("string"); topicTitleVal.appendChild(doc.createCDATASection(checklistTopic.getTitle())); topicDict.appendChild(topicTitleVal); Element topicDesc = doc.createElement("key"); topicDesc.appendChild(doc.createTextNode("Instruction")); topicDict.appendChild(topicDesc); Element topicDescVal = doc.createElement("string"); topicDescVal.appendChild(doc.createCDATASection(checklistTopic.getDescription() == null ? "" : checklistTopic.getDescription())); topicDict.appendChild(topicDescVal); Element topicSeqNo = doc.createElement("key"); topicSeqNo.appendChild(doc.createTextNode("SequenceNumber")); topicDict.appendChild(topicSeqNo); Element topicSeqNoVal = doc.createElement("string"); topicSeqNoVal.appendChild(doc.createCDATASection(checklistTopic.getSort_order().toString())); topicDict.appendChild(topicSeqNoVal); Element queKey = doc.createElement("key"); queKey.appendChild(doc.createTextNode("Questions")); topicDict.appendChild(queKey); Element queArray = doc.createElement("array"); topicDict.appendChild(queArray); Iterator<ChecklistQuestion> queItr = checklistTopic.getCheckListQuestions().iterator(); while (queItr.hasNext()) { ChecklistQuestion checklistQuestion = queItr.next(); Element queDict = doc.createElement("dict"); queArray.appendChild(queDict); Element queProblem = doc.createElement("key"); queProblem.appendChild(doc.createTextNode("Problem")); queDict.appendChild(queProblem); Element queProblemVal = doc.createElement("string"); queProblemVal.appendChild(doc.createCDATASection(checklistQuestion.getQuestion())); queDict.appendChild(queProblemVal); Element queInst = doc.createElement("key"); queInst.appendChild(doc.createTextNode("Instruction")); queDict.appendChild(queInst); Element queInstVal = doc.createElement("string"); queInstVal.appendChild(doc.createCDATASection(checklistQuestion.getInstruction())); queDict.appendChild(queInstVal); Element queIsOverall = doc.createElement("key"); queIsOverall.appendChild(doc.createTextNode("isOverallQuestion")); queDict.appendChild(queIsOverall); Element queIsOverallVal = doc.createElement((checklistQuestion.getIsOveralQuestion() == null ? "false" : checklistQuestion.getIsOveralQuestion().toString())); queDict.appendChild(queIsOverallVal); Element hasAttachment = doc.createElement("key"); hasAttachment.appendChild(doc.createTextNode("hasAttachment")); queDict.appendChild(hasAttachment); Element hasAttachmentVal = doc.createElement("false"); queDict.appendChild(hasAttachmentVal); Element queSeqNo = doc.createElement("key"); queSeqNo.appendChild(doc.createTextNode("SequenceNumber")); queDict.appendChild(queSeqNo); Element queSeqNoVal = doc.createElement("string"); queSeqNoVal.appendChild(doc.createCDATASection(String.valueOf(ctr))); ctr++; //queSeqNoVal.appendChild(doc.createCDATASection(checklistQuestion.getSequenceNumber().toString())); queDict.appendChild(queSeqNoVal); Element optionKey = doc.createElement("key"); optionKey.appendChild(doc.createTextNode("Options")); queDict.appendChild(optionKey); Element optionArray = doc.createElement("array"); queDict.appendChild(optionArray); Iterator<ChecklistOption> optionIterator = checklistQuestion.getCheckListOptions().iterator(); while (optionIterator.hasNext()) { ChecklistOption checklistOption = optionIterator.next(); Element optionDict = doc.createElement("dict"); optionArray.appendChild(optionDict); Element optionTitle = doc.createElement("key"); optionTitle.appendChild(doc.createTextNode("Title")); optionDict.appendChild(optionTitle); Element optionTitleVal = doc.createElement("string"); optionTitleVal.appendChild(doc.createCDATASection(checklistOption.getOptionName())); optionDict.appendChild(optionTitleVal); Element optionSubTitle = doc.createElement("key"); optionSubTitle.appendChild(doc.createTextNode("Subtitle")); optionDict.appendChild(optionSubTitle); Element optionSubTitleVal = doc.createElement("string"); optionSubTitleVal.appendChild(doc.createCDATASection(checklistOption.getName() == null ? "" : checklistOption.getName())); optionDict.appendChild(optionSubTitleVal); Element optionValue = doc.createElement("key"); optionValue.appendChild(doc.createTextNode("Value")); optionDict.appendChild(optionValue); Element optionValueVal = doc.createElement("real"); optionValueVal.appendChild(doc.createTextNode(checklistOption.getValue() == null ? "0" : checklistOption.getValue())); optionDict.appendChild(optionValueVal); Element instTitle = doc.createElement("key"); instTitle.appendChild(doc.createTextNode("Instruction")); optionDict.appendChild(instTitle); Element instTitleValue = doc.createElement("string"); - instTitleValue.appendChild(doc.createCDATASection(checklistOption.getInstruction() == null ? "" : checklistOption.getInstruction())); + instTitleValue.appendChild(doc.createCDATASection(checklistOption.getDescription() == null ? "" : checklistOption.getDescription())); optionDict.appendChild(instTitleValue); Element criCountValue = doc.createElement("key"); criCountValue.appendChild(doc.createTextNode("criteriaCount")); optionDict.appendChild(criCountValue); Element criCountValueVal = doc.createElement("real"); criCountValueVal.appendChild(doc.createTextNode((checklistOption.getCriteriaCount() == null ? "0" : checklistOption.getCriteriaCount().toString()))); optionDict.appendChild(criCountValueVal); Element optionSeqNo = doc.createElement("key"); optionSeqNo.appendChild(doc.createTextNode("SequenceNumber")); optionDict.appendChild(optionSeqNo); Element optionSeqNoVal = doc.createElement("string"); optionSeqNoVal.appendChild(doc.createCDATASection(checklistOption.getSequenceNumber().toString())); optionDict.appendChild(optionSeqNoVal); } Element criteriaKey = doc.createElement("key"); criteriaKey.appendChild(doc.createTextNode("Criterias")); queDict.appendChild(criteriaKey); Element criteriaArray = doc.createElement("array"); queDict.appendChild(criteriaArray); Iterator<ChecklistCriteria> criIterator = checklistQuestion.getCheckListCriterias().iterator(); while (criIterator.hasNext()) { ChecklistCriteria checklistCriteria = criIterator.next(); Element criteriaDict = doc.createElement("dict"); criteriaArray.appendChild(criteriaDict); Element criteriaTitle = doc.createElement("key"); criteriaTitle.appendChild(doc.createTextNode("Title")); criteriaDict.appendChild(criteriaTitle); Element criteriaTitleVal = doc.createElement("string"); criteriaTitleVal.appendChild(doc.createCDATASection(checklistCriteria.getCriteria())); criteriaDict.appendChild(criteriaTitleVal); Element criteriaSeqNo = doc.createElement("key"); criteriaSeqNo.appendChild(doc.createTextNode("SequenceNumber")); criteriaDict.appendChild(criteriaSeqNo); Element criteriaSeqNoVal = doc.createElement("string"); criteriaSeqNoVal.appendChild(doc.createCDATASection(checklistCriteria.getSequenceNumber().toString())); criteriaDict.appendChild(criteriaSeqNoVal); } } } String path = "Checklist.osceform"; writeFile(doc, os); return path; } catch (Exception e) { log.error(e.getMessage(), e); } return null; } public void writeFile(Document doc, OutputStream os) { try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(os); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "Checklist.dtd"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3"); transformer.transform(source, result); } catch(Exception e) { log.error(e.getMessage(),e); } } public static void getnerateXMLFile(String fileName,Oscedata oscedata, org.apache.commons.io.output.ByteArrayOutputStream os){ log.info("getnerateXMLFile called at XmlUtil"); try { JAXBContext jaxbContext = JAXBContext.newInstance(Oscedata.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output pretty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); jaxbMarshaller.marshal(oscedata, stream); String data = new String(stream.toByteArray(),"UTF-8"); data = data.replaceAll("xsi:oscedata", "oscedata"); os.write(data.getBytes("UTF-8")); //FileUtils.writeStringToFile(file, data); }catch (Exception e) { e.printStackTrace(); } } }
true
true
public String writeXml(Long standardiedRoleId, OutputStream os) { try { StandardizedRole standardizedRole = StandardizedRole.findStandardizedRole(standardiedRoleId); CheckList checkList = standardizedRole.getCheckList(); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element pListElement = doc.createElement("plist"); doc.appendChild(pListElement); pListElement.setAttribute("version", "1.0"); Element rootElement = doc.createElement("dict"); pListElement.appendChild(rootElement); Element checklistTitle = doc.createElement("key"); checklistTitle.appendChild(doc.createTextNode("Title")); rootElement.appendChild(checklistTitle); Element checklistTitleValue = doc.createElement("string"); checklistTitleValue.appendChild(doc.createCDATASection(checkList.getTitle() == null ? "" : checkList.getTitle())); rootElement.appendChild(checklistTitleValue); Element checklistId = doc.createElement("key"); checklistId.appendChild(doc.createTextNode("FormId")); rootElement.appendChild(checklistId); Element checklistIdVal = doc.createElement("string"); checklistIdVal.appendChild(doc.createCDATASection(checkList.getId().toString())); rootElement.appendChild(checklistIdVal); Element topicKey = doc.createElement("key"); topicKey.appendChild(doc.createTextNode("Topics")); rootElement.appendChild(topicKey); Iterator<ChecklistTopic> checklistTopicItr = checkList.getCheckListTopics().iterator(); Element topicArray = doc.createElement("array"); rootElement.appendChild(topicArray); int ctr = 1; while (checklistTopicItr.hasNext()) { Element topicDict = doc.createElement("dict"); topicArray.appendChild(topicDict); ChecklistTopic checklistTopic = checklistTopicItr.next(); Element topicTitle = doc.createElement("key"); topicTitle.appendChild(doc.createTextNode("Title")); topicDict.appendChild(topicTitle); Element topicTitleVal = doc.createElement("string"); topicTitleVal.appendChild(doc.createCDATASection(checklistTopic.getTitle())); topicDict.appendChild(topicTitleVal); Element topicDesc = doc.createElement("key"); topicDesc.appendChild(doc.createTextNode("Instruction")); topicDict.appendChild(topicDesc); Element topicDescVal = doc.createElement("string"); topicDescVal.appendChild(doc.createCDATASection(checklistTopic.getDescription() == null ? "" : checklistTopic.getDescription())); topicDict.appendChild(topicDescVal); Element topicSeqNo = doc.createElement("key"); topicSeqNo.appendChild(doc.createTextNode("SequenceNumber")); topicDict.appendChild(topicSeqNo); Element topicSeqNoVal = doc.createElement("string"); topicSeqNoVal.appendChild(doc.createCDATASection(checklistTopic.getSort_order().toString())); topicDict.appendChild(topicSeqNoVal); Element queKey = doc.createElement("key"); queKey.appendChild(doc.createTextNode("Questions")); topicDict.appendChild(queKey); Element queArray = doc.createElement("array"); topicDict.appendChild(queArray); Iterator<ChecklistQuestion> queItr = checklistTopic.getCheckListQuestions().iterator(); while (queItr.hasNext()) { ChecklistQuestion checklistQuestion = queItr.next(); Element queDict = doc.createElement("dict"); queArray.appendChild(queDict); Element queProblem = doc.createElement("key"); queProblem.appendChild(doc.createTextNode("Problem")); queDict.appendChild(queProblem); Element queProblemVal = doc.createElement("string"); queProblemVal.appendChild(doc.createCDATASection(checklistQuestion.getQuestion())); queDict.appendChild(queProblemVal); Element queInst = doc.createElement("key"); queInst.appendChild(doc.createTextNode("Instruction")); queDict.appendChild(queInst); Element queInstVal = doc.createElement("string"); queInstVal.appendChild(doc.createCDATASection(checklistQuestion.getInstruction())); queDict.appendChild(queInstVal); Element queIsOverall = doc.createElement("key"); queIsOverall.appendChild(doc.createTextNode("isOverallQuestion")); queDict.appendChild(queIsOverall); Element queIsOverallVal = doc.createElement((checklistQuestion.getIsOveralQuestion() == null ? "false" : checklistQuestion.getIsOveralQuestion().toString())); queDict.appendChild(queIsOverallVal); Element hasAttachment = doc.createElement("key"); hasAttachment.appendChild(doc.createTextNode("hasAttachment")); queDict.appendChild(hasAttachment); Element hasAttachmentVal = doc.createElement("false"); queDict.appendChild(hasAttachmentVal); Element queSeqNo = doc.createElement("key"); queSeqNo.appendChild(doc.createTextNode("SequenceNumber")); queDict.appendChild(queSeqNo); Element queSeqNoVal = doc.createElement("string"); queSeqNoVal.appendChild(doc.createCDATASection(String.valueOf(ctr))); ctr++; //queSeqNoVal.appendChild(doc.createCDATASection(checklistQuestion.getSequenceNumber().toString())); queDict.appendChild(queSeqNoVal); Element optionKey = doc.createElement("key"); optionKey.appendChild(doc.createTextNode("Options")); queDict.appendChild(optionKey); Element optionArray = doc.createElement("array"); queDict.appendChild(optionArray); Iterator<ChecklistOption> optionIterator = checklistQuestion.getCheckListOptions().iterator(); while (optionIterator.hasNext()) { ChecklistOption checklistOption = optionIterator.next(); Element optionDict = doc.createElement("dict"); optionArray.appendChild(optionDict); Element optionTitle = doc.createElement("key"); optionTitle.appendChild(doc.createTextNode("Title")); optionDict.appendChild(optionTitle); Element optionTitleVal = doc.createElement("string"); optionTitleVal.appendChild(doc.createCDATASection(checklistOption.getOptionName())); optionDict.appendChild(optionTitleVal); Element optionSubTitle = doc.createElement("key"); optionSubTitle.appendChild(doc.createTextNode("Subtitle")); optionDict.appendChild(optionSubTitle); Element optionSubTitleVal = doc.createElement("string"); optionSubTitleVal.appendChild(doc.createCDATASection(checklistOption.getName() == null ? "" : checklistOption.getName())); optionDict.appendChild(optionSubTitleVal); Element optionValue = doc.createElement("key"); optionValue.appendChild(doc.createTextNode("Value")); optionDict.appendChild(optionValue); Element optionValueVal = doc.createElement("real"); optionValueVal.appendChild(doc.createTextNode(checklistOption.getValue() == null ? "0" : checklistOption.getValue())); optionDict.appendChild(optionValueVal); Element instTitle = doc.createElement("key"); instTitle.appendChild(doc.createTextNode("Instruction")); optionDict.appendChild(instTitle); Element instTitleValue = doc.createElement("string"); instTitleValue.appendChild(doc.createCDATASection(checklistOption.getInstruction() == null ? "" : checklistOption.getInstruction())); optionDict.appendChild(instTitleValue); Element criCountValue = doc.createElement("key"); criCountValue.appendChild(doc.createTextNode("criteriaCount")); optionDict.appendChild(criCountValue); Element criCountValueVal = doc.createElement("real"); criCountValueVal.appendChild(doc.createTextNode((checklistOption.getCriteriaCount() == null ? "0" : checklistOption.getCriteriaCount().toString()))); optionDict.appendChild(criCountValueVal); Element optionSeqNo = doc.createElement("key"); optionSeqNo.appendChild(doc.createTextNode("SequenceNumber")); optionDict.appendChild(optionSeqNo); Element optionSeqNoVal = doc.createElement("string"); optionSeqNoVal.appendChild(doc.createCDATASection(checklistOption.getSequenceNumber().toString())); optionDict.appendChild(optionSeqNoVal); } Element criteriaKey = doc.createElement("key"); criteriaKey.appendChild(doc.createTextNode("Criterias")); queDict.appendChild(criteriaKey); Element criteriaArray = doc.createElement("array"); queDict.appendChild(criteriaArray); Iterator<ChecklistCriteria> criIterator = checklistQuestion.getCheckListCriterias().iterator(); while (criIterator.hasNext()) { ChecklistCriteria checklistCriteria = criIterator.next(); Element criteriaDict = doc.createElement("dict"); criteriaArray.appendChild(criteriaDict); Element criteriaTitle = doc.createElement("key"); criteriaTitle.appendChild(doc.createTextNode("Title")); criteriaDict.appendChild(criteriaTitle); Element criteriaTitleVal = doc.createElement("string"); criteriaTitleVal.appendChild(doc.createCDATASection(checklistCriteria.getCriteria())); criteriaDict.appendChild(criteriaTitleVal); Element criteriaSeqNo = doc.createElement("key"); criteriaSeqNo.appendChild(doc.createTextNode("SequenceNumber")); criteriaDict.appendChild(criteriaSeqNo); Element criteriaSeqNoVal = doc.createElement("string"); criteriaSeqNoVal.appendChild(doc.createCDATASection(checklistCriteria.getSequenceNumber().toString())); criteriaDict.appendChild(criteriaSeqNoVal); } } } String path = "Checklist.osceform"; writeFile(doc, os); return path; } catch (Exception e) { log.error(e.getMessage(), e); } return null; }
public String writeXml(Long standardiedRoleId, OutputStream os) { try { StandardizedRole standardizedRole = StandardizedRole.findStandardizedRole(standardiedRoleId); CheckList checkList = standardizedRole.getCheckList(); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element pListElement = doc.createElement("plist"); doc.appendChild(pListElement); pListElement.setAttribute("version", "1.0"); Element rootElement = doc.createElement("dict"); pListElement.appendChild(rootElement); Element checklistTitle = doc.createElement("key"); checklistTitle.appendChild(doc.createTextNode("Title")); rootElement.appendChild(checklistTitle); Element checklistTitleValue = doc.createElement("string"); checklistTitleValue.appendChild(doc.createCDATASection(checkList.getTitle() == null ? "" : checkList.getTitle())); rootElement.appendChild(checklistTitleValue); Element checklistId = doc.createElement("key"); checklistId.appendChild(doc.createTextNode("FormId")); rootElement.appendChild(checklistId); Element checklistIdVal = doc.createElement("string"); checklistIdVal.appendChild(doc.createCDATASection(checkList.getId().toString())); rootElement.appendChild(checklistIdVal); Element topicKey = doc.createElement("key"); topicKey.appendChild(doc.createTextNode("Topics")); rootElement.appendChild(topicKey); Iterator<ChecklistTopic> checklistTopicItr = checkList.getCheckListTopics().iterator(); Element topicArray = doc.createElement("array"); rootElement.appendChild(topicArray); int ctr = 1; while (checklistTopicItr.hasNext()) { Element topicDict = doc.createElement("dict"); topicArray.appendChild(topicDict); ChecklistTopic checklistTopic = checklistTopicItr.next(); Element topicTitle = doc.createElement("key"); topicTitle.appendChild(doc.createTextNode("Title")); topicDict.appendChild(topicTitle); Element topicTitleVal = doc.createElement("string"); topicTitleVal.appendChild(doc.createCDATASection(checklistTopic.getTitle())); topicDict.appendChild(topicTitleVal); Element topicDesc = doc.createElement("key"); topicDesc.appendChild(doc.createTextNode("Instruction")); topicDict.appendChild(topicDesc); Element topicDescVal = doc.createElement("string"); topicDescVal.appendChild(doc.createCDATASection(checklistTopic.getDescription() == null ? "" : checklistTopic.getDescription())); topicDict.appendChild(topicDescVal); Element topicSeqNo = doc.createElement("key"); topicSeqNo.appendChild(doc.createTextNode("SequenceNumber")); topicDict.appendChild(topicSeqNo); Element topicSeqNoVal = doc.createElement("string"); topicSeqNoVal.appendChild(doc.createCDATASection(checklistTopic.getSort_order().toString())); topicDict.appendChild(topicSeqNoVal); Element queKey = doc.createElement("key"); queKey.appendChild(doc.createTextNode("Questions")); topicDict.appendChild(queKey); Element queArray = doc.createElement("array"); topicDict.appendChild(queArray); Iterator<ChecklistQuestion> queItr = checklistTopic.getCheckListQuestions().iterator(); while (queItr.hasNext()) { ChecklistQuestion checklistQuestion = queItr.next(); Element queDict = doc.createElement("dict"); queArray.appendChild(queDict); Element queProblem = doc.createElement("key"); queProblem.appendChild(doc.createTextNode("Problem")); queDict.appendChild(queProblem); Element queProblemVal = doc.createElement("string"); queProblemVal.appendChild(doc.createCDATASection(checklistQuestion.getQuestion())); queDict.appendChild(queProblemVal); Element queInst = doc.createElement("key"); queInst.appendChild(doc.createTextNode("Instruction")); queDict.appendChild(queInst); Element queInstVal = doc.createElement("string"); queInstVal.appendChild(doc.createCDATASection(checklistQuestion.getInstruction())); queDict.appendChild(queInstVal); Element queIsOverall = doc.createElement("key"); queIsOverall.appendChild(doc.createTextNode("isOverallQuestion")); queDict.appendChild(queIsOverall); Element queIsOverallVal = doc.createElement((checklistQuestion.getIsOveralQuestion() == null ? "false" : checklistQuestion.getIsOveralQuestion().toString())); queDict.appendChild(queIsOverallVal); Element hasAttachment = doc.createElement("key"); hasAttachment.appendChild(doc.createTextNode("hasAttachment")); queDict.appendChild(hasAttachment); Element hasAttachmentVal = doc.createElement("false"); queDict.appendChild(hasAttachmentVal); Element queSeqNo = doc.createElement("key"); queSeqNo.appendChild(doc.createTextNode("SequenceNumber")); queDict.appendChild(queSeqNo); Element queSeqNoVal = doc.createElement("string"); queSeqNoVal.appendChild(doc.createCDATASection(String.valueOf(ctr))); ctr++; //queSeqNoVal.appendChild(doc.createCDATASection(checklistQuestion.getSequenceNumber().toString())); queDict.appendChild(queSeqNoVal); Element optionKey = doc.createElement("key"); optionKey.appendChild(doc.createTextNode("Options")); queDict.appendChild(optionKey); Element optionArray = doc.createElement("array"); queDict.appendChild(optionArray); Iterator<ChecklistOption> optionIterator = checklistQuestion.getCheckListOptions().iterator(); while (optionIterator.hasNext()) { ChecklistOption checklistOption = optionIterator.next(); Element optionDict = doc.createElement("dict"); optionArray.appendChild(optionDict); Element optionTitle = doc.createElement("key"); optionTitle.appendChild(doc.createTextNode("Title")); optionDict.appendChild(optionTitle); Element optionTitleVal = doc.createElement("string"); optionTitleVal.appendChild(doc.createCDATASection(checklistOption.getOptionName())); optionDict.appendChild(optionTitleVal); Element optionSubTitle = doc.createElement("key"); optionSubTitle.appendChild(doc.createTextNode("Subtitle")); optionDict.appendChild(optionSubTitle); Element optionSubTitleVal = doc.createElement("string"); optionSubTitleVal.appendChild(doc.createCDATASection(checklistOption.getName() == null ? "" : checklistOption.getName())); optionDict.appendChild(optionSubTitleVal); Element optionValue = doc.createElement("key"); optionValue.appendChild(doc.createTextNode("Value")); optionDict.appendChild(optionValue); Element optionValueVal = doc.createElement("real"); optionValueVal.appendChild(doc.createTextNode(checklistOption.getValue() == null ? "0" : checklistOption.getValue())); optionDict.appendChild(optionValueVal); Element instTitle = doc.createElement("key"); instTitle.appendChild(doc.createTextNode("Instruction")); optionDict.appendChild(instTitle); Element instTitleValue = doc.createElement("string"); instTitleValue.appendChild(doc.createCDATASection(checklistOption.getDescription() == null ? "" : checklistOption.getDescription())); optionDict.appendChild(instTitleValue); Element criCountValue = doc.createElement("key"); criCountValue.appendChild(doc.createTextNode("criteriaCount")); optionDict.appendChild(criCountValue); Element criCountValueVal = doc.createElement("real"); criCountValueVal.appendChild(doc.createTextNode((checklistOption.getCriteriaCount() == null ? "0" : checklistOption.getCriteriaCount().toString()))); optionDict.appendChild(criCountValueVal); Element optionSeqNo = doc.createElement("key"); optionSeqNo.appendChild(doc.createTextNode("SequenceNumber")); optionDict.appendChild(optionSeqNo); Element optionSeqNoVal = doc.createElement("string"); optionSeqNoVal.appendChild(doc.createCDATASection(checklistOption.getSequenceNumber().toString())); optionDict.appendChild(optionSeqNoVal); } Element criteriaKey = doc.createElement("key"); criteriaKey.appendChild(doc.createTextNode("Criterias")); queDict.appendChild(criteriaKey); Element criteriaArray = doc.createElement("array"); queDict.appendChild(criteriaArray); Iterator<ChecklistCriteria> criIterator = checklistQuestion.getCheckListCriterias().iterator(); while (criIterator.hasNext()) { ChecklistCriteria checklistCriteria = criIterator.next(); Element criteriaDict = doc.createElement("dict"); criteriaArray.appendChild(criteriaDict); Element criteriaTitle = doc.createElement("key"); criteriaTitle.appendChild(doc.createTextNode("Title")); criteriaDict.appendChild(criteriaTitle); Element criteriaTitleVal = doc.createElement("string"); criteriaTitleVal.appendChild(doc.createCDATASection(checklistCriteria.getCriteria())); criteriaDict.appendChild(criteriaTitleVal); Element criteriaSeqNo = doc.createElement("key"); criteriaSeqNo.appendChild(doc.createTextNode("SequenceNumber")); criteriaDict.appendChild(criteriaSeqNo); Element criteriaSeqNoVal = doc.createElement("string"); criteriaSeqNoVal.appendChild(doc.createCDATASection(checklistCriteria.getSequenceNumber().toString())); criteriaDict.appendChild(criteriaSeqNoVal); } } } String path = "Checklist.osceform"; writeFile(doc, os); return path; } catch (Exception e) { log.error(e.getMessage(), e); } return null; }
diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/DiffTreeChangesSection.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/DiffTreeChangesSection.java index dcb310047..04e675f33 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/DiffTreeChangesSection.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/DiffTreeChangesSection.java @@ -1,581 +1,582 @@ /******************************************************************************* * Copyright (c) 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.ui.mapping; import java.util.*; import java.util.List; import org.eclipse.core.resources.mapping.*; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.*; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.preference.PreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; import org.eclipse.team.core.diff.*; import org.eclipse.team.core.mapping.ISynchronizationContext; import org.eclipse.team.core.mapping.ISynchronizationScope; import org.eclipse.team.internal.core.subscribers.SubscriberDiffTreeEventHandler; import org.eclipse.team.internal.ui.*; import org.eclipse.team.internal.ui.synchronize.*; import org.eclipse.team.ui.ISharedImages; import org.eclipse.team.ui.TeamUI; import org.eclipse.team.ui.mapping.*; import org.eclipse.team.ui.synchronize.*; import org.eclipse.ui.forms.events.HyperlinkAdapter; import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.forms.widgets.Hyperlink; public class DiffTreeChangesSection extends ForwardingChangesSection implements IDiffChangeListener, IPropertyChangeListener, IEmptyTreeListener { private ISynchronizationContext context; private IStatus[] errors; private boolean showingError; public interface ITraversalFactory { ResourceTraversal[] getTraversals(ISynchronizationScope scope); } public DiffTreeChangesSection(Composite parent, AbstractSynchronizePage page, ISynchronizePageConfiguration configuration) { super(parent, page, configuration); context = (ISynchronizationContext)configuration.getProperty(ITeamContentProviderManager.P_SYNCHRONIZATION_CONTEXT); context.getDiffTree().addDiffChangeListener(this); getConfiguration().addPropertyChangeListener(this); Platform.getJobManager().addJobChangeListener(new JobChangeAdapter() { public void running(IJobChangeEvent event) { if (isJobOfInterest(event.getJob())) { if (context.getDiffTree().isEmpty()) calculateDescription(); } } private boolean isJobOfInterest(Job job) { if (job.belongsTo(getConfiguration().getParticipant())) return true; SubscriberDiffTreeEventHandler handler = getHandler(); if (handler != null && handler.getEventHandlerJob() == job) return true; return false; } public void done(IJobChangeEvent event) { if (isJobOfInterest(event.getJob())) { if (context.getDiffTree().isEmpty()) calculateDescription(); } } }); } public void dispose() { context.getDiffTree().removeDiffChangeListener(this); getConfiguration().removePropertyChangeListener(this); super.dispose(); } protected int getChangesCount() { return context.getDiffTree().size(); } protected long getChangesInMode(int candidateMode) { long numChanges; long numConflicts = context.getDiffTree().countFor(IThreeWayDiff.CONFLICTING, IThreeWayDiff.DIRECTION_MASK); switch (candidateMode) { case ISynchronizePageConfiguration.CONFLICTING_MODE: numChanges = numConflicts; break; case ISynchronizePageConfiguration.OUTGOING_MODE: numChanges = numConflicts + context.getDiffTree().countFor(IThreeWayDiff.OUTGOING, IThreeWayDiff.DIRECTION_MASK); break; case ISynchronizePageConfiguration.INCOMING_MODE: numChanges = numConflicts + context.getDiffTree().countFor(IThreeWayDiff.INCOMING, IThreeWayDiff.DIRECTION_MASK); break; case ISynchronizePageConfiguration.BOTH_MODE: numChanges = numConflicts + context.getDiffTree().countFor(IThreeWayDiff.INCOMING, IThreeWayDiff.DIRECTION_MASK) + context.getDiffTree().countFor(IThreeWayDiff.OUTGOING, IThreeWayDiff.DIRECTION_MASK); break; default: numChanges = 0; break; } return numChanges; } protected boolean hasChangesInMode(String id, ISynchronizationCompareAdapter adapter, int candidateMode) { switch (candidateMode) { case ISynchronizePageConfiguration.CONFLICTING_MODE: return hasChangesFor(id, adapter, context, new int[] { IThreeWayDiff.CONFLICTING }, IThreeWayDiff.DIRECTION_MASK); case ISynchronizePageConfiguration.OUTGOING_MODE: return hasChangesFor(id, adapter, context, new int[] { IThreeWayDiff.CONFLICTING, IThreeWayDiff.OUTGOING }, IThreeWayDiff.DIRECTION_MASK); case ISynchronizePageConfiguration.INCOMING_MODE: return hasChangesFor(id, adapter, context, new int[] { IThreeWayDiff.CONFLICTING, IThreeWayDiff.INCOMING }, IThreeWayDiff.DIRECTION_MASK); case ISynchronizePageConfiguration.BOTH_MODE: return hasChangesFor(id, adapter, context, new int[] { IThreeWayDiff.CONFLICTING, IThreeWayDiff.INCOMING, IThreeWayDiff.OUTGOING }, IThreeWayDiff.DIRECTION_MASK); } return false; } private boolean hasChangesFor(String id, ISynchronizationCompareAdapter adapter, ISynchronizationContext context, int[] states, int mask) { ITraversalFactory factory = (ITraversalFactory)Utils.getAdapter(adapter, ITraversalFactory.class); ResourceTraversal[] traversals; if (factory == null) { traversals = context.getScope().getTraversals(id); } else { traversals = factory.getTraversals(context.getScope()); } return (context.getDiffTree().hasMatchingDiffs(traversals, FastDiffFilter.getStateFilter(states, mask))); } protected long getVisibleChangesCount() { ISynchronizePageConfiguration configuration = getConfiguration(); if (configuration.getComparisonType() == ISynchronizePageConfiguration.TWO_WAY) { return context.getDiffTree().size(); } int currentMode = configuration.getMode(); String id = (String)configuration.getProperty(ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER); if (id != null && !id.equals(ModelSynchronizeParticipant.ALL_MODEL_PROVIDERS_VISIBLE)) { try { IModelProviderDescriptor desc = ModelProvider.getModelProviderDescriptor(id); ISynchronizationCompareAdapter adapter = Utils.getCompareAdapter(desc.getModelProvider()); if (adapter != null) { return hasChangesInMode(desc.getId(), adapter, getConfiguration().getMode()) ? -1 : 0; } } catch (CoreException e) { TeamUIPlugin.log(e); } // Use the view state to indicate whether there are visible changes return isViewerEmpty() ? 0 : -1; } return getChangesInMode(currentMode); } protected int getCandidateMode() { SynchronizePageConfiguration configuration = (SynchronizePageConfiguration)getConfiguration(); long outgoingChanges = context.getDiffTree().countFor(IThreeWayDiff.OUTGOING, IThreeWayDiff.DIRECTION_MASK); if (outgoingChanges > 0) { if (configuration.isModeSupported(ISynchronizePageConfiguration.OUTGOING_MODE)) { return ISynchronizePageConfiguration.OUTGOING_MODE; } if (configuration.isModeSupported(ISynchronizePageConfiguration.BOTH_MODE)) { return ISynchronizePageConfiguration.BOTH_MODE; } } long incomingChanges = context.getDiffTree().countFor(IThreeWayDiff.INCOMING, IThreeWayDiff.DIRECTION_MASK); if (incomingChanges > 0) { if (configuration.isModeSupported(ISynchronizePageConfiguration.INCOMING_MODE)) { return ISynchronizePageConfiguration.INCOMING_MODE; } if (configuration.isModeSupported(ISynchronizePageConfiguration.BOTH_MODE)) { return ISynchronizePageConfiguration.BOTH_MODE; } } return configuration.getMode(); } public void diffsChanged(IDiffChangeEvent event, IProgressMonitor monitor) { IStatus[] errors = event.getErrors(); if (errors.length > 0) { this.errors = errors; } calculateDescription(); } /* (non-Javadoc) * @see org.eclipse.team.core.diff.IDiffChangeListener#propertyChanged(int, org.eclipse.core.runtime.IPath[]) */ public void propertyChanged(IDiffTree tree, int property, IPath[] paths) { // Do nothing } public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(ISynchronizePageConfiguration.P_MODE) || event.getProperty().equals(ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER)) { calculateDescription(); } } protected Composite getEmptyChangesComposite(Composite parent) { if (context.getDiffTree().isEmpty()) { SubscriberDiffTreeEventHandler handler = getHandler(); if (handler != null && handler.getState() == SubscriberDiffTreeEventHandler.STATE_STARTED) { // The context has not been initialized yet return getInitializationPane(parent); } if (isRefreshRunning() || (handler != null && handler.getEventHandlerJob().getState() != Job.NONE)) { return getInitializingMessagePane(parent); } } else { ISynchronizePageConfiguration configuration = getConfiguration(); String id = (String)configuration.getProperty(ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER); if (id == null) id = ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER; if (id.equals(ModelSynchronizeParticipant.ALL_MODEL_PROVIDERS_VISIBLE)) { if (getChangesInMode(getConfiguration().getMode()) > 0 && isAtLeastOneProviderDisabled()) { // There are changes in this mode but they are not visible so enable // all providers return createEnableParticipantModelProvidersPane(parent); } } else { // A particular model is active so we need to look for a model that has changes in this // same mode before offering to change modes. ModelProvider[] providers =findModelsWithChangesInMode(getConfiguration().getMode()); ModelProvider currentProvider = null; for (int i = 0; i < providers.length; i++) { ModelProvider provider = providers[i]; if (isEnabled(provider)) { if (provider.getDescriptor().getId().equals(id)) { currentProvider = provider; } else { return getPointerToModel(parent, provider, id); } } } if (currentProvider != null || providers.length > 0) { // The current provider has changes but the view is empty // or there is a disabled provider with changes // This is an error so offer to enable and show all models return createEnableParticipantModelProvidersPane(parent); } } } return super.getEmptyChangesComposite(parent); } private boolean isAtLeastOneProviderDisabled() { ModelProvider[] providers =findModelsWithChangesInMode(getConfiguration().getMode()); for (int i = 0; i < providers.length; i++) { ModelProvider provider = providers[i]; if (!isEnabled(provider)) { return true; } } return false; } private ModelProvider[] findModelsWithChangesInMode(int mode) { ModelProvider[] providers =context.getScope().getModelProviders(); providers = ModelOperation.sortByExtension(providers); List result = new ArrayList(); for (int i = 0; i < providers.length; i++) { ModelProvider provider = providers[i]; ISynchronizationCompareAdapter adapter = Utils.getCompareAdapter(provider); if (adapter != null) { boolean hasChanges = hasChangesInMode(provider.getId(), adapter, getConfiguration().getMode()); if (hasChanges) { result.add(provider); } } } return (ModelProvider[]) result.toArray(new ModelProvider[result.size()]); } private boolean isEnabled(ModelProvider provider) { ITeamContentProviderDescriptor desc = TeamUI.getTeamContentProviderManager().getDescriptor(provider.getId()); return (desc != null && desc.isEnabled()); } private Composite createEnableParticipantModelProvidersPane(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setBackground(getBackgroundColor()); GridLayout layout = new GridLayout(); layout.numColumns = 2; composite.setLayout(layout); GridData data = new GridData(GridData.FILL_BOTH); data.grabExcessVerticalSpace = true; composite.setLayoutData(data); String message; int changesCount = getChangesCount(); if (changesCount == 1) { message = TeamUIMessages.DiffTreeChangesSection_8; } else { message = NLS.bind(TeamUIMessages.DiffTreeChangesSection_9, new Integer(changesCount)); } final ITeamContentProviderDescriptor[] descriptors = getEnabledContentDescriptors(); if (descriptors.length == 0) message = NLS.bind(TeamUIMessages.DiffTreeChangesSection_10, message); else message = NLS.bind(TeamUIMessages.DiffTreeChangesSection_11, message); createDescriptionLabel(composite, message); Label warning = new Label(composite, SWT.NONE); warning.setImage(TeamUIPlugin.getPlugin().getImage(ISharedImages.IMG_WARNING_OVR)); Hyperlink link = getForms().createHyperlink(composite, TeamUIMessages.DiffTreeChangesSection_12, SWT.WRAP); link.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { ModelSynchronizeParticipant participant = (ModelSynchronizeParticipant)getConfiguration().getParticipant(); ModelProvider[] providers = participant.getEnabledModelProviders(); Set toEnable = new HashSet(); toEnable.addAll(Arrays.asList(descriptors)); for (int i = 0; i < providers.length; i++) { ModelProvider provider = providers[i]; ITeamContentProviderDescriptor desc = TeamUI.getTeamContentProviderManager().getDescriptor(provider.getId()); if (desc != null && !desc.isEnabled()) { toEnable.add(desc); } } TeamUI.getTeamContentProviderManager().setEnabledDescriptors( (ITeamContentProviderDescriptor[]) toEnable .toArray(new ITeamContentProviderDescriptor[toEnable.size()])); getConfiguration().setProperty(ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER, ModelSynchronizeParticipant.ALL_MODEL_PROVIDERS_VISIBLE ); } }); getForms().getHyperlinkGroup().add(link); return composite; } private ITeamContentProviderDescriptor[] getEnabledContentDescriptors() { ModelSynchronizeParticipant participant = (ModelSynchronizeParticipant)getConfiguration().getParticipant(); ModelProvider[] providers = participant.getEnabledModelProviders(); Set result = new HashSet(); for (int i = 0; i < providers.length; i++) { ModelProvider provider = providers[i]; ITeamContentProviderDescriptor desc = TeamUI.getTeamContentProviderManager().getDescriptor(provider.getId()); if (desc != null && desc.isEnabled()) result.add(desc); } return (ITeamContentProviderDescriptor[]) result.toArray(new ITeamContentProviderDescriptor[result.size()]); } private Composite getInitializationPane(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setBackground(getBackgroundColor()); GridLayout layout = new GridLayout(); layout.numColumns = 2; composite.setLayout(layout); GridData data = new GridData(GridData.FILL_BOTH); data.grabExcessVerticalSpace = true; composite.setLayoutData(data); createDescriptionLabel(composite, NLS.bind(TeamUIMessages.DiffTreeChangesSection_3, new String[] { Utils.shortenText(SynchronizeView.MAX_NAME_LENGTH, getConfiguration().getParticipant().getName()) })); final boolean[] remember = new boolean[] { false }; final PreferenceStore store = (PreferenceStore) getConfiguration() .getProperty(StartupPreferencePage.STARTUP_PREFERENCES); Hyperlink link = getForms().createHyperlink(composite, TeamUIMessages.DiffTreeChangesSection_4, SWT.WRAP); link.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { if (remember[0] && store != null) { store.putValue(StartupPreferencePage.PROP_STARTUP_ACTION, StartupPreferencePage.STARTUP_ACTION_POPULATE); } getHandler().initializeIfNeeded(); } }); getForms().getHyperlinkGroup().add(link); link = getForms().createHyperlink(composite, TeamUIMessages.DiffTreeChangesSection_5, SWT.WRAP); link.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { if (remember[0] && store != null) { store.putValue(StartupPreferencePage.PROP_STARTUP_ACTION, StartupPreferencePage.STARTUP_ACTION_SYNCHRONIZE); } getConfiguration().getParticipant().run(getConfiguration().getSite().getPart()); } }); getForms().getHyperlinkGroup().add(link); if (store != null) { final Button rememberButton = getForms().createButton(composite, TeamUIMessages.DiffTreeChangesSection_14, SWT.CHECK); + rememberButton.setToolTipText(TeamUIMessages.DiffTreeChangesSection_14); data = new GridData(GridData.FILL_HORIZONTAL); data.horizontalSpan = 2; data.horizontalIndent=5; data.verticalIndent=5; data.widthHint = 100; rememberButton.setLayoutData(data); rememberButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { remember[0] = rememberButton.getSelection(); } public void widgetDefaultSelected(SelectionEvent e) { // Do nothing } }); } return composite; } private Composite getInitializingMessagePane(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setBackground(getBackgroundColor()); GridLayout layout = new GridLayout(); layout.numColumns = 2; composite.setLayout(layout); GridData data = new GridData(GridData.FILL_BOTH); data.grabExcessVerticalSpace = true; composite.setLayoutData(data); if (isRefreshRunning()) { createDescriptionLabel(composite,NLS.bind(TeamUIMessages.DiffTreeChangesSection_6, new String[] { Utils.shortenText(SynchronizeView.MAX_NAME_LENGTH, getConfiguration().getParticipant().getName()) })); } else { createDescriptionLabel(composite,NLS.bind(TeamUIMessages.DiffTreeChangesSection_7, new String[] { Utils.shortenText(SynchronizeView.MAX_NAME_LENGTH, getConfiguration().getParticipant().getName()) })); } return composite; } private boolean isRefreshRunning() { return Platform.getJobManager().find(getConfiguration().getParticipant()).length > 0; } private SubscriberDiffTreeEventHandler getHandler() { return (SubscriberDiffTreeEventHandler)Utils.getAdapter(context, SubscriberDiffTreeEventHandler.class); } private Composite getPointerToModel(Composite parent, final ModelProvider provider, String oldId) { Composite composite = new Composite(parent, SWT.NONE); composite.setBackground(getBackgroundColor()); GridLayout layout = new GridLayout(); layout.numColumns = 2; composite.setLayout(layout); GridData data = new GridData(GridData.FILL_BOTH); data.grabExcessVerticalSpace = true; composite.setLayoutData(data); IModelProviderDescriptor oldDesc = ModelProvider.getModelProviderDescriptor(oldId); String message; String modeToString = Utils.modeToString(getConfiguration().getMode()); message = NLS.bind(TeamUIMessages.DiffTreeChangesSection_0, new String[] { provider.getDescriptor().getLabel(), modeToString }); message = NLS.bind(TeamUIMessages.DiffTreeChangesSection_1, new String[] { modeToString, oldDesc.getLabel(), message }); createDescriptionLabel(composite, message); Label warning = new Label(composite, SWT.NONE); warning.setImage(TeamUIPlugin.getPlugin().getImage(ISharedImages.IMG_WARNING_OVR)); Hyperlink link = getForms().createHyperlink(composite, NLS.bind(TeamUIMessages.DiffTreeChangesSection_2, new String[] { provider.getDescriptor().getLabel() }), SWT.WRAP); link.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { getConfiguration().setProperty(ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER, provider.getDescriptor().getId() ); } }); getForms().getHyperlinkGroup().add(link); new Label(composite, SWT.NONE); Hyperlink link2 = getForms().createHyperlink(composite, TeamUIMessages.DiffTreeChangesSection_13, SWT.WRAP); link2.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { getConfiguration().setProperty(ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER, ModelSynchronizeParticipant.ALL_MODEL_PROVIDERS_VISIBLE ); } }); getForms().getHyperlinkGroup().add(link2); return composite; } public void treeEmpty(TreeViewer viewer) { handleEmptyViewer(); } private void handleEmptyViewer() { // Override stand behavior to do our best to show something TeamUIPlugin.getStandardDisplay().asyncExec(new Runnable() { public void run() { if (!getContainer().isDisposed()) updatePage(getEmptyChangesComposite(getContainer())); } }); } protected void calculateDescription() { if (errors != null && errors.length > 0) { if (!showingError) { TeamUIPlugin.getStandardDisplay().asyncExec(new Runnable() { public void run() { updatePage(getErrorComposite(getContainer())); showingError = true; } }); } return; } showingError = false; if (isViewerEmpty()) { handleEmptyViewer(); } else { super.calculateDescription(); } } private boolean isViewerEmpty() { Viewer v = getPage().getViewer(); if (v instanceof CommonViewerAdvisor.NavigableCommonViewer) { CommonViewerAdvisor.NavigableCommonViewer cv = (CommonViewerAdvisor.NavigableCommonViewer) v; return cv.isEmpty(); } return false; } public void notEmpty(TreeViewer viewer) { calculateDescription(); } private Composite getErrorComposite(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setBackground(getBackgroundColor()); GridLayout layout = new GridLayout(); layout.numColumns = 2; composite.setLayout(layout); GridData data = new GridData(GridData.FILL_BOTH); data.grabExcessVerticalSpace = true; composite.setLayoutData(data); createDescriptionLabel(composite, NLS.bind(TeamUIMessages.ChangesSection_10, new String[] { Utils.shortenText(SynchronizeView.MAX_NAME_LENGTH, getConfiguration().getParticipant().getName()) })); Hyperlink link = getForms().createHyperlink(composite, TeamUIMessages.ChangesSection_8, SWT.WRAP); link.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { showErrors(); } }); getForms().getHyperlinkGroup().add(link); link = getForms().createHyperlink(composite, TeamUIMessages.ChangesSection_9, SWT.WRAP); link.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { errors = null; calculateDescription(); SubscriberDiffTreeEventHandler handler = getHandler(); if (handler != null) handler.initializeIfNeeded(); else getConfiguration().getParticipant().run(getConfiguration().getSite().getPart()); } }); getForms().getHyperlinkGroup().add(link); return composite; } /* private */ void showErrors() { if (errors != null) { IStatus[] status = errors; String title = TeamUIMessages.ChangesSection_11; if (status.length == 1) { ErrorDialog.openError(getShell(), title, status[0].getMessage(), status[0]); } else { MultiStatus multi = new MultiStatus(TeamUIPlugin.ID, 0, status, TeamUIMessages.ChangesSection_12, null); ErrorDialog.openError(getShell(), title, null, multi); } } } }
true
true
private Composite getInitializationPane(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setBackground(getBackgroundColor()); GridLayout layout = new GridLayout(); layout.numColumns = 2; composite.setLayout(layout); GridData data = new GridData(GridData.FILL_BOTH); data.grabExcessVerticalSpace = true; composite.setLayoutData(data); createDescriptionLabel(composite, NLS.bind(TeamUIMessages.DiffTreeChangesSection_3, new String[] { Utils.shortenText(SynchronizeView.MAX_NAME_LENGTH, getConfiguration().getParticipant().getName()) })); final boolean[] remember = new boolean[] { false }; final PreferenceStore store = (PreferenceStore) getConfiguration() .getProperty(StartupPreferencePage.STARTUP_PREFERENCES); Hyperlink link = getForms().createHyperlink(composite, TeamUIMessages.DiffTreeChangesSection_4, SWT.WRAP); link.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { if (remember[0] && store != null) { store.putValue(StartupPreferencePage.PROP_STARTUP_ACTION, StartupPreferencePage.STARTUP_ACTION_POPULATE); } getHandler().initializeIfNeeded(); } }); getForms().getHyperlinkGroup().add(link); link = getForms().createHyperlink(composite, TeamUIMessages.DiffTreeChangesSection_5, SWT.WRAP); link.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { if (remember[0] && store != null) { store.putValue(StartupPreferencePage.PROP_STARTUP_ACTION, StartupPreferencePage.STARTUP_ACTION_SYNCHRONIZE); } getConfiguration().getParticipant().run(getConfiguration().getSite().getPart()); } }); getForms().getHyperlinkGroup().add(link); if (store != null) { final Button rememberButton = getForms().createButton(composite, TeamUIMessages.DiffTreeChangesSection_14, SWT.CHECK); data = new GridData(GridData.FILL_HORIZONTAL); data.horizontalSpan = 2; data.horizontalIndent=5; data.verticalIndent=5; data.widthHint = 100; rememberButton.setLayoutData(data); rememberButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { remember[0] = rememberButton.getSelection(); } public void widgetDefaultSelected(SelectionEvent e) { // Do nothing } }); } return composite; }
private Composite getInitializationPane(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setBackground(getBackgroundColor()); GridLayout layout = new GridLayout(); layout.numColumns = 2; composite.setLayout(layout); GridData data = new GridData(GridData.FILL_BOTH); data.grabExcessVerticalSpace = true; composite.setLayoutData(data); createDescriptionLabel(composite, NLS.bind(TeamUIMessages.DiffTreeChangesSection_3, new String[] { Utils.shortenText(SynchronizeView.MAX_NAME_LENGTH, getConfiguration().getParticipant().getName()) })); final boolean[] remember = new boolean[] { false }; final PreferenceStore store = (PreferenceStore) getConfiguration() .getProperty(StartupPreferencePage.STARTUP_PREFERENCES); Hyperlink link = getForms().createHyperlink(composite, TeamUIMessages.DiffTreeChangesSection_4, SWT.WRAP); link.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { if (remember[0] && store != null) { store.putValue(StartupPreferencePage.PROP_STARTUP_ACTION, StartupPreferencePage.STARTUP_ACTION_POPULATE); } getHandler().initializeIfNeeded(); } }); getForms().getHyperlinkGroup().add(link); link = getForms().createHyperlink(composite, TeamUIMessages.DiffTreeChangesSection_5, SWT.WRAP); link.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { if (remember[0] && store != null) { store.putValue(StartupPreferencePage.PROP_STARTUP_ACTION, StartupPreferencePage.STARTUP_ACTION_SYNCHRONIZE); } getConfiguration().getParticipant().run(getConfiguration().getSite().getPart()); } }); getForms().getHyperlinkGroup().add(link); if (store != null) { final Button rememberButton = getForms().createButton(composite, TeamUIMessages.DiffTreeChangesSection_14, SWT.CHECK); rememberButton.setToolTipText(TeamUIMessages.DiffTreeChangesSection_14); data = new GridData(GridData.FILL_HORIZONTAL); data.horizontalSpan = 2; data.horizontalIndent=5; data.verticalIndent=5; data.widthHint = 100; rememberButton.setLayoutData(data); rememberButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { remember[0] = rememberButton.getSelection(); } public void widgetDefaultSelected(SelectionEvent e) { // Do nothing } }); } return composite; }
diff --git a/src/com/massivecraft/factions/commands/FBaseCommand.java b/src/com/massivecraft/factions/commands/FBaseCommand.java index 7ebd78e3..7ae3ba31 100644 --- a/src/com/massivecraft/factions/commands/FBaseCommand.java +++ b/src/com/massivecraft/factions/commands/FBaseCommand.java @@ -1,309 +1,309 @@ package com.massivecraft.factions.commands; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.massivecraft.factions.Conf; import com.massivecraft.factions.Econ; import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.Faction; import com.massivecraft.factions.Factions; import com.massivecraft.factions.struct.Role; import com.massivecraft.factions.util.TextUtil; public class FBaseCommand { public List<String> aliases; public List<String> requiredParameters; public List<String> optionalParameters; public String helpNameAndParams; public String helpDescription; public CommandSender sender; public boolean senderMustBePlayer; public Player player; public FPlayer me; public List<String> parameters; private static boolean lock = false; public FBaseCommand() { aliases = new ArrayList<String>(); requiredParameters = new ArrayList<String>(); optionalParameters = new ArrayList<String>(); senderMustBePlayer = true; helpNameAndParams = "fail!"; helpDescription = "no description"; } public List<String> getAliases() { return aliases; } public void execute(CommandSender sender, List<String> parameters) { this.sender = sender; this.parameters = parameters; if ( ! validateCall()) { return; } if (sender instanceof Player) { this.player = (Player)sender; this.me = FPlayer.get(this.player); } perform(); } public void perform() { } public void sendMessage(String message) { sender.sendMessage(Conf.colorSystem+message); } public void sendMessage(List<String> messages) { for(String message : messages) { this.sendMessage(message); } } public boolean validateCall() { if ( this.senderMustBePlayer && ! (sender instanceof Player)) { sendMessage("This command can only be used by ingame players."); return false; } if( ! hasPermission(sender)) { sendMessage("You lack the permissions to "+this.helpDescription.toLowerCase()+"."); return false; } // make sure player doesn't have their access to the command revoked Iterator<String> iter = aliases.iterator(); while (iter.hasNext()) { if (Factions.isCommandDisabled(sender, iter.next())) { sendMessage("You lack the permissions to "+this.helpDescription.toLowerCase()+"."); return false; } } if (parameters.size() < requiredParameters.size()) { sendMessage("Usage: "+this.getUseageTemplate(false)); return false; } return true; } public boolean hasPermission(CommandSender sender) { return Factions.hasPermParticipate(sender); } // -------------------------------------------- // // Help and usage description // -------------------------------------------- // public String getUseageTemplate(boolean withDescription) { String ret = ""; ret += Conf.colorCommand; ret += Factions.instance.getBaseCommand()+ " " +TextUtil.implode(this.getAliases(), ",")+" "; List<String> parts = new ArrayList<String>(); for (String requiredParameter : this.requiredParameters) { parts.add("["+requiredParameter+"]"); } for (String optionalParameter : this.optionalParameters) { parts.add("*["+optionalParameter+"]"); } ret += Conf.colorParameter; ret += TextUtil.implode(parts, " "); if (withDescription) { ret += " "+Conf.colorSystem + this.helpDescription; } return ret; } public String getUseageTemplate() { return getUseageTemplate(true); } // -------------------------------------------- // // Assertions // -------------------------------------------- // public boolean assertHasFaction() { if ( ! me.hasFaction()) { sendMessage("You are not member of any faction."); return false; } return true; } public boolean assertMinRole(Role role) { if (me.getRole().value < role.value) { sendMessage("You must be "+role+" to "+this.helpDescription+"."); return false; } return true; } // -------------------------------------------- // // Commonly used logic // -------------------------------------------- // public FPlayer findFPlayer(String playerName, boolean defaultToMe) { FPlayer fp = FPlayer.find(playerName); if (fp == null) { if (defaultToMe) { return me; } sendMessage("The player \""+playerName+"\" could not be found"); } return fp; } public FPlayer findFPlayer(String playerName) { return findFPlayer(playerName, false); } public Faction findFaction(String factionName, boolean defaultToMine) { // First we search faction names Faction faction = Faction.findByTag(factionName); if (faction != null) { return faction; } // Next we search player names FPlayer fp = FPlayer.find(factionName); if (fp != null) { return fp.getFaction(); } if (defaultToMine && sender instanceof Player) { return me.getFaction(); } sendMessage(Conf.colorSystem+"No faction or player \""+factionName+"\" was found"); return null; } public Faction findFaction(String factionName) { return findFaction(factionName, false); } public boolean canIAdministerYou(FPlayer i, FPlayer you) { if ( ! i.getFaction().equals(you.getFaction())) { i.sendMessage(you.getNameAndRelevant(i)+Conf.colorSystem+" is not in the same faction as you."); return false; } if (i.getRole().value > you.getRole().value || i.getRole().equals(Role.ADMIN) ) { return true; } if (you.getRole().equals(Role.ADMIN)) { i.sendMessage(Conf.colorSystem+"Only the faction admin can do that."); } else if (i.getRole().equals(Role.MODERATOR)) { i.sendMessage(Conf.colorSystem+"Moderators can't control each other..."); } else { i.sendMessage(Conf.colorSystem+"You must be a faction moderator to do that."); } return false; } // if economy is enabled and they're not on the bypass list, make 'em pay; returns true unless person can't afford the cost public boolean payForCommand(double cost) { if (!Econ.enabled() || this.me == null || cost == 0.0 || Conf.adminBypassPlayers.contains(me.getName())) { return true; } String desc = this.helpDescription.toLowerCase(); Faction faction = me.getFaction(); // pay up if (cost > 0.0) { String costString = Econ.moneyString(cost); - if(Conf.bankFactionPaysCosts) { + if(Conf.bankFactionPaysCosts && me.hasFaction() ) { if(!faction.removeMoney(cost)) { sendMessage("It costs "+costString+" to "+desc+", which your faction can't currently afford."); return false; } else { sendMessage(faction.getTag()+" has paid "+costString+" to "+desc+"."); } } else { if (!Econ.deductMoney(me.getName(), cost)) { sendMessage("It costs "+costString+" to "+desc+", which you can't currently afford."); return false; } sendMessage("You have paid "+costString+" to "+desc+"."); } } // wait... we pay you to use this command? else { String costString = Econ.moneyString(-cost); - if(Conf.bankFactionPaysCosts) { + if(Conf.bankFactionPaysCosts && me.hasFaction() ) { faction.addMoney(-cost); sendMessage(faction.getTag()+" has been paid "+costString+" to "+desc+"."); } else { Econ.addMoney(me.getName(), -cost); } sendMessage("You have been paid "+costString+" to "+desc+"."); } return true; } public static final List<String> aliasTrue = new ArrayList<String>(Arrays.asList("true", "yes", "y", "ok", "on", "+")); public static final List<String> aliasFalse = new ArrayList<String>(Arrays.asList("false", "no", "n", "off", "-")); public boolean parseBool(String str) { return aliasTrue.contains(str.toLowerCase()); } public void setLock(boolean newLock) { if( newLock ) { sendMessage("Factions is now locked"); } else { sendMessage("Factions in now unlocked"); } lock = newLock; } public boolean isLocked() { return lock; } public void sendLockMessage() { me.sendMessage("Factions is locked. Please try again later"); } }
false
true
public boolean payForCommand(double cost) { if (!Econ.enabled() || this.me == null || cost == 0.0 || Conf.adminBypassPlayers.contains(me.getName())) { return true; } String desc = this.helpDescription.toLowerCase(); Faction faction = me.getFaction(); // pay up if (cost > 0.0) { String costString = Econ.moneyString(cost); if(Conf.bankFactionPaysCosts) { if(!faction.removeMoney(cost)) { sendMessage("It costs "+costString+" to "+desc+", which your faction can't currently afford."); return false; } else { sendMessage(faction.getTag()+" has paid "+costString+" to "+desc+"."); } } else { if (!Econ.deductMoney(me.getName(), cost)) { sendMessage("It costs "+costString+" to "+desc+", which you can't currently afford."); return false; } sendMessage("You have paid "+costString+" to "+desc+"."); } } // wait... we pay you to use this command? else { String costString = Econ.moneyString(-cost); if(Conf.bankFactionPaysCosts) { faction.addMoney(-cost); sendMessage(faction.getTag()+" has been paid "+costString+" to "+desc+"."); } else { Econ.addMoney(me.getName(), -cost); } sendMessage("You have been paid "+costString+" to "+desc+"."); } return true; }
public boolean payForCommand(double cost) { if (!Econ.enabled() || this.me == null || cost == 0.0 || Conf.adminBypassPlayers.contains(me.getName())) { return true; } String desc = this.helpDescription.toLowerCase(); Faction faction = me.getFaction(); // pay up if (cost > 0.0) { String costString = Econ.moneyString(cost); if(Conf.bankFactionPaysCosts && me.hasFaction() ) { if(!faction.removeMoney(cost)) { sendMessage("It costs "+costString+" to "+desc+", which your faction can't currently afford."); return false; } else { sendMessage(faction.getTag()+" has paid "+costString+" to "+desc+"."); } } else { if (!Econ.deductMoney(me.getName(), cost)) { sendMessage("It costs "+costString+" to "+desc+", which you can't currently afford."); return false; } sendMessage("You have paid "+costString+" to "+desc+"."); } } // wait... we pay you to use this command? else { String costString = Econ.moneyString(-cost); if(Conf.bankFactionPaysCosts && me.hasFaction() ) { faction.addMoney(-cost); sendMessage(faction.getTag()+" has been paid "+costString+" to "+desc+"."); } else { Econ.addMoney(me.getName(), -cost); } sendMessage("You have been paid "+costString+" to "+desc+"."); } return true; }
diff --git a/core/sail/inferencer/src/main/java/org/openrdf/sail/inferencer/fc/ForwardChainingRDFSInferencer.java b/core/sail/inferencer/src/main/java/org/openrdf/sail/inferencer/fc/ForwardChainingRDFSInferencer.java index da254e1b9..d60adea53 100644 --- a/core/sail/inferencer/src/main/java/org/openrdf/sail/inferencer/fc/ForwardChainingRDFSInferencer.java +++ b/core/sail/inferencer/src/main/java/org/openrdf/sail/inferencer/fc/ForwardChainingRDFSInferencer.java @@ -1,70 +1,71 @@ /* * Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2008. * * Licensed under the Aduna BSD-style license. */ package org.openrdf.sail.inferencer.fc; import org.openrdf.sail.NotifyingSail; import org.openrdf.sail.Sail; import org.openrdf.sail.SailException; import org.openrdf.sail.helpers.NotifyingSailWrapper; import org.openrdf.sail.inferencer.InferencerConnection; /** * Forward-chaining RDF Schema inferencer, using the rules from the <a * href="http://www.w3.org/TR/2004/REC-rdf-mt-20040210/">RDF Semantics * Recommendation (10 February 2004)</a>. This inferencer can be used to add * RDF Schema semantics to any Sail that returns {@link InferencerConnection}s * from their {@link Sail#getConnection()} method. */ public class ForwardChainingRDFSInferencer extends NotifyingSailWrapper { /*--------------* * Constructors * *--------------*/ public ForwardChainingRDFSInferencer() { super(); } public ForwardChainingRDFSInferencer(NotifyingSail baseSail) { super(baseSail); } /*---------* * Methods * *---------*/ @Override public ForwardChainingRDFSInferencerConnection getConnection() throws SailException { try { InferencerConnection con = (InferencerConnection)super.getConnection(); return new ForwardChainingRDFSInferencerConnection(con); } catch (ClassCastException e) { throw new SailException(e.getMessage(), e); } } /** * Adds axiom statements to the underlying Sail. */ @Override public void initialize() throws SailException { super.initialize(); ForwardChainingRDFSInferencerConnection con = getConnection(); try { + con.begin(); con.addAxiomStatements(); con.commit(); } finally { con.close(); } } }
true
true
public void initialize() throws SailException { super.initialize(); ForwardChainingRDFSInferencerConnection con = getConnection(); try { con.addAxiomStatements(); con.commit(); } finally { con.close(); } }
public void initialize() throws SailException { super.initialize(); ForwardChainingRDFSInferencerConnection con = getConnection(); try { con.begin(); con.addAxiomStatements(); con.commit(); } finally { con.close(); } }
diff --git a/src/com/fluendo/jheora/FrArray.java b/src/com/fluendo/jheora/FrArray.java index 2a54560..1324f48 100644 --- a/src/com/fluendo/jheora/FrArray.java +++ b/src/com/fluendo/jheora/FrArray.java @@ -1,420 +1,420 @@ /* Jheora * Copyright (C) 2004 Fluendo S.L. * * Written by: 2004 Wim Taymans <[email protected]> * * Many thanks to * The Xiph.Org Foundation http://www.xiph.org/ * Jheora was based on their Theora reference decoder. * * This program 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 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 Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package com.fluendo.jheora; import com.jcraft.jogg.*; import com.fluendo.utils.*; public class FrArray { private int bit_pattern; private byte bits_so_far; private byte NextBit; private int BitsLeft; public FrArray() { } public void init() { /* Initialise the decoding of a run. */ bit_pattern = 0; bits_so_far = 0; } private int deCodeBlockRun(int bit_value){ /* Add in the new bit value. */ bits_so_far++; bit_pattern = (bit_pattern << 1) + (bit_value & 1); /* Coding scheme: Codeword RunLength 0x 1-2 10x 3-4 110x 5-6 1110xx 7-10 11110xx 11-14 11111xxxx 15-30 */ switch ( bits_so_far ){ case 2: /* If bit 1 is clear */ if ((bit_pattern & 0x0002) == 0){ BitsLeft = (bit_pattern & 0x0001) + 1; return 1; } break; case 3: /* If bit 1 is clear */ if ((bit_pattern & 0x0002) == 0){ BitsLeft = (bit_pattern & 0x0001) + 3; return 1; } break; case 4: /* If bit 1 is clear */ if ((bit_pattern & 0x0002) == 0){ BitsLeft = (bit_pattern & 0x0001) + 5; return 1; } break; case 6: /* If bit 2 is clear */ if ((bit_pattern & 0x0004) == 0){ BitsLeft = (bit_pattern & 0x0003) + 7; return 1; } break; case 7: /* If bit 2 is clear */ if ((bit_pattern & 0x0004) == 0){ BitsLeft = (bit_pattern & 0x0003) + 11; return 1; } break; case 9: BitsLeft = (bit_pattern & 0x000F) + 15; return 1; } return 0; } private int deCodeSBRun (int bit_value){ /* Add in the new bit value. */ bits_so_far++; bit_pattern = (bit_pattern << 1) + (bit_value & 1); /* Coding scheme: Codeword RunLength 0 1 10x 2-3 110x 4-5 1110xx 6-9 11110xxx 10-17 111110xxxx 18-33 111111xxxxxxxxxxxx 34-4129 */ switch ( bits_so_far ){ case 1: if (bit_pattern == 0 ){ BitsLeft = 1; return 1; } break; case 3: /* Bit 1 clear */ if ((bit_pattern & 0x0002) == 0){ BitsLeft = (bit_pattern & 0x0001) + 2; return 1; } break; case 4: /* Bit 1 clear */ if ((bit_pattern & 0x0002) == 0){ BitsLeft = (bit_pattern & 0x0001) + 4; return 1; } break; case 6: /* Bit 2 clear */ if ((bit_pattern & 0x0004) == 0){ BitsLeft = (bit_pattern & 0x0003) + 6; return 1; } break; case 8: /* Bit 3 clear */ if ((bit_pattern & 0x0008) == 0){ BitsLeft = (bit_pattern & 0x0007) + 10; return 1; } break; case 10: /* Bit 4 clear */ if ((bit_pattern & 0x0010) == 0){ BitsLeft = (bit_pattern & 0x000F) + 18; return 1; } break; case 18: BitsLeft = (bit_pattern & 0x0FFF) + 34; return 1; } return 0; } private void getNextBInit(Buffer opb){ long ret; ret = opb.readB(1); NextBit = (byte)ret; /* Read run length */ init(); do { ret = opb.readB(1); } while (deCodeBlockRun((int)ret)==0); } private byte getNextBBit (Buffer opb){ long ret; if (BitsLeft == 0){ /* Toggle the value. */ NextBit = NextBit = (byte) (NextBit ^ 1); /* Read next run */ init(); do { ret = opb.readB(1); } while (deCodeBlockRun((int)ret)==0); } /* Have read a bit */ BitsLeft--; /* Return next bit value */ return NextBit; } private void getNextSbInit(Buffer opb){ long ret; ret = opb.readB(1); NextBit = (byte)ret; /* Read run length */ init(); do { ret = opb.readB(1); } while (deCodeSBRun((int)ret)==0); } private byte getNextSbBit (Buffer opb){ long ret; if (BitsLeft == 0){ /* Toggle the value. */ NextBit = (byte) (NextBit ^ 1); /* Read next run */ init(); do { ret = opb.readB(1); } while (deCodeSBRun((int)ret)==0); } /* Have read a bit */ BitsLeft--; /* Return next bit value */ return NextBit; } private final short[] empty64 = new short[64]; public void quadDecodeDisplayFragments ( Playback pbi ){ int SB, MB, B; int DataToDecode; int dfIndex; int MBIndex = 0; Buffer opb = pbi.opb; /* Reset various data structures common to key frames and inter frames. */ pbi.CodedBlockIndex = 0; MemUtils.set ( pbi.display_fragments, 0, 0, pbi.UnitFragments ); /* For "Key frames" mark all blocks as coded and return. */ /* Else initialise the ArrayPtr array to 0 (all blocks uncoded by default) */ if ( pbi.getFrameType() == Constants.BASE_FRAME ) { MemUtils.set( pbi.SBFullyFlags, 0, 1, pbi.SuperBlocks ); MemUtils.set( pbi.SBCodedFlags, 0, 1, pbi.SuperBlocks ); MemUtils.set( pbi.MBCodedFlags, 0, 0, pbi.MacroBlocks ); }else{ MemUtils.set( pbi.SBFullyFlags, 0, 0, pbi.SuperBlocks ); MemUtils.set( pbi.MBCodedFlags, 0, 0, pbi.MacroBlocks ); /* Un-pack the list of partially coded Super-Blocks */ getNextSbInit(opb); for( SB = 0; SB < pbi.SuperBlocks; SB++){ pbi.SBCodedFlags[SB] = getNextSbBit (opb); } /* Scan through the list of super blocks. Unless all are marked as partially coded we have more to do. */ DataToDecode = 0; for ( SB=0; SB<pbi.SuperBlocks; SB++ ) { if (pbi.SBCodedFlags[SB] == 0) { DataToDecode = 1; break; } } /* Are there further block map bits to decode ? */ if (DataToDecode != 0) { /* Un-pack the Super-Block fully coded flags. */ getNextSbInit(opb); for( SB = 0; SB < pbi.SuperBlocks; SB++) { /* Skip blocks already marked as partially coded */ while( (SB < pbi.SuperBlocks) && (pbi.SBCodedFlags[SB] != 0 )) SB++; if (SB < pbi.SuperBlocks) { pbi.SBFullyFlags[SB] = getNextSbBit (opb); if (pbi.SBFullyFlags[SB] != 0) /* If SB is fully coded. */ pbi.SBCodedFlags[SB] = 1; /* Mark the SB as coded */ } } } /* Scan through the list of coded super blocks. If at least one is marked as partially coded then we have a block list to decode. */ for ( SB=0; SB<pbi.SuperBlocks; SB++ ) { if ((pbi.SBCodedFlags[SB] != 0) && (pbi.SBFullyFlags[SB] == 0)) { /* Initialise the block list decoder. */ getNextBInit(opb); break; } } } /* Decode the block data from the bit stream. */ for ( SB=0; SB<pbi.SuperBlocks; SB++ ){ for ( MB=0; MB<4; MB++ ){ /* If MB is in the frame */ if (pbi.BlockMap.quadMapToMBTopLeft(SB,MB) >= 0 ){ /* Only read block level data if SB was fully or partially coded */ if (pbi.SBCodedFlags[SB] != 0) { for ( B=0; B<4; B++ ){ /* If block is valid (in frame)... */ dfIndex = pbi.BlockMap.quadMapToIndex1(SB, MB, B); if ( dfIndex >= 0 ){ if ( pbi.SBFullyFlags[SB] != 0) pbi.display_fragments[dfIndex] = 1; else pbi.display_fragments[dfIndex] = getNextBBit(opb); /* Create linear list of coded block indices */ if ( pbi.display_fragments[dfIndex] != 0) { pbi.MBCodedFlags[MBIndex] = 1; pbi.CodedBlockList[pbi.CodedBlockIndex] = dfIndex; - /* Clear down the pbi.QFragData structure for all coded blocks. */ + /* Clear down the pbi.QFragData structure for this coded block. */ System.arraycopy(empty64, 0, pbi.QFragData[dfIndex], 0, 64); pbi.CodedBlockIndex++; } } } } MBIndex++; } } } } public CodingMode unpackMode(Buffer opb){ /* Coding scheme: Token Codeword Bits Entry 0 (most frequent) 0 1 Entry 1 10 2 Entry 2 110 3 Entry 3 1110 4 Entry 4 11110 5 Entry 5 111110 6 Entry 6 1111110 7 Entry 7 1111111 7 */ /* Initialise the decoding. */ bits_so_far = 0; bit_pattern = (int) opb.readB(1); /* Do we have a match */ if ( bit_pattern == 0 ) return CodingMode.MODES[0]; /* Get the next bit */ bit_pattern = (bit_pattern << 1) | (int)opb.readB(1); /* Do we have a match */ if ( bit_pattern == 0x0002 ) return CodingMode.MODES[1]; bit_pattern = (bit_pattern << 1) | (int)opb.readB(1); /* Do we have a match */ if ( bit_pattern == 0x0006 ) return CodingMode.MODES[2]; bit_pattern = (bit_pattern << 1) | (int)opb.readB(1); /* Do we have a match */ if ( bit_pattern == 0x000E ) return CodingMode.MODES[3]; bit_pattern = (bit_pattern << 1) | (int)opb.readB(1); /* Do we have a match */ if ( bit_pattern == 0x001E ) return CodingMode.MODES[4]; bit_pattern = (bit_pattern << 1) | (int)opb.readB(1); /* Do we have a match */ if ( bit_pattern == 0x003E ) return CodingMode.MODES[5]; bit_pattern = (bit_pattern << 1) | (int)opb.readB(1); /* Do we have a match */ if ( bit_pattern == 0x007E ) return CodingMode.MODES[6]; else return CodingMode.MODES[7]; } }
true
true
public void quadDecodeDisplayFragments ( Playback pbi ){ int SB, MB, B; int DataToDecode; int dfIndex; int MBIndex = 0; Buffer opb = pbi.opb; /* Reset various data structures common to key frames and inter frames. */ pbi.CodedBlockIndex = 0; MemUtils.set ( pbi.display_fragments, 0, 0, pbi.UnitFragments ); /* For "Key frames" mark all blocks as coded and return. */ /* Else initialise the ArrayPtr array to 0 (all blocks uncoded by default) */ if ( pbi.getFrameType() == Constants.BASE_FRAME ) { MemUtils.set( pbi.SBFullyFlags, 0, 1, pbi.SuperBlocks ); MemUtils.set( pbi.SBCodedFlags, 0, 1, pbi.SuperBlocks ); MemUtils.set( pbi.MBCodedFlags, 0, 0, pbi.MacroBlocks ); }else{ MemUtils.set( pbi.SBFullyFlags, 0, 0, pbi.SuperBlocks ); MemUtils.set( pbi.MBCodedFlags, 0, 0, pbi.MacroBlocks ); /* Un-pack the list of partially coded Super-Blocks */ getNextSbInit(opb); for( SB = 0; SB < pbi.SuperBlocks; SB++){ pbi.SBCodedFlags[SB] = getNextSbBit (opb); } /* Scan through the list of super blocks. Unless all are marked as partially coded we have more to do. */ DataToDecode = 0; for ( SB=0; SB<pbi.SuperBlocks; SB++ ) { if (pbi.SBCodedFlags[SB] == 0) { DataToDecode = 1; break; } } /* Are there further block map bits to decode ? */ if (DataToDecode != 0) { /* Un-pack the Super-Block fully coded flags. */ getNextSbInit(opb); for( SB = 0; SB < pbi.SuperBlocks; SB++) { /* Skip blocks already marked as partially coded */ while( (SB < pbi.SuperBlocks) && (pbi.SBCodedFlags[SB] != 0 )) SB++; if (SB < pbi.SuperBlocks) { pbi.SBFullyFlags[SB] = getNextSbBit (opb); if (pbi.SBFullyFlags[SB] != 0) /* If SB is fully coded. */ pbi.SBCodedFlags[SB] = 1; /* Mark the SB as coded */ } } } /* Scan through the list of coded super blocks. If at least one is marked as partially coded then we have a block list to decode. */ for ( SB=0; SB<pbi.SuperBlocks; SB++ ) { if ((pbi.SBCodedFlags[SB] != 0) && (pbi.SBFullyFlags[SB] == 0)) { /* Initialise the block list decoder. */ getNextBInit(opb); break; } } } /* Decode the block data from the bit stream. */ for ( SB=0; SB<pbi.SuperBlocks; SB++ ){ for ( MB=0; MB<4; MB++ ){ /* If MB is in the frame */ if (pbi.BlockMap.quadMapToMBTopLeft(SB,MB) >= 0 ){ /* Only read block level data if SB was fully or partially coded */ if (pbi.SBCodedFlags[SB] != 0) { for ( B=0; B<4; B++ ){ /* If block is valid (in frame)... */ dfIndex = pbi.BlockMap.quadMapToIndex1(SB, MB, B); if ( dfIndex >= 0 ){ if ( pbi.SBFullyFlags[SB] != 0) pbi.display_fragments[dfIndex] = 1; else pbi.display_fragments[dfIndex] = getNextBBit(opb); /* Create linear list of coded block indices */ if ( pbi.display_fragments[dfIndex] != 0) { pbi.MBCodedFlags[MBIndex] = 1; pbi.CodedBlockList[pbi.CodedBlockIndex] = dfIndex; /* Clear down the pbi.QFragData structure for all coded blocks. */ System.arraycopy(empty64, 0, pbi.QFragData[dfIndex], 0, 64); pbi.CodedBlockIndex++; } } } } MBIndex++; } } } }
public void quadDecodeDisplayFragments ( Playback pbi ){ int SB, MB, B; int DataToDecode; int dfIndex; int MBIndex = 0; Buffer opb = pbi.opb; /* Reset various data structures common to key frames and inter frames. */ pbi.CodedBlockIndex = 0; MemUtils.set ( pbi.display_fragments, 0, 0, pbi.UnitFragments ); /* For "Key frames" mark all blocks as coded and return. */ /* Else initialise the ArrayPtr array to 0 (all blocks uncoded by default) */ if ( pbi.getFrameType() == Constants.BASE_FRAME ) { MemUtils.set( pbi.SBFullyFlags, 0, 1, pbi.SuperBlocks ); MemUtils.set( pbi.SBCodedFlags, 0, 1, pbi.SuperBlocks ); MemUtils.set( pbi.MBCodedFlags, 0, 0, pbi.MacroBlocks ); }else{ MemUtils.set( pbi.SBFullyFlags, 0, 0, pbi.SuperBlocks ); MemUtils.set( pbi.MBCodedFlags, 0, 0, pbi.MacroBlocks ); /* Un-pack the list of partially coded Super-Blocks */ getNextSbInit(opb); for( SB = 0; SB < pbi.SuperBlocks; SB++){ pbi.SBCodedFlags[SB] = getNextSbBit (opb); } /* Scan through the list of super blocks. Unless all are marked as partially coded we have more to do. */ DataToDecode = 0; for ( SB=0; SB<pbi.SuperBlocks; SB++ ) { if (pbi.SBCodedFlags[SB] == 0) { DataToDecode = 1; break; } } /* Are there further block map bits to decode ? */ if (DataToDecode != 0) { /* Un-pack the Super-Block fully coded flags. */ getNextSbInit(opb); for( SB = 0; SB < pbi.SuperBlocks; SB++) { /* Skip blocks already marked as partially coded */ while( (SB < pbi.SuperBlocks) && (pbi.SBCodedFlags[SB] != 0 )) SB++; if (SB < pbi.SuperBlocks) { pbi.SBFullyFlags[SB] = getNextSbBit (opb); if (pbi.SBFullyFlags[SB] != 0) /* If SB is fully coded. */ pbi.SBCodedFlags[SB] = 1; /* Mark the SB as coded */ } } } /* Scan through the list of coded super blocks. If at least one is marked as partially coded then we have a block list to decode. */ for ( SB=0; SB<pbi.SuperBlocks; SB++ ) { if ((pbi.SBCodedFlags[SB] != 0) && (pbi.SBFullyFlags[SB] == 0)) { /* Initialise the block list decoder. */ getNextBInit(opb); break; } } } /* Decode the block data from the bit stream. */ for ( SB=0; SB<pbi.SuperBlocks; SB++ ){ for ( MB=0; MB<4; MB++ ){ /* If MB is in the frame */ if (pbi.BlockMap.quadMapToMBTopLeft(SB,MB) >= 0 ){ /* Only read block level data if SB was fully or partially coded */ if (pbi.SBCodedFlags[SB] != 0) { for ( B=0; B<4; B++ ){ /* If block is valid (in frame)... */ dfIndex = pbi.BlockMap.quadMapToIndex1(SB, MB, B); if ( dfIndex >= 0 ){ if ( pbi.SBFullyFlags[SB] != 0) pbi.display_fragments[dfIndex] = 1; else pbi.display_fragments[dfIndex] = getNextBBit(opb); /* Create linear list of coded block indices */ if ( pbi.display_fragments[dfIndex] != 0) { pbi.MBCodedFlags[MBIndex] = 1; pbi.CodedBlockList[pbi.CodedBlockIndex] = dfIndex; /* Clear down the pbi.QFragData structure for this coded block. */ System.arraycopy(empty64, 0, pbi.QFragData[dfIndex], 0, 64); pbi.CodedBlockIndex++; } } } } MBIndex++; } } } }
diff --git a/src/main/java/com/tadamski/arij/issue/activity/list/IssueListFragment.java b/src/main/java/com/tadamski/arij/issue/activity/list/IssueListFragment.java index 9854a39..005a9e7 100644 --- a/src/main/java/com/tadamski/arij/issue/activity/list/IssueListFragment.java +++ b/src/main/java/com/tadamski/arij/issue/activity/list/IssueListFragment.java @@ -1,53 +1,54 @@ package com.tadamski.arij.issue.activity.list; import android.view.View; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; import com.google.inject.Inject; import com.googlecode.androidannotations.annotations.AfterViews; import com.googlecode.androidannotations.annotations.EFragment; import com.googlecode.androidannotations.annotations.ViewById; import com.tadamski.arij.R; import com.tadamski.arij.account.service.LoginInfo; import com.tadamski.arij.issue.activity.single.view.IssueActivity_; import com.tadamski.arij.issue.dao.Issue; import com.tadamski.arij.issue.dao.IssueDAO; import roboguice.fragment.RoboFragment; import java.util.ArrayList; /** * Created with IntelliJ IDEA. * User: tmszdmsk * Date: 09.04.13 * Time: 20:09 * To change this template use File | Settings | File Templates. */ @EFragment(R.layout.issue_list_fragment) public class IssueListFragment extends RoboFragment implements AdapterView.OnItemClickListener { @ViewById(android.R.id.list) ListView listView; @Inject IssueDAO issueDAO; ListAdapter issueListAdapter; private LoginInfo account; @AfterViews void initClickListener() { listView.setOnItemClickListener(this); } public void executeJql(String jql, LoginInfo account) { + this.account = account; IssueListAdapter adapter = new IssueListAdapter(getActivity(), new ArrayList<Issue.Summary>(), 1, jql); issueListAdapter = new EndlessIssueListAdapter(issueDAO, getActivity(), adapter, account); listView.setAdapter(issueListAdapter); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Issue.Summary item = (Issue.Summary) issueListAdapter.getItem(position); IssueActivity_.intent(getActivity()).issueKey(item.getKey()).account(account).start(); } }
true
true
public void executeJql(String jql, LoginInfo account) { IssueListAdapter adapter = new IssueListAdapter(getActivity(), new ArrayList<Issue.Summary>(), 1, jql); issueListAdapter = new EndlessIssueListAdapter(issueDAO, getActivity(), adapter, account); listView.setAdapter(issueListAdapter); }
public void executeJql(String jql, LoginInfo account) { this.account = account; IssueListAdapter adapter = new IssueListAdapter(getActivity(), new ArrayList<Issue.Summary>(), 1, jql); issueListAdapter = new EndlessIssueListAdapter(issueDAO, getActivity(), adapter, account); listView.setAdapter(issueListAdapter); }
diff --git a/src/main/java/com/github/maven_nar/NarLayout21.java b/src/main/java/com/github/maven_nar/NarLayout21.java index d19c7aa7..fefc166a 100644 --- a/src/main/java/com/github/maven_nar/NarLayout21.java +++ b/src/main/java/com/github/maven_nar/NarLayout21.java @@ -1,265 +1,265 @@ package com.github.maven_nar; import java.io.File; import java.io.IOException; import java.util.ArrayList; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectHelper; import org.codehaus.plexus.archiver.manager.ArchiverManager; import org.codehaus.plexus.util.FileUtils; /* * 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. */ /** * Layout which expands a nar file into: * * <pre> * nar/noarch/include * nar/aol/<aol>-<type>/bin * nar/aol/<aol>-<type>/lib * </pre> * * This loayout has a one-to-one relation with the aol-type version of the nar. * * @author Mark Donszelmann ([email protected]) */ public class NarLayout21 extends AbstractNarLayout { private NarFileLayout fileLayout; public NarLayout21( Log log ) { super( log ); this.fileLayout = new NarFileLayout10(); } public File getNoArchDirectory( File baseDir, String artifactId, String version ) { return new File( baseDir, artifactId + "-" + version + "-" + NarConstants.NAR_NO_ARCH ); } private File getAolDirectory( File baseDir, String artifactId, String version, String aol, String type ) { return new File( baseDir, artifactId + "-" + version + "-" + aol + "-" + type ); } /* * (non-Javadoc) * @see com.github.maven_nar.NarLayout#getIncludeDirectory(java.io.File) */ public final File getIncludeDirectory( File baseDir, String artifactId, String version ) { return new File( getNoArchDirectory( baseDir, artifactId, version ), fileLayout.getIncludeDirectory() ); } /* * (non-Javadoc) * @see com.github.maven_nar.NarLayout#getLibDir(java.io.File, com.github.maven_nar.AOL, * java.lang.String) */ public final File getLibDirectory( File baseDir, String artifactId, String version, String aol, String type ) throws MojoExecutionException { if ( type.equals( Library.EXECUTABLE ) ) { throw new MojoExecutionException( "NAR: for type EXECUTABLE call getBinDirectory instead of getLibDirectory" ); } File dir = getAolDirectory( baseDir, artifactId, version, aol, type ); dir = new File( dir, fileLayout.getLibDirectory( aol, type ) ); return dir; } /* * (non-Javadoc) * @see com.github.maven_nar.NarLayout#getLibDir(java.io.File, com.github.maven_nar.AOL, * java.lang.String) */ public final File getBinDirectory( File baseDir, String artifactId, String version, String aol ) { File dir = getAolDirectory( baseDir, artifactId, version, aol, Library.EXECUTABLE ); dir = new File( dir, fileLayout.getBinDirectory( aol ) ); return dir; } /* * (non-Javadoc) * @see com.github.maven_nar.NarLayout#attachNars(java.io.File, org.apache.maven.project.MavenProjectHelper, * org.apache.maven.project.MavenProject, com.github.maven_nar.NarInfo) */ public final void prepareNarInfo( File baseDir, MavenProject project, NarInfo narInfo, AbstractNarMojo mojo ) throws MojoExecutionException { if ( getNoArchDirectory( baseDir, project.getArtifactId(), project.getVersion() ).exists() ) { narInfo.setNar( null, NarConstants.NAR_NO_ARCH, project.getGroupId() + ":" + project.getArtifactId() + ":" + NarConstants.NAR_TYPE + ":" + NarConstants.NAR_NO_ARCH ); } String artifactIdVersion = project.getArtifactId() + "-" + project.getVersion(); // list all directories in basedir, scan them for classifiers String[] subDirs = baseDir.list(); ArrayList<String> classifiers = new ArrayList<String>(); for ( int i = 0; ( subDirs != null ) && ( i < subDirs.length ); i++ ) { // skip entries not belonging to this project if ( !subDirs[i].startsWith( artifactIdVersion ) ) continue; String classifier = subDirs[i].substring( artifactIdVersion.length() + 1 ); // skip noarch here if ( classifier.equals( NarConstants.NAR_NO_ARCH ) ) continue; classifiers.add(classifier); } if( !classifiers.isEmpty() ){ for(String classifier : classifiers ){ int lastDash = classifier.lastIndexOf( '-' ); String type = classifier.substring( lastDash + 1 ); AOL aol = new AOL( classifier.substring( 0, lastDash ) ); if ( ( narInfo.getOutput( aol, null ) == null ) ) { - narInfo.setOutput( aol, mojo.getOutput(! aol.getOS().contains( OS.WINDOWS ) && ! type.equals( Library.EXECUTABLE ) ) ); + narInfo.setOutput( aol, mojo.getOutput(! Library.EXECUTABLE.equals( type ) ) ); } // We prefer shared to jni/executable/static/none, if ( type.equals( Library.SHARED ) ) // overwrite whatever we had { narInfo.setBinding( aol, type ); narInfo.setBinding( null, type ); } else { // if the binding is already set, then don't write it for jni/executable/static/none. if ( ( narInfo.getBinding( aol, null ) == null ) ) { narInfo.setBinding( aol, type ); } if ( ( narInfo.getBinding( null, null ) == null ) ) { narInfo.setBinding( null, type ); } } narInfo.setNar( null, type, project.getGroupId() + ":" + project.getArtifactId() + ":" + NarConstants.NAR_TYPE + ":" + "${aol}" + "-" + type ); } // setting this first stops the per type config because getOutput check for aol defaults to this generic one... if ( mojo!= null && ( narInfo.getOutput( null, null ) == null ) ) { narInfo.setOutput( null, mojo.getOutput(true) ); } } } /* * (non-Javadoc) * @see com.github.maven_nar.NarLayout#attachNars(java.io.File, org.apache.maven.project.MavenProjectHelper, * org.apache.maven.project.MavenProject, com.github.maven_nar.NarInfo) */ public final void attachNars( File baseDir, ArchiverManager archiverManager, MavenProjectHelper projectHelper, MavenProject project ) throws MojoExecutionException { if ( getNoArchDirectory( baseDir, project.getArtifactId(), project.getVersion() ).exists() ) { attachNar( archiverManager, projectHelper, project, NarConstants.NAR_NO_ARCH, getNoArchDirectory( baseDir, project.getArtifactId(), project.getVersion() ), "*/**" ); } // list all directories in basedir, scan them for classifiers String[] subDirs = baseDir.list(); for ( int i = 0; ( subDirs != null ) && ( i < subDirs.length ); i++ ) { String artifactIdVersion = project.getArtifactId() + "-" + project.getVersion(); // skip entries not belonging to this project if ( !subDirs[i].startsWith( artifactIdVersion ) ) continue; String classifier = subDirs[i].substring( artifactIdVersion.length() + 1 ); // skip noarch here if ( classifier.equals( NarConstants.NAR_NO_ARCH ) ) continue; File dir = new File( baseDir, subDirs[i] ); attachNar( archiverManager, projectHelper, project, classifier, dir, "*/**" ); } } public void unpackNar( File unpackDirectory, ArchiverManager archiverManager, File file, String os, String linkerName, AOL defaultAOL ) throws MojoExecutionException, MojoFailureException { File dir = getNarUnpackDirectory(unpackDirectory, file); boolean process = false; if ( !unpackDirectory.exists() ) { unpackDirectory.mkdirs(); process = true; } else if ( !dir.exists() ) { process = true; } else if ( file.lastModified() > dir.lastModified() ) { try { FileUtils.deleteDirectory( dir ); } catch ( IOException e ) { throw new MojoExecutionException( "Could not delete directory: " + dir, e ); } process = true; } if ( process ) { unpackNarAndProcess( archiverManager, file, dir, os, linkerName, defaultAOL ); } } public File getNarUnpackDirectory(File baseUnpackDirectory, File narFile) { File dir = new File( baseUnpackDirectory, FileUtils.basename( narFile.getPath(), "." + NarConstants.NAR_EXTENSION )); return dir; } }
true
true
public final void prepareNarInfo( File baseDir, MavenProject project, NarInfo narInfo, AbstractNarMojo mojo ) throws MojoExecutionException { if ( getNoArchDirectory( baseDir, project.getArtifactId(), project.getVersion() ).exists() ) { narInfo.setNar( null, NarConstants.NAR_NO_ARCH, project.getGroupId() + ":" + project.getArtifactId() + ":" + NarConstants.NAR_TYPE + ":" + NarConstants.NAR_NO_ARCH ); } String artifactIdVersion = project.getArtifactId() + "-" + project.getVersion(); // list all directories in basedir, scan them for classifiers String[] subDirs = baseDir.list(); ArrayList<String> classifiers = new ArrayList<String>(); for ( int i = 0; ( subDirs != null ) && ( i < subDirs.length ); i++ ) { // skip entries not belonging to this project if ( !subDirs[i].startsWith( artifactIdVersion ) ) continue; String classifier = subDirs[i].substring( artifactIdVersion.length() + 1 ); // skip noarch here if ( classifier.equals( NarConstants.NAR_NO_ARCH ) ) continue; classifiers.add(classifier); } if( !classifiers.isEmpty() ){ for(String classifier : classifiers ){ int lastDash = classifier.lastIndexOf( '-' ); String type = classifier.substring( lastDash + 1 ); AOL aol = new AOL( classifier.substring( 0, lastDash ) ); if ( ( narInfo.getOutput( aol, null ) == null ) ) { narInfo.setOutput( aol, mojo.getOutput(! aol.getOS().contains( OS.WINDOWS ) && ! type.equals( Library.EXECUTABLE ) ) ); } // We prefer shared to jni/executable/static/none, if ( type.equals( Library.SHARED ) ) // overwrite whatever we had { narInfo.setBinding( aol, type ); narInfo.setBinding( null, type ); } else { // if the binding is already set, then don't write it for jni/executable/static/none. if ( ( narInfo.getBinding( aol, null ) == null ) ) { narInfo.setBinding( aol, type ); } if ( ( narInfo.getBinding( null, null ) == null ) ) { narInfo.setBinding( null, type ); } } narInfo.setNar( null, type, project.getGroupId() + ":" + project.getArtifactId() + ":" + NarConstants.NAR_TYPE + ":" + "${aol}" + "-" + type ); } // setting this first stops the per type config because getOutput check for aol defaults to this generic one... if ( mojo!= null && ( narInfo.getOutput( null, null ) == null ) ) { narInfo.setOutput( null, mojo.getOutput(true) ); } } }
public final void prepareNarInfo( File baseDir, MavenProject project, NarInfo narInfo, AbstractNarMojo mojo ) throws MojoExecutionException { if ( getNoArchDirectory( baseDir, project.getArtifactId(), project.getVersion() ).exists() ) { narInfo.setNar( null, NarConstants.NAR_NO_ARCH, project.getGroupId() + ":" + project.getArtifactId() + ":" + NarConstants.NAR_TYPE + ":" + NarConstants.NAR_NO_ARCH ); } String artifactIdVersion = project.getArtifactId() + "-" + project.getVersion(); // list all directories in basedir, scan them for classifiers String[] subDirs = baseDir.list(); ArrayList<String> classifiers = new ArrayList<String>(); for ( int i = 0; ( subDirs != null ) && ( i < subDirs.length ); i++ ) { // skip entries not belonging to this project if ( !subDirs[i].startsWith( artifactIdVersion ) ) continue; String classifier = subDirs[i].substring( artifactIdVersion.length() + 1 ); // skip noarch here if ( classifier.equals( NarConstants.NAR_NO_ARCH ) ) continue; classifiers.add(classifier); } if( !classifiers.isEmpty() ){ for(String classifier : classifiers ){ int lastDash = classifier.lastIndexOf( '-' ); String type = classifier.substring( lastDash + 1 ); AOL aol = new AOL( classifier.substring( 0, lastDash ) ); if ( ( narInfo.getOutput( aol, null ) == null ) ) { narInfo.setOutput( aol, mojo.getOutput(! Library.EXECUTABLE.equals( type ) ) ); } // We prefer shared to jni/executable/static/none, if ( type.equals( Library.SHARED ) ) // overwrite whatever we had { narInfo.setBinding( aol, type ); narInfo.setBinding( null, type ); } else { // if the binding is already set, then don't write it for jni/executable/static/none. if ( ( narInfo.getBinding( aol, null ) == null ) ) { narInfo.setBinding( aol, type ); } if ( ( narInfo.getBinding( null, null ) == null ) ) { narInfo.setBinding( null, type ); } } narInfo.setNar( null, type, project.getGroupId() + ":" + project.getArtifactId() + ":" + NarConstants.NAR_TYPE + ":" + "${aol}" + "-" + type ); } // setting this first stops the per type config because getOutput check for aol defaults to this generic one... if ( mojo!= null && ( narInfo.getOutput( null, null ) == null ) ) { narInfo.setOutput( null, mojo.getOutput(true) ); } } }
diff --git a/AeroControl/src/com/aero/control/fragments/UpdaterFragment.java b/AeroControl/src/com/aero/control/fragments/UpdaterFragment.java index 7c168b1..dfb60d8 100644 --- a/AeroControl/src/com/aero/control/fragments/UpdaterFragment.java +++ b/AeroControl/src/com/aero/control/fragments/UpdaterFragment.java @@ -1,184 +1,184 @@ package com.aero.control.fragments; import android.app.AlertDialog; import android.app.Fragment; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceScreen; import android.provider.MediaStore; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.aero.control.R; import com.aero.control.helpers.shellHelper; import com.aero.control.helpers.updateHelpers; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; /** * Created by Alexander Christ on 16.09.13. * Default Updater Fragment */ public class UpdaterFragment extends PreferenceFragment { public static String timeStamp = new SimpleDateFormat("ddMMyyyy").format(Calendar.getInstance().getTime()); public static String zImage = "/system/bootmenu/2nd-boot/zImage"; public static File BACKUP_PATH = new File ("/sdcard/com.aero.control/" + timeStamp + "/zImage"); public static File IMAGE = new File (zImage); updateHelpers update = new updateHelpers(); shellHelper shell = new shellHelper(); public static Fragment newInstance(Context context) { UpdaterFragment f = new UpdaterFragment(); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // We have to load the xml layout first; addPreferencesFromResource(R.layout.updater_fragment); PreferenceScreen root = this.getPreferenceScreen(); final Preference backup_kernel = root.findPreference("backup_kernel"); final Preference updater_kernel = root.findPreference("updater_kernel"); final ListPreference restore_kernel = (ListPreference) root.findPreference("restore_kernel"); // Disable them all; //backup_kernel.setEnabled(false); updater_kernel.setEnabled(false); //restore_kernel.setEnabled(false); // If device doesn't have this kernel path; - //if (shell.getInfo(zImage).equals("Unavailable")) - //backup_kernel.setEnabled(false); + if (shell.getInfo(zImage).equals("Unavailable")) + backup_kernel.setEnabled(false); - //if (shell.getInfo(zImage).equals("Unavailable")) - //restore_kernel.setEnabled(false); + if (shell.getInfo(zImage).equals("Unavailable")) + restore_kernel.setEnabled(false); // Fresh Start, no backup found; try { backup_kernel.setSummary(getText(R.string.last_backup_from)+ " " + shell.getDirInfo("/sdcard/com.aero.control/", false)[0]); restore_kernel.setEnabled(true); } catch (ArrayIndexOutOfBoundsException e) { backup_kernel.setSummary(getText(R.string.last_backup_from)+ " " + getText(R.string.unavailable)); restore_kernel.setEnabled(false); } restore_kernel.setEntries(shell.getDirInfo("/sdcard/com.aero.control/", false)); restore_kernel.setEntryValues(shell.getDirInfo("/sdcard/com.aero.control/", false)); restore_kernel.setDialogIcon(R.drawable.restore_dark); restore_kernel.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object o) { final String s = (String) o; AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View layout = inflater.inflate(R.layout.about_screen, null); TextView aboutText = (TextView) layout.findViewById(R.id.aboutScreen); builder.setTitle(getText(R.string.backup_from) + " " + s); aboutText.setText(getText(R.string.restore_from_backup) + " " + s + " ?"); shell.remountSystem(); builder.setView(layout) .setPositiveButton(R.string.save, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // Delete old zImage first, then copy backup; String[] commands = new String[] { "rm -f " + zImage, "cp " + "/sdcard/com.aero.control/" + s + "/zImage" + " " + zImage, }; shell.setRootInfo(commands); Toast.makeText(getActivity(), R.string.need_reboot, Toast.LENGTH_LONG).show(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Do nothing } }); builder.show(); return true; }; }); backup_kernel.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View layout = inflater.inflate(R.layout.about_screen, null); TextView aboutText = (TextView) layout.findViewById(R.id.aboutScreen); builder.setTitle("Backup"); builder.setIcon(R.drawable.backup_dark); aboutText.setText(R.string.proceed_backup); builder.setView(layout) .setPositiveButton(R.string.save, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { try { update.copyFile(IMAGE, BACKUP_PATH, false); Toast.makeText(getActivity(), "Backup was successful!", Toast.LENGTH_LONG).show(); backup_kernel.setSummary(getText(R.string.last_backup_from) + " " + timeStamp); restore_kernel.setEnabled(true); } catch (IOException e) { Log.e("Aero", "A problem occured while saving a backup.", e); } } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Do nothing } }); builder.show(); return true; } ; }); } }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // We have to load the xml layout first; addPreferencesFromResource(R.layout.updater_fragment); PreferenceScreen root = this.getPreferenceScreen(); final Preference backup_kernel = root.findPreference("backup_kernel"); final Preference updater_kernel = root.findPreference("updater_kernel"); final ListPreference restore_kernel = (ListPreference) root.findPreference("restore_kernel"); // Disable them all; //backup_kernel.setEnabled(false); updater_kernel.setEnabled(false); //restore_kernel.setEnabled(false); // If device doesn't have this kernel path; //if (shell.getInfo(zImage).equals("Unavailable")) //backup_kernel.setEnabled(false); //if (shell.getInfo(zImage).equals("Unavailable")) //restore_kernel.setEnabled(false); // Fresh Start, no backup found; try { backup_kernel.setSummary(getText(R.string.last_backup_from)+ " " + shell.getDirInfo("/sdcard/com.aero.control/", false)[0]); restore_kernel.setEnabled(true); } catch (ArrayIndexOutOfBoundsException e) { backup_kernel.setSummary(getText(R.string.last_backup_from)+ " " + getText(R.string.unavailable)); restore_kernel.setEnabled(false); } restore_kernel.setEntries(shell.getDirInfo("/sdcard/com.aero.control/", false)); restore_kernel.setEntryValues(shell.getDirInfo("/sdcard/com.aero.control/", false)); restore_kernel.setDialogIcon(R.drawable.restore_dark); restore_kernel.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object o) { final String s = (String) o; AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View layout = inflater.inflate(R.layout.about_screen, null); TextView aboutText = (TextView) layout.findViewById(R.id.aboutScreen); builder.setTitle(getText(R.string.backup_from) + " " + s); aboutText.setText(getText(R.string.restore_from_backup) + " " + s + " ?"); shell.remountSystem(); builder.setView(layout) .setPositiveButton(R.string.save, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // Delete old zImage first, then copy backup; String[] commands = new String[] { "rm -f " + zImage, "cp " + "/sdcard/com.aero.control/" + s + "/zImage" + " " + zImage, }; shell.setRootInfo(commands); Toast.makeText(getActivity(), R.string.need_reboot, Toast.LENGTH_LONG).show(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Do nothing } }); builder.show(); return true; }; }); backup_kernel.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View layout = inflater.inflate(R.layout.about_screen, null); TextView aboutText = (TextView) layout.findViewById(R.id.aboutScreen); builder.setTitle("Backup"); builder.setIcon(R.drawable.backup_dark); aboutText.setText(R.string.proceed_backup); builder.setView(layout) .setPositiveButton(R.string.save, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { try { update.copyFile(IMAGE, BACKUP_PATH, false); Toast.makeText(getActivity(), "Backup was successful!", Toast.LENGTH_LONG).show(); backup_kernel.setSummary(getText(R.string.last_backup_from) + " " + timeStamp); restore_kernel.setEnabled(true); } catch (IOException e) { Log.e("Aero", "A problem occured while saving a backup.", e); } } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Do nothing } }); builder.show(); return true; } ; }); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // We have to load the xml layout first; addPreferencesFromResource(R.layout.updater_fragment); PreferenceScreen root = this.getPreferenceScreen(); final Preference backup_kernel = root.findPreference("backup_kernel"); final Preference updater_kernel = root.findPreference("updater_kernel"); final ListPreference restore_kernel = (ListPreference) root.findPreference("restore_kernel"); // Disable them all; //backup_kernel.setEnabled(false); updater_kernel.setEnabled(false); //restore_kernel.setEnabled(false); // If device doesn't have this kernel path; if (shell.getInfo(zImage).equals("Unavailable")) backup_kernel.setEnabled(false); if (shell.getInfo(zImage).equals("Unavailable")) restore_kernel.setEnabled(false); // Fresh Start, no backup found; try { backup_kernel.setSummary(getText(R.string.last_backup_from)+ " " + shell.getDirInfo("/sdcard/com.aero.control/", false)[0]); restore_kernel.setEnabled(true); } catch (ArrayIndexOutOfBoundsException e) { backup_kernel.setSummary(getText(R.string.last_backup_from)+ " " + getText(R.string.unavailable)); restore_kernel.setEnabled(false); } restore_kernel.setEntries(shell.getDirInfo("/sdcard/com.aero.control/", false)); restore_kernel.setEntryValues(shell.getDirInfo("/sdcard/com.aero.control/", false)); restore_kernel.setDialogIcon(R.drawable.restore_dark); restore_kernel.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object o) { final String s = (String) o; AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View layout = inflater.inflate(R.layout.about_screen, null); TextView aboutText = (TextView) layout.findViewById(R.id.aboutScreen); builder.setTitle(getText(R.string.backup_from) + " " + s); aboutText.setText(getText(R.string.restore_from_backup) + " " + s + " ?"); shell.remountSystem(); builder.setView(layout) .setPositiveButton(R.string.save, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // Delete old zImage first, then copy backup; String[] commands = new String[] { "rm -f " + zImage, "cp " + "/sdcard/com.aero.control/" + s + "/zImage" + " " + zImage, }; shell.setRootInfo(commands); Toast.makeText(getActivity(), R.string.need_reboot, Toast.LENGTH_LONG).show(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Do nothing } }); builder.show(); return true; }; }); backup_kernel.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View layout = inflater.inflate(R.layout.about_screen, null); TextView aboutText = (TextView) layout.findViewById(R.id.aboutScreen); builder.setTitle("Backup"); builder.setIcon(R.drawable.backup_dark); aboutText.setText(R.string.proceed_backup); builder.setView(layout) .setPositiveButton(R.string.save, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { try { update.copyFile(IMAGE, BACKUP_PATH, false); Toast.makeText(getActivity(), "Backup was successful!", Toast.LENGTH_LONG).show(); backup_kernel.setSummary(getText(R.string.last_backup_from) + " " + timeStamp); restore_kernel.setEnabled(true); } catch (IOException e) { Log.e("Aero", "A problem occured while saving a backup.", e); } } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Do nothing } }); builder.show(); return true; } ; }); }
diff --git a/loci/formats/TiffTools.java b/loci/formats/TiffTools.java index 6af53b108..366e34a93 100644 --- a/loci/formats/TiffTools.java +++ b/loci/formats/TiffTools.java @@ -1,2613 +1,2614 @@ // // TiffTools.java // /* LOCI Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan, Eric Kjellman and Brian Loranger. This program 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 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats; import java.awt.image.BufferedImage; import java.awt.image.DataBuffer; import java.io.*; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.nio.*; import java.util.*; import loci.formats.codec.*; /** * A utility class for manipulating TIFF files. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/loci/formats/TiffTools.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/loci/formats/TiffTools.java">SVN</a></dd></dl> * * @author Curtis Rueden ctrueden at wisc.edu * @author Eric Kjellman egkjellman at wisc.edu * @author Melissa Linkert linkert at wisc.edu * @author Chris Allan callan at blackcat.ca */ public final class TiffTools { // -- Constants -- private static final boolean DEBUG = false; /** The number of bytes in each IFD entry. */ public static final int BYTES_PER_ENTRY = 12; /** The number of bytes in each IFD entry of a BigTIFF file. */ public static final int BIG_TIFF_BYTES_PER_ENTRY = 20; // non-IFD tags (for internal use) public static final int LITTLE_ENDIAN = 0; public static final int BIG_TIFF = 1; // IFD types public static final int BYTE = 1; public static final int ASCII = 2; public static final int SHORT = 3; public static final int LONG = 4; public static final int RATIONAL = 5; public static final int SBYTE = 6; public static final int UNDEFINED = 7; public static final int SSHORT = 8; public static final int SLONG = 9; public static final int SRATIONAL = 10; public static final int FLOAT = 11; public static final int DOUBLE = 12; public static final int LONG8 = 16; public static final int SLONG8 = 17; public static final int IFD8 = 18; public static final int[] BYTES_PER_ELEMENT = { -1, // invalid type 1, // BYTE 1, // ASCII 2, // SHORT 4, // LONG 8, // RATIONAL 1, // SBYTE 1, // UNDEFINED 2, // SSHORT 4, // SLONG 8, // SRATIONAL 4, // FLOAT 8, // DOUBLE -1, // invalid type -1, // invalid type -1, // invalid type -1, // invalid type 8, // LONG8 8, // SLONG8 8 // IFD8 }; // IFD tags public static final int NEW_SUBFILE_TYPE = 254; public static final int SUBFILE_TYPE = 255; public static final int IMAGE_WIDTH = 256; public static final int IMAGE_LENGTH = 257; public static final int BITS_PER_SAMPLE = 258; public static final int COMPRESSION = 259; public static final int PHOTOMETRIC_INTERPRETATION = 262; public static final int THRESHHOLDING = 263; public static final int CELL_WIDTH = 264; public static final int CELL_LENGTH = 265; public static final int FILL_ORDER = 266; public static final int DOCUMENT_NAME = 269; public static final int IMAGE_DESCRIPTION = 270; public static final int MAKE = 271; public static final int MODEL = 272; public static final int STRIP_OFFSETS = 273; public static final int ORIENTATION = 274; public static final int SAMPLES_PER_PIXEL = 277; public static final int ROWS_PER_STRIP = 278; public static final int STRIP_BYTE_COUNTS = 279; public static final int MIN_SAMPLE_VALUE = 280; public static final int MAX_SAMPLE_VALUE = 281; public static final int X_RESOLUTION = 282; public static final int Y_RESOLUTION = 283; public static final int PLANAR_CONFIGURATION = 284; public static final int PAGE_NAME = 285; public static final int X_POSITION = 286; public static final int Y_POSITION = 287; public static final int FREE_OFFSETS = 288; public static final int FREE_BYTE_COUNTS = 289; public static final int GRAY_RESPONSE_UNIT = 290; public static final int GRAY_RESPONSE_CURVE = 291; public static final int T4_OPTIONS = 292; public static final int T6_OPTIONS = 293; public static final int RESOLUTION_UNIT = 296; public static final int PAGE_NUMBER = 297; public static final int TRANSFER_FUNCTION = 301; public static final int SOFTWARE = 305; public static final int DATE_TIME = 306; public static final int ARTIST = 315; public static final int HOST_COMPUTER = 316; public static final int PREDICTOR = 317; public static final int WHITE_POINT = 318; public static final int PRIMARY_CHROMATICITIES = 319; public static final int COLOR_MAP = 320; public static final int HALFTONE_HINTS = 321; public static final int TILE_WIDTH = 322; public static final int TILE_LENGTH = 323; public static final int TILE_OFFSETS = 324; public static final int TILE_BYTE_COUNTS = 325; public static final int INK_SET = 332; public static final int INK_NAMES = 333; public static final int NUMBER_OF_INKS = 334; public static final int DOT_RANGE = 336; public static final int TARGET_PRINTER = 337; public static final int EXTRA_SAMPLES = 338; public static final int SAMPLE_FORMAT = 339; public static final int S_MIN_SAMPLE_VALUE = 340; public static final int S_MAX_SAMPLE_VALUE = 341; public static final int TRANSFER_RANGE = 342; public static final int JPEG_TABLES = 347; public static final int JPEG_PROC = 512; public static final int JPEG_INTERCHANGE_FORMAT = 513; public static final int JPEG_INTERCHANGE_FORMAT_LENGTH = 514; public static final int JPEG_RESTART_INTERVAL = 515; public static final int JPEG_LOSSLESS_PREDICTORS = 517; public static final int JPEG_POINT_TRANSFORMS = 518; public static final int JPEG_Q_TABLES = 519; public static final int JPEG_DC_TABLES = 520; public static final int JPEG_AC_TABLES = 521; public static final int Y_CB_CR_COEFFICIENTS = 529; public static final int Y_CB_CR_SUB_SAMPLING = 530; public static final int Y_CB_CR_POSITIONING = 531; public static final int REFERENCE_BLACK_WHITE = 532; public static final int COPYRIGHT = 33432; // compression types public static final int UNCOMPRESSED = 1; public static final int CCITT_1D = 2; public static final int GROUP_3_FAX = 3; public static final int GROUP_4_FAX = 4; public static final int LZW = 5; //public static final int JPEG = 6; public static final int JPEG = 7; public static final int PACK_BITS = 32773; public static final int PROPRIETARY_DEFLATE = 32946; public static final int DEFLATE = 8; public static final int THUNDERSCAN = 32809; public static final int NIKON = 34713; public static final int LURAWAVE = 65535; // photometric interpretation types public static final int WHITE_IS_ZERO = 0; public static final int BLACK_IS_ZERO = 1; public static final int RGB = 2; public static final int RGB_PALETTE = 3; public static final int TRANSPARENCY_MASK = 4; public static final int CMYK = 5; public static final int Y_CB_CR = 6; public static final int CIE_LAB = 8; public static final int CFA_ARRAY = -32733; // TIFF header constants public static final int MAGIC_NUMBER = 42; public static final int BIG_TIFF_MAGIC_NUMBER = 43; public static final int LITTLE = 0x49; public static final int BIG = 0x4d; // -- Constructor -- private TiffTools() { } // -- TiffTools API methods -- /** * Tests the given data block to see if it represents * the first few bytes of a TIFF file. */ public static boolean isValidHeader(byte[] block) { return checkHeader(block) != null; } /** * Checks the TIFF header. * @return true if little-endian, * false if big-endian, * or null if not a TIFF. */ public static Boolean checkHeader(byte[] block) { if (block.length < 4) return null; // byte order must be II or MM boolean littleEndian = block[0] == LITTLE && block[1] == LITTLE; // II boolean bigEndian = block[0] == BIG && block[1] == BIG; // MM if (!littleEndian && !bigEndian) return null; // check magic number (42) short magic = DataTools.bytesToShort(block, 2, littleEndian); if (magic != MAGIC_NUMBER && magic != BIG_TIFF_MAGIC_NUMBER) return null; return new Boolean(littleEndian); } /** Gets whether this is a BigTIFF IFD. */ public static boolean isBigTiff(Hashtable ifd) throws FormatException { return ((Boolean) getIFDValue(ifd, BIG_TIFF, false, Boolean.class)).booleanValue(); } /** Gets whether the TIFF information in the given IFD is little-endian. */ public static boolean isLittleEndian(Hashtable ifd) throws FormatException { return ((Boolean) getIFDValue(ifd, LITTLE_ENDIAN, true, Boolean.class)).booleanValue(); } // --------------------------- Reading TIFF files --------------------------- // -- IFD parsing methods -- /** * Gets all IFDs within the given TIFF file, or null * if the given file is not a valid TIFF file. */ public static Hashtable[] getIFDs(RandomAccessStream in) throws IOException { // check TIFF header Boolean result = checkHeader(in); if (result == null) return null; in.seek(2); boolean bigTiff = in.readShort() == BIG_TIFF_MAGIC_NUMBER; long offset = getFirstOffset(in, bigTiff); // compute maximum possible number of IFDs, for loop safety // each IFD must have at least one directory entry, which means that // each IFD must be at least 2 + 12 + 4 = 18 bytes in length long ifdMax = (in.length() - 8) / 18; // read in IFDs Vector v = new Vector(); for (long ifdNum=0; ifdNum<ifdMax; ifdNum++) { Hashtable ifd = getIFD(in, ifdNum, offset, bigTiff); if (ifd == null || ifd.size() <= 1) break; v.add(ifd); offset = bigTiff ? in.readLong() : in.readInt(); if (offset <= 0 || offset >= in.length()) break; } Hashtable[] ifds = new Hashtable[v.size()]; v.copyInto(ifds); return ifds; } /** * Gets the first IFD within the given TIFF file, or null * if the given file is not a valid TIFF file. */ public static Hashtable getFirstIFD(RandomAccessStream in) throws IOException { // check TIFF header Boolean result = checkHeader(in); if (result == null) return null; in.seek(2); boolean bigTiff = in.readShort() == BIG_TIFF_MAGIC_NUMBER; long offset = getFirstOffset(in, bigTiff); Hashtable ifd = getIFD(in, 0, offset, bigTiff); ifd.put(new Integer(BIG_TIFF), new Boolean(bigTiff)); return ifd; } /** * Retrieve a given entry from the first IFD in a stream. * * @param in the stream to retrieve the entry from. * @param tag the tag of the entry to be retrieved. * @return an object representing the entry's fields. * @throws IOException when there is an error accessing the stream <i>in</i>. */ public static TiffIFDEntry getFirstIFDEntry(RandomAccessStream in, int tag) throws IOException { // First lets re-position the file pointer by checking the TIFF header Boolean result = checkHeader(in); if (result == null) return null; in.seek(2); boolean bigTiff = in.readShort() == BIG_TIFF_MAGIC_NUMBER; // Get the offset of the first IFD long offset = getFirstOffset(in, bigTiff); // The following loosely resembles the logic of getIFD()... in.seek(offset); long numEntries = bigTiff ? in.readLong() : in.readShort() & 0xffff; for (int i = 0; i < numEntries; i++) { in.seek(offset + // The beginning of the IFD 2 + // The width of the initial numEntries field (bigTiff ? BIG_TIFF_BYTES_PER_ENTRY : BYTES_PER_ENTRY) * i); int entryTag = in.readShort() & 0xffff; // Skip this tag unless it matches the one we want if (entryTag != tag) continue; // Parse the entry's "Type" int entryType = in.readShort() & 0xffff; // Parse the entry's "ValueCount" int valueCount = bigTiff ? (int) (in.readLong() & 0xffffffff) : in.readInt(); if (valueCount < 0) { throw new RuntimeException("Count of '" + valueCount + "' unexpected."); } // Parse the entry's "ValueOffset" long valueOffset = bigTiff ? in.readLong() : in.readInt(); return new TiffIFDEntry(entryTag, entryType, valueCount, valueOffset); } throw new UnknownTagException(); } /** * Checks the TIFF header. * @return true if little-endian, * false if big-endian, * or null if not a TIFF. */ public static Boolean checkHeader(RandomAccessStream in) throws IOException { if (DEBUG) debug("getIFDs: reading IFD entries"); // start at the beginning of the file in.seek(0); byte[] header = new byte[4]; in.readFully(header); Boolean b = checkHeader(header); if (b != null) in.order(b.booleanValue()); return b; } /** * Gets offset to the first IFD, or -1 if stream is not TIFF. * Assumes the stream is positioned properly (checkHeader just called). */ public static long getFirstOffset(RandomAccessStream in) throws IOException { return getFirstOffset(in, false); } /** * Gets offset to the first IFD, or -1 if stream is not TIFF. * Assumes the stream is positioned properly (checkHeader just called). * * @param bigTiff true if this is a BigTIFF file (8 byte pointers). */ public static long getFirstOffset(RandomAccessStream in, boolean bigTiff) throws IOException { if (bigTiff) in.skipBytes(4); return bigTiff ? in.readLong() : in.readInt(); } /** Gets the IFD stored at the given offset. */ public static Hashtable getIFD(RandomAccessStream in, long ifdNum, long offset) throws IOException { return getIFD(in, ifdNum, offset, false); } /** Gets the IFD stored at the given offset. */ public static Hashtable getIFD(RandomAccessStream in, long ifdNum, long offset, boolean bigTiff) throws IOException { Hashtable ifd = new Hashtable(); // save little-endian flag to internal LITTLE_ENDIAN tag ifd.put(new Integer(LITTLE_ENDIAN), new Boolean(in.isLittleEndian())); ifd.put(new Integer(BIG_TIFF), new Boolean(bigTiff)); // read in directory entries for this IFD if (DEBUG) { debug("getIFDs: seeking IFD #" + ifdNum + " at " + offset); } in.seek(offset); long numEntries = bigTiff ? in.readLong() : in.readShort() & 0xffff; if (DEBUG) debug("getIFDs: " + numEntries + " directory entries to read"); if (numEntries == 0 || numEntries == 1) return ifd; int bytesPerEntry = bigTiff ? BIG_TIFF_BYTES_PER_ENTRY : BYTES_PER_ENTRY; int baseOffset = bigTiff ? 8 : 2; int threshhold = bigTiff ? 8 : 4; for (int i=0; i<numEntries; i++) { in.seek(offset + baseOffset + bytesPerEntry * i); int tag = in.readShort() & 0xffff; int type = in.readShort() & 0xffff; // BigTIFF case is a slight hack int count = bigTiff ? (int) (in.readLong() & 0xffffffff) : in.readInt(); if (DEBUG) { debug("getIFDs: read " + getIFDTagName(tag) + " (type=" + getIFDTypeName(type) + "; count=" + count + ")"); } if (count < 0) return null; // invalid data Object value = null; if (type == BYTE) { // 8-bit unsigned integer if (count > threshhold) { long pointer = bigTiff ? in.readLong() : in.readInt(); in.seek(pointer); } if (count == 1) value = new Short(in.readByte()); else { short[] bytes = new short[count]; for (int j=0; j<count; j++) { bytes[j] = in.readByte(); if (bytes[j] < 0) bytes[j] += 255; } value = bytes; } } else if (type == ASCII) { // 8-bit byte that contain a 7-bit ASCII code; // the last byte must be NUL (binary zero) byte[] ascii = new byte[count]; if (count > threshhold) { long pointer = bigTiff ? in.readLong() : in.readInt(); in.seek(pointer); } in.read(ascii); // count number of null terminators int nullCount = 0; for (int j=0; j<count; j++) { if (ascii[j] == 0 || j == count - 1) nullCount++; } // convert character array to array of strings String[] strings = nullCount == 1 ? null : new String[nullCount]; String s = null; int c = 0, ndx = -1; for (int j=0; j<count; j++) { if (ascii[j] == 0) { s = new String(ascii, ndx + 1, j - ndx - 1); ndx = j; } else if (j == count - 1) { // handle non-null-terminated strings s = new String(ascii, ndx + 1, j - ndx); } else s = null; if (strings != null && s != null) strings[c++] = s; } value = strings == null ? (Object) s : strings; } else if (type == SHORT) { // 16-bit (2-byte) unsigned integer if (count > threshhold / 2) { long pointer = bigTiff ? in.readLong() : in.readInt(); in.seek(pointer); } if (count == 1) value = new Integer(in.readShort()); else { int[] shorts = new int[count]; for (int j=0; j<count; j++) { shorts[j] = in.readShort() & 0xffff; } value = shorts; } } else if (type == LONG) { // 32-bit (4-byte) unsigned integer if (count > threshhold / 4) { long pointer = bigTiff ? in.readLong() : in.readInt(); in.seek(pointer); } if (count == 1) value = new Long(in.readInt()); else { long[] longs = new long[count]; for (int j=0; j<count; j++) longs[j] = in.readInt(); value = longs; } } else if (type == LONG8 || type == SLONG8 || type == IFD8) { if (count > threshhold / 8) { long pointer = bigTiff ? in.readLong() : in.readInt(); in.seek(pointer); } if (count == 1) value = new Long(in.readLong()); else { long[] longs = new long[count]; for (int j=0; j<count; j++) longs[j] = in.readLong(); value = longs; } } else if (type == RATIONAL || type == SRATIONAL) { // Two LONGs: the first represents the numerator of a fraction; // the second, the denominator // Two SLONG's: the first represents the numerator of a fraction, // the second the denominator long pointer = bigTiff ? in.readLong() : in.readInt(); if (count > threshhold / 8) in.seek(pointer); if (count == 1) value = new TiffRational(in.readInt(), in.readInt()); else { TiffRational[] rationals = new TiffRational[count]; for (int j=0; j<count; j++) { rationals[j] = new TiffRational(in.readInt(), in.readInt()); } value = rationals; } } else if (type == SBYTE || type == UNDEFINED) { // SBYTE: An 8-bit signed (twos-complement) integer // UNDEFINED: An 8-bit byte that may contain anything, // depending on the definition of the field if (count > threshhold) { long pointer = bigTiff ? in.readLong() : in.readInt(); in.seek(pointer); } if (count == 1) value = new Byte(in.readByte()); else { byte[] sbytes = new byte[count]; in.readFully(sbytes); value = sbytes; } } else if (type == SSHORT) { // A 16-bit (2-byte) signed (twos-complement) integer if (count > threshhold / 2) { long pointer = bigTiff ? in.readLong() : in.readInt(); in.seek(pointer); } if (count == 1) value = new Short(in.readShort()); else { short[] sshorts = new short[count]; for (int j=0; j<count; j++) sshorts[j] = in.readShort(); value = sshorts; } } else if (type == SLONG) { // A 32-bit (4-byte) signed (twos-complement) integer if (count > threshhold / 4) { long pointer = bigTiff ? in.readLong() : in.readInt(); in.seek(pointer); } if (count == 1) value = new Integer(in.readInt()); else { int[] slongs = new int[count]; for (int j=0; j<count; j++) slongs[j] = in.readInt(); value = slongs; } } else if (type == FLOAT) { // Single precision (4-byte) IEEE format if (count > threshhold / 4) { long pointer = bigTiff ? in.readLong() : in.readInt(); in.seek(pointer); } if (count == 1) value = new Float(in.readFloat()); else { float[] floats = new float[count]; for (int j=0; j<count; j++) floats[j] = in.readFloat(); value = floats; } } else if (type == DOUBLE) { // Double precision (8-byte) IEEE format long pointer = bigTiff ? in.readLong() : in.readInt(); in.seek(pointer); if (count == 1) value = new Double(in.readDouble()); else { double[] doubles = new double[count]; for (int j=0; j<count; j++) { doubles[j] = in.readDouble(); } value = doubles; } } if (value != null) ifd.put(new Integer(tag), value); } in.seek(offset + baseOffset + bytesPerEntry * numEntries); return ifd; } /** Gets the name of the IFD tag encoded by the given number. */ public static String getIFDTagName(int tag) { return getFieldName(tag); } /** Gets the name of the IFD type encoded by the given number. */ public static String getIFDTypeName(int type) { return getFieldName(type); } /** * This method uses reflection to scan the values of this class's * static fields, returning the first matching field's name. It is * probably not very efficient, and is mainly intended for debugging. */ public static String getFieldName(int value) { Field[] fields = TiffTools.class.getFields(); for (int i=0; i<fields.length; i++) { try { if (fields[i].getInt(null) == value) return fields[i].getName(); } catch (IllegalAccessException exc) { } catch (IllegalArgumentException exc) { } } return "" + value; } /** Gets the given directory entry value from the specified IFD. */ public static Object getIFDValue(Hashtable ifd, int tag) { return ifd.get(new Integer(tag)); } /** * Gets the given directory entry value from the specified IFD, * performing some error checking. */ public static Object getIFDValue(Hashtable ifd, int tag, boolean checkNull, Class checkClass) throws FormatException { Object value = ifd.get(new Integer(tag)); if (checkNull && value == null) { throw new FormatException( getIFDTagName(tag) + " directory entry not found"); } if (checkClass != null && value != null && !checkClass.isInstance(value)) { // wrap object in array of length 1, if appropriate Class cType = checkClass.getComponentType(); Object array = null; if (cType == value.getClass()) { array = Array.newInstance(value.getClass(), 1); Array.set(array, 0, value); } if (cType == boolean.class && value instanceof Boolean) { array = Array.newInstance(boolean.class, 1); Array.setBoolean(array, 0, ((Boolean) value).booleanValue()); } else if (cType == byte.class && value instanceof Byte) { array = Array.newInstance(byte.class, 1); Array.setByte(array, 0, ((Byte) value).byteValue()); } else if (cType == char.class && value instanceof Character) { array = Array.newInstance(char.class, 1); Array.setChar(array, 0, ((Character) value).charValue()); } else if (cType == double.class && value instanceof Double) { array = Array.newInstance(double.class, 1); Array.setDouble(array, 0, ((Double) value).doubleValue()); } else if (cType == float.class && value instanceof Float) { array = Array.newInstance(float.class, 1); Array.setFloat(array, 0, ((Float) value).floatValue()); } else if (cType == int.class && value instanceof Integer) { array = Array.newInstance(int.class, 1); Array.setInt(array, 0, ((Integer) value).intValue()); } else if (cType == long.class && value instanceof Long) { array = Array.newInstance(long.class, 1); Array.setLong(array, 0, ((Long) value).longValue()); } else if (cType == short.class && value instanceof Short) { array = Array.newInstance(short.class, 1); Array.setShort(array, 0, ((Short) value).shortValue()); } if (array != null) return array; throw new FormatException(getIFDTagName(tag) + " directory entry is the wrong type (got " + value.getClass().getName() + ", expected " + checkClass.getName()); } return value; } /** * Gets the given directory entry value in long format from the * specified IFD, performing some error checking. */ public static long getIFDLongValue(Hashtable ifd, int tag, boolean checkNull, long defaultValue) throws FormatException { long value = defaultValue; Number number = (Number) getIFDValue(ifd, tag, checkNull, Number.class); if (number != null) value = number.longValue(); return value; } /** * Gets the given directory entry value in int format from the * specified IFD, or -1 if the given directory does not exist. */ public static int getIFDIntValue(Hashtable ifd, int tag) { int value = -1; try { value = getIFDIntValue(ifd, tag, false, -1); } catch (FormatException exc) { } return value; } /** * Gets the given directory entry value in int format from the * specified IFD, performing some error checking. */ public static int getIFDIntValue(Hashtable ifd, int tag, boolean checkNull, int defaultValue) throws FormatException { int value = defaultValue; Number number = (Number) getIFDValue(ifd, tag, checkNull, Number.class); if (number != null) value = number.intValue(); return value; } /** * Gets the given directory entry value in rational format from the * specified IFD, performing some error checking. */ public static TiffRational getIFDRationalValue(Hashtable ifd, int tag, boolean checkNull) throws FormatException { return (TiffRational) getIFDValue(ifd, tag, checkNull, TiffRational.class); } /** * Gets the given directory entry values in long format * from the specified IFD, performing some error checking. */ public static long[] getIFDLongArray(Hashtable ifd, int tag, boolean checkNull) throws FormatException { Object value = getIFDValue(ifd, tag, checkNull, null); long[] results = null; if (value instanceof long[]) results = (long[]) value; else if (value instanceof Number) { results = new long[] {((Number) value).longValue()}; } else if (value instanceof Number[]) { Number[] numbers = (Number[]) value; results = new long[numbers.length]; for (int i=0; i<results.length; i++) results[i] = numbers[i].longValue(); } else if (value instanceof int[]) { // convert int[] to long[] int[] integers = (int[]) value; results = new long[integers.length]; for (int i=0; i<integers.length; i++) results[i] = integers[i]; } else if (value != null) { throw new FormatException(getIFDTagName(tag) + " directory entry is the wrong type (got " + value.getClass().getName() + ", expected Number, long[], Number[] or int[])"); } return results; } /** * Gets the given directory entry values in int format * from the specified IFD, performing some error checking. */ public static int[] getIFDIntArray(Hashtable ifd, int tag, boolean checkNull) throws FormatException { Object value = getIFDValue(ifd, tag, checkNull, null); int[] results = null; if (value instanceof int[]) results = (int[]) value; else if (value instanceof Number) { results = new int[] {((Number) value).intValue()}; } else if (value instanceof Number[]) { Number[] numbers = (Number[]) value; results = new int[numbers.length]; for (int i=0; i<results.length; i++) results[i] = numbers[i].intValue(); } else if (value != null) { throw new FormatException(getIFDTagName(tag) + " directory entry is the wrong type (got " + value.getClass().getName() + ", expected Number, int[] or Number[])"); } return results; } /** * Gets the given directory entry values in short format * from the specified IFD, performing some error checking. */ public static short[] getIFDShortArray(Hashtable ifd, int tag, boolean checkNull) throws FormatException { Object value = getIFDValue(ifd, tag, checkNull, null); short[] results = null; if (value instanceof short[]) results = (short[]) value; else if (value instanceof Number) { results = new short[] {((Number) value).shortValue()}; } else if (value instanceof Number[]) { Number[] numbers = (Number[]) value; results = new short[numbers.length]; for (int i=0; i<results.length; i++) { results[i] = numbers[i].shortValue(); } } else if (value != null) { throw new FormatException(getIFDTagName(tag) + " directory entry is the wrong type (got " + value.getClass().getName() + ", expected Number, short[] or Number[])"); } return results; } /** Convenience method for obtaining the ImageDescription from an IFD. */ public static String getComment(Hashtable ifd) { if (ifd == null) return null; // extract comment Object o = TiffTools.getIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION); String comment = null; if (o instanceof String) comment = (String) o; else if (o instanceof String[]) { String[] s = (String[]) o; if (s.length > 0) comment = s[0]; } else if (o != null) comment = o.toString(); if (comment != null) { // sanitize line feeds comment = comment.replaceAll("\r\n", "\n"); comment = comment.replaceAll("\r", "\n"); } return comment; } /** Convenience method for obtaining a file's first ImageDescription. */ public static String getComment(String id) throws FormatException, IOException { // read first IFD RandomAccessStream in = new RandomAccessStream(id); Hashtable ifd = TiffTools.getFirstIFD(in); in.close(); return getComment(ifd); } // -- Image reading methods -- /** Reads the image defined in the given IFD from the specified file. */ public static byte[][] getSamples(Hashtable ifd, RandomAccessStream in) throws FormatException, IOException { int samplesPerPixel = getSamplesPerPixel(ifd); int photoInterp = getPhotometricInterpretation(ifd); int bpp = getBitsPerSample(ifd)[0]; while ((bpp % 8) != 0) bpp++; bpp /= 8; long width = getImageWidth(ifd); long length = getImageLength(ifd); byte[] b = new byte[(int) (width * length * samplesPerPixel * bpp)]; getSamples(ifd, in, b); byte[][] samples = new byte[samplesPerPixel][(int) (width * length * bpp)]; for (int i=0; i<samplesPerPixel; i++) { System.arraycopy(b, (int) (i*width*length*bpp), samples[i], 0, samples[i].length); } b = null; return samples; } public static byte[] getSamples(Hashtable ifd, RandomAccessStream in, byte[] buf) throws FormatException, IOException { if (DEBUG) debug("parsing IFD entries"); // get internal non-IFD entries boolean littleEndian = isLittleEndian(ifd); in.order(littleEndian); // get relevant IFD entries long imageWidth = getImageWidth(ifd); long imageLength = getImageLength(ifd); int[] bitsPerSample = getBitsPerSample(ifd); int samplesPerPixel = getSamplesPerPixel(ifd); int compression = getCompression(ifd); int photoInterp = getPhotometricInterpretation(ifd); long[] stripOffsets = getStripOffsets(ifd); long[] stripByteCounts = getStripByteCounts(ifd); long[] rowsPerStripArray = getRowsPerStrip(ifd); boolean fakeByteCounts = stripByteCounts == null; boolean fakeRPS = rowsPerStripArray == null; boolean isTiled = stripOffsets == null; long[] maxes = getIFDLongArray(ifd, MAX_SAMPLE_VALUE, false); long maxValue = maxes == null ? 0 : maxes[0]; if (isTiled) { stripOffsets = getIFDLongArray(ifd, TILE_OFFSETS, true); stripByteCounts = getIFDLongArray(ifd, TILE_BYTE_COUNTS, true); rowsPerStripArray = new long[] {imageLength}; } else if (fakeByteCounts) { // technically speaking, this shouldn't happen (since TIFF writers are // required to write the StripByteCounts tag), but we'll support it // anyway // don't rely on RowsPerStrip, since it's likely that if the file doesn't // have the StripByteCounts tag, it also won't have the RowsPerStrip tag stripByteCounts = new long[stripOffsets.length]; if (stripByteCounts.length == 1) { stripByteCounts[0] = imageWidth * imageLength * (bitsPerSample[0] / 8); } else { stripByteCounts[0] = stripOffsets[0]; for (int i=1; i<stripByteCounts.length; i++) { stripByteCounts[i] = stripOffsets[i] - stripByteCounts[i-1]; } } } boolean lastBitsZero = bitsPerSample[bitsPerSample.length - 1] == 0; if (fakeRPS && !isTiled) { // create a false rowsPerStripArray if one is not present // it's sort of a cheap hack, but here's how it's done: // RowsPerStrip = stripByteCounts / (imageLength * bitsPerSample) // since stripByteCounts and bitsPerSample are arrays, we have to // iterate through each item rowsPerStripArray = new long[bitsPerSample.length]; long temp = stripByteCounts[0]; stripByteCounts = new long[bitsPerSample.length]; for (int i=0; i<stripByteCounts.length; i++) stripByteCounts[i] = temp; temp = bitsPerSample[0]; if (temp == 0) temp = 8; bitsPerSample = new int[bitsPerSample.length]; for (int i=0; i<bitsPerSample.length; i++) bitsPerSample[i] = (int) temp; temp = stripOffsets[0]; /* stripOffsets = new long[bitsPerSample.length]; for (int i=0; i<bitsPerSample.length; i++) { stripOffsets[i] = i == 0 ? temp : stripOffsets[i - 1] + stripByteCounts[i]; } */ // we have two files that reverse the endianness for BitsPerSample, // StripOffsets, and StripByteCounts if (bitsPerSample[0] > 64) { byte[] bps = new byte[2]; byte[] stripOffs = new byte[4]; byte[] byteCounts = new byte[4]; if (littleEndian) { bps[0] = (byte) (bitsPerSample[0] & 0xff); bps[1] = (byte) ((bitsPerSample[0] >>> 8) & 0xff); int ndx = stripOffsets.length - 1; stripOffs[0] = (byte) (stripOffsets[ndx] & 0xff); stripOffs[1] = (byte) ((stripOffsets[ndx] >>> 8) & 0xff); stripOffs[2] = (byte) ((stripOffsets[ndx] >>> 16) & 0xff); stripOffs[3] = (byte) ((stripOffsets[ndx] >>> 24) & 0xff); ndx = stripByteCounts.length - 1; byteCounts[0] = (byte) (stripByteCounts[ndx] & 0xff); byteCounts[1] = (byte) ((stripByteCounts[ndx] >>> 8) & 0xff); byteCounts[2] = (byte) ((stripByteCounts[ndx] >>> 16) & 0xff); byteCounts[3] = (byte) ((stripByteCounts[ndx] >>> 24) & 0xff); } else { bps[1] = (byte) ((bitsPerSample[0] >>> 16) & 0xff); bps[0] = (byte) ((bitsPerSample[0] >>> 24) & 0xff); stripOffs[3] = (byte) (stripOffsets[0] & 0xff); stripOffs[2] = (byte) ((stripOffsets[0] >>> 8) & 0xff); stripOffs[1] = (byte) ((stripOffsets[0] >>> 16) & 0xff); stripOffs[0] = (byte) ((stripOffsets[0] >>> 24) & 0xff); byteCounts[3] = (byte) (stripByteCounts[0] & 0xff); byteCounts[2] = (byte) ((stripByteCounts[0] >>> 8) & 0xff); byteCounts[1] = (byte) ((stripByteCounts[0] >>> 16) & 0xff); byteCounts[0] = (byte) ((stripByteCounts[0] >>> 24) & 0xff); } bitsPerSample[0] = DataTools.bytesToInt(bps, !littleEndian); stripOffsets[0] = DataTools.bytesToInt(stripOffs, !littleEndian); stripByteCounts[0] = DataTools.bytesToInt(byteCounts, !littleEndian); } if (rowsPerStripArray.length == 1 && stripByteCounts[0] != (imageWidth * imageLength * (bitsPerSample[0] / 8)) && compression == UNCOMPRESSED) { for (int i=0; i<stripByteCounts.length; i++) { stripByteCounts[i] = imageWidth * imageLength * (bitsPerSample[i] / 8); stripOffsets[0] = (int) (in.length() - stripByteCounts[0] - 48 * imageWidth); if (i != 0) { stripOffsets[i] = stripOffsets[i - 1] + stripByteCounts[i]; } in.seek((int) stripOffsets[i]); in.read(buf, (int) (i*imageWidth), (int) imageWidth); boolean isZero = true; for (int j=0; j<imageWidth; j++) { if (buf[(int) (i*imageWidth + j)] != 0) { isZero = false; break; } } while (isZero) { stripOffsets[i] -= imageWidth; in.seek((int) stripOffsets[i]); in.read(buf, (int) (i*imageWidth), (int) imageWidth); for (int j=0; j<imageWidth; j++) { if (buf[(int) (i*imageWidth + j)] != 0) { isZero = false; stripOffsets[i] -= (stripByteCounts[i] - imageWidth); break; } } } } } for (int i=0; i<bitsPerSample.length; i++) { // case 1: we're still within bitsPerSample array bounds if (i < bitsPerSample.length) { if (i == samplesPerPixel) { bitsPerSample[i] = 0; lastBitsZero = true; } // remember that the universe collapses when we divide by 0 if (bitsPerSample[i] != 0) { rowsPerStripArray[i] = (long) stripByteCounts[i] / (imageWidth * (bitsPerSample[i] / 8)); } else if (bitsPerSample[i] == 0 && i > 0) { rowsPerStripArray[i] = (long) stripByteCounts[i] / (imageWidth * (bitsPerSample[i - 1] / 8)); bitsPerSample[i] = bitsPerSample[i - 1]; } else { throw new FormatException("BitsPerSample is 0"); } } // case 2: we're outside bitsPerSample array bounds else if (i >= bitsPerSample.length) { rowsPerStripArray[i] = (long) stripByteCounts[i] / (imageWidth * (bitsPerSample[bitsPerSample.length - 1] / 8)); } } for (int i=0; i<stripByteCounts.length; i++) { stripByteCounts[i] *= 2; } } if (lastBitsZero) { bitsPerSample[bitsPerSample.length - 1] = 0; //samplesPerPixel--; } TiffRational xResolution = getIFDRationalValue(ifd, X_RESOLUTION, false); TiffRational yResolution = getIFDRationalValue(ifd, Y_RESOLUTION, false); int planarConfig = getIFDIntValue(ifd, PLANAR_CONFIGURATION, false, 1); int resolutionUnit = getIFDIntValue(ifd, RESOLUTION_UNIT, false, 2); if (xResolution == null || yResolution == null) resolutionUnit = 0; int[] colorMap = getIFDIntArray(ifd, COLOR_MAP, false); int predictor = getIFDIntValue(ifd, PREDICTOR, false, 1); // If the subsequent color maps are empty, use the first IFD's color map //if (colorMap == null) { // colorMap = getIFDIntArray(getFirstIFD(in), COLOR_MAP, false); //} // use special color map for YCbCr if (photoInterp == Y_CB_CR) { int[] tempColorMap = getIFDIntArray(ifd, Y_CB_CR_COEFFICIENTS, false); int[] refBlackWhite = getIFDIntArray(ifd, REFERENCE_BLACK_WHITE, false); colorMap = new int[tempColorMap.length + refBlackWhite.length]; System.arraycopy(tempColorMap, 0, colorMap, 0, tempColorMap.length); System.arraycopy(refBlackWhite, 0, colorMap, tempColorMap.length, refBlackWhite.length); } if (DEBUG) { StringBuffer sb = new StringBuffer(); sb.append("IFD directory entry values:"); sb.append("\n\tLittleEndian="); sb.append(littleEndian); sb.append("\n\tImageWidth="); sb.append(imageWidth); sb.append("\n\tImageLength="); sb.append(imageLength); sb.append("\n\tBitsPerSample="); sb.append(bitsPerSample[0]); for (int i=1; i<bitsPerSample.length; i++) { sb.append(","); sb.append(bitsPerSample[i]); } sb.append("\n\tSamplesPerPixel="); sb.append(samplesPerPixel); sb.append("\n\tCompression="); sb.append(compression); sb.append("\n\tPhotometricInterpretation="); sb.append(photoInterp); sb.append("\n\tStripOffsets="); sb.append(stripOffsets[0]); for (int i=1; i<stripOffsets.length; i++) { sb.append(","); sb.append(stripOffsets[i]); } sb.append("\n\tRowsPerStrip="); sb.append(rowsPerStripArray[0]); for (int i=1; i<rowsPerStripArray.length; i++) { sb.append(","); sb.append(rowsPerStripArray[i]); } sb.append("\n\tStripByteCounts="); sb.append(stripByteCounts[0]); for (int i=1; i<stripByteCounts.length; i++) { sb.append(","); sb.append(stripByteCounts[i]); } sb.append("\n\tXResolution="); sb.append(xResolution); sb.append("\n\tYResolution="); sb.append(yResolution); sb.append("\n\tPlanarConfiguration="); sb.append(planarConfig); sb.append("\n\tResolutionUnit="); sb.append(resolutionUnit); sb.append("\n\tColorMap="); if (colorMap == null) sb.append("null"); else { sb.append(colorMap[0]); for (int i=1; i<colorMap.length; i++) { sb.append(","); sb.append(colorMap[i]); } } sb.append("\n\tPredictor="); sb.append(predictor); debug(sb.toString()); } for (int i=0; i<samplesPerPixel; i++) { if (bitsPerSample[i] < 1) { throw new FormatException("Illegal BitsPerSample (" + bitsPerSample[i] + ")"); } // don't support odd numbers of bits (except for 1) else if (bitsPerSample[i] % 2 != 0 && bitsPerSample[i] != 1) { throw new FormatException("Sorry, unsupported BitsPerSample (" + bitsPerSample[i] + ")"); } } if (bitsPerSample.length < samplesPerPixel) { throw new FormatException("BitsPerSample length (" + bitsPerSample.length + ") does not match SamplesPerPixel (" + samplesPerPixel + ")"); } else if (photoInterp == TRANSPARENCY_MASK) { throw new FormatException( "Sorry, Transparency Mask PhotometricInterpretation is not supported"); } else if (photoInterp == Y_CB_CR) { throw new FormatException( "Sorry, YCbCr PhotometricInterpretation is not supported"); } else if (photoInterp == CIE_LAB) { throw new FormatException( "Sorry, CIELAB PhotometricInterpretation is not supported"); } else if (photoInterp != WHITE_IS_ZERO && photoInterp != BLACK_IS_ZERO && photoInterp != RGB && photoInterp != RGB_PALETTE && photoInterp != CMYK && photoInterp != Y_CB_CR && photoInterp != CFA_ARRAY) { throw new FormatException("Unknown PhotometricInterpretation (" + photoInterp + ")"); } long rowsPerStrip = rowsPerStripArray[0]; for (int i=1; i<rowsPerStripArray.length; i++) { if (rowsPerStrip != rowsPerStripArray[i]) { throw new FormatException( "Sorry, non-uniform RowsPerStrip is not supported"); } } long numStrips = (imageLength + rowsPerStrip - 1) / rowsPerStrip; if (isTiled || fakeRPS) numStrips = stripOffsets.length; if (planarConfig == 2) numStrips *= samplesPerPixel; if (stripOffsets.length < numStrips && !fakeRPS) { throw new FormatException("StripOffsets length (" + stripOffsets.length + ") does not match expected " + "number of strips (" + numStrips + ")"); } else if (fakeRPS) numStrips = stripOffsets.length; if (stripByteCounts.length < numStrips) { throw new FormatException("StripByteCounts length (" + stripByteCounts.length + ") does not match expected " + "number of strips (" + numStrips + ")"); } if (imageWidth > Integer.MAX_VALUE || imageLength > Integer.MAX_VALUE || imageWidth * imageLength > Integer.MAX_VALUE) { throw new FormatException("Sorry, ImageWidth x ImageLength > " + Integer.MAX_VALUE + " is not supported (" + imageWidth + " x " + imageLength + ")"); } int numSamples = (int) (imageWidth * imageLength); if (planarConfig != 1 && planarConfig != 2) { throw new FormatException( "Unknown PlanarConfiguration (" + planarConfig + ")"); } // read in image strips if (DEBUG) { debug("reading image data (samplesPerPixel=" + samplesPerPixel + "; numSamples=" + numSamples + ")"); } if (photoInterp == CFA_ARRAY) { int[] tempMap = new int[colorMap.length + 2]; System.arraycopy(colorMap, 0, tempMap, 0, colorMap.length); tempMap[tempMap.length - 2] = (int) imageWidth; tempMap[tempMap.length - 1] = (int) imageLength; colorMap = tempMap; } if (stripOffsets.length > 1 && (stripOffsets[stripOffsets.length - 1] == stripOffsets[stripOffsets.length - 2])) { long[] tmp = stripOffsets; stripOffsets = new long[tmp.length - 1]; System.arraycopy(tmp, 0, stripOffsets, 0, stripOffsets.length); numStrips--; } short[][] samples = new short[samplesPerPixel][numSamples]; byte[] altBytes = new byte[0]; if (bitsPerSample[0] == 16) littleEndian = !littleEndian; byte[] jpegTable = null; if (compression == JPEG) { jpegTable = (byte[]) TiffTools.getIFDValue(ifd, JPEG_TABLES); } // number of uncompressed bytes in a strip int size = (int) (imageWidth * (bitsPerSample[0] / 8) * rowsPerStrip * samplesPerPixel); if (isTiled) { long tileWidth = getIFDLongValue(ifd, TILE_WIDTH, true, 0); long tileLength = getIFDLongValue(ifd, TILE_LENGTH, true, 0); byte[] data = new byte[(int) (imageWidth * imageLength * samplesPerPixel * (bitsPerSample[0] / 8))]; int row = 0; int col = 0; int bytes = bitsPerSample[0] / 8; for (int i=0; i<stripOffsets.length; i++) { byte[] b = new byte[(int) stripByteCounts[i]]; in.seek(stripOffsets[i]); in.read(b); int len = (int) (tileWidth * tileLength * samplesPerPixel * (bitsPerSample[0] / 8)); if (jpegTable != null) { byte[] q = new byte[jpegTable.length + b.length - 4]; System.arraycopy(jpegTable, 0, q, 0, jpegTable.length - 2); System.arraycopy(b, 2, q, jpegTable.length - 2, b.length - 2); b = uncompress(q, compression, len); } else b = uncompress(b, compression, len); int ext = (int) (b.length / (tileWidth * tileLength)); int rowBytes = (int) (tileWidth * ext); - if (tileWidth + col > imageWidth) { - rowBytes = (int) ((imageWidth - col) * ext); - } for (int j=0; j<tileLength; j++) { if (row + j < imageLength) { - System.arraycopy(b, rowBytes*j, data, - (int) ((row + j)*imageWidth*ext + ext*col), rowBytes); + int rowLen = rowBytes; + int offset = (int) ((row + j) * imageWidth * ext + ext * col); + if (col + tileWidth > imageWidth) { + rowLen = ext * (int) (imageWidth - col); + } + System.arraycopy(b, rowBytes*j, data, offset, rowLen); } else break; } // update row and column col += (int) tileWidth; if (col >= imageWidth) { row += (int) tileLength; col = 0; } } undifference(data, bitsPerSample, imageWidth, planarConfig, predictor, littleEndian); unpackBytes(samples, 0, data, bitsPerSample, photoInterp, colorMap, littleEndian, maxValue, planarConfig, 0, 1, imageWidth); } else { int overallOffset = 0; for (int strip=0, row=0; strip<numStrips; strip++, row+=rowsPerStrip) { try { if (DEBUG) debug("reading image strip #" + strip); in.seek((int) stripOffsets[strip]); if (stripByteCounts[strip] > Integer.MAX_VALUE) { throw new FormatException("Sorry, StripByteCounts > " + Integer.MAX_VALUE + " is not supported"); } byte[] bytes = new byte[(int) stripByteCounts[strip]]; in.read(bytes); if (compression != PACK_BITS) { if (jpegTable != null) { byte[] q = new byte[jpegTable.length + bytes.length - 4]; System.arraycopy(jpegTable, 0, q, 0, jpegTable.length - 2); System.arraycopy(bytes, 2, q, jpegTable.length - 2, bytes.length - 2); bytes = uncompress(q, compression, size); } else bytes = uncompress(bytes, compression, size); undifference(bytes, bitsPerSample, imageWidth, planarConfig, predictor, littleEndian); int offset = (int) (imageWidth * row); if (planarConfig == 2) { offset = overallOffset / samplesPerPixel; } unpackBytes(samples, offset, bytes, bitsPerSample, photoInterp, colorMap, littleEndian, maxValue, planarConfig, strip, (int) numStrips, imageWidth); overallOffset += bytes.length / bitsPerSample.length; } else { // concatenate contents of bytes to altBytes byte[] tempPackBits = new byte[altBytes.length]; System.arraycopy(altBytes, 0, tempPackBits, 0, altBytes.length); altBytes = new byte[altBytes.length + bytes.length]; System.arraycopy(tempPackBits, 0, altBytes, 0, tempPackBits.length); System.arraycopy(bytes, 0, altBytes, tempPackBits.length, bytes.length); } } catch (Exception e) { // CTR TODO - eliminate catch-all exception handling if (strip == 0) { if (e instanceof FormatException) throw (FormatException) e; else throw new FormatException(e); } byte[] bytes = new byte[samples[0].length]; undifference(bytes, bitsPerSample, imageWidth, planarConfig, predictor, littleEndian); int offset = (int) (imageWidth * row); if (planarConfig == 2) offset = overallOffset / samplesPerPixel; unpackBytes(samples, offset, bytes, bitsPerSample, photoInterp, colorMap, littleEndian, maxValue, planarConfig, strip, (int) numStrips, imageWidth); overallOffset += bytes.length / bitsPerSample.length; } } } // only do this if the image uses PackBits compression if (altBytes.length != 0) { altBytes = uncompress(altBytes, compression, size); undifference(altBytes, bitsPerSample, imageWidth, planarConfig, predictor, littleEndian); unpackBytes(samples, (int) imageWidth, altBytes, bitsPerSample, photoInterp, colorMap, littleEndian, maxValue, planarConfig, 0, 1, imageWidth); } // construct field if (DEBUG) debug("constructing image"); // Since the lowest common denominator for all pixel operations is "byte" // we're going to normalize everything to byte. if (bitsPerSample[0] == 12) bitsPerSample[0] = 16; if (photoInterp == CFA_ARRAY) { samples = ImageTools.demosaic(samples, (int) imageWidth, (int) imageLength); } if (bitsPerSample[0] == 16) { int pt = 0; for (int i = 0; i < samplesPerPixel; i++) { for (int j = 0; j < numSamples; j++) { buf[pt++] = (byte) ((samples[i][j] & 0xff00) >> 8); buf[pt++] = (byte) (samples[i][j] & 0xff); } } } else if (bitsPerSample[0] == 32) { int pt = 0; for (int i=0; i<samplesPerPixel; i++) { for (int j=0; j<numSamples; j++) { buf[pt++] = (byte) ((samples[i][j] & 0xff000000) >> 24); buf[pt++] = (byte) ((samples[i][j] & 0xff0000) >> 16); buf[pt++] = (byte) ((samples[i][j] & 0xff00) >> 8); buf[pt++] = (byte) (samples[i][j] & 0xff); } } } else { for (int i=0; i<samplesPerPixel; i++) { for (int j=0; j<numSamples; j++) { buf[j + i*numSamples] = (byte) samples[i][j]; } } } return buf; } /** Reads the image defined in the given IFD from the specified file. */ public static BufferedImage getImage(Hashtable ifd, RandomAccessStream in) throws FormatException, IOException { // construct field if (DEBUG) debug("constructing image"); byte[][] samples = getSamples(ifd, in); int[] bitsPerSample = getBitsPerSample(ifd); long imageWidth = getImageWidth(ifd); long imageLength = getImageLength(ifd); int samplesPerPixel = getSamplesPerPixel(ifd); int photoInterp = getPhotometricInterpretation(ifd); if (bitsPerSample[0] == 16 || bitsPerSample[0] == 12) { // First wrap the byte arrays and then use the features of the // ByteBuffer to transform to a ShortBuffer. Finally, use the ShortBuffer // bulk get method to copy the data into a usable form for makeImage(). int len = samples.length == 2 ? 3 : samples.length; short[][] sampleData = new short[len][samples[0].length / 2]; for (int i = 0; i < samplesPerPixel; i++) { ShortBuffer sampleBuf = ByteBuffer.wrap(samples[i]).asShortBuffer(); sampleBuf.get(sampleData[i]); } // Now make our image. return ImageTools.makeImage(sampleData, (int) imageWidth, (int) imageLength); } else if (bitsPerSample[0] == 24) { int[][] intData = new int[samplesPerPixel][samples[0].length / 3]; for (int i=0; i<samplesPerPixel; i++) { for (int j=0; j<intData[i].length; j++) { intData[i][j] = DataTools.bytesToInt(samples[i], j*3, 3, isLittleEndian(ifd)); } } return ImageTools.makeImage(intData, (int) imageWidth, (int) imageLength); } else if (bitsPerSample[0] == 32) { int type = getIFDIntValue(ifd, SAMPLE_FORMAT); if (type == 3) { // float data float[][] floatData = new float[samplesPerPixel][samples[0].length / 4]; for (int i=0; i<samplesPerPixel; i++) { floatData[i] = (float[]) DataTools.makeDataArray(samples[i], 4, true, isLittleEndian(ifd)); } return ImageTools.makeImage(floatData, (int) imageWidth, (int) imageLength); } else { // int data int[][] intData = new int[samplesPerPixel][samples[0].length / 4]; for (int i=0; i<samplesPerPixel; i++) { IntBuffer sampleBuf = ByteBuffer.wrap(samples[i]).asIntBuffer(); sampleBuf.get(intData[i]); } byte[][] shortData = new byte[samplesPerPixel][intData[0].length]; for (int i=0; i<samplesPerPixel; i++) { for (int j=0; j<shortData[0].length; j++) { shortData[i][j] = (byte) intData[i][j]; } } return ImageTools.makeImage(shortData, (int) imageWidth, (int) imageLength); } } if (samplesPerPixel == 1) { return ImageTools.makeImage(samples[0], (int) imageWidth, (int) imageLength, 1, false); } return ImageTools.makeImage(samples, (int) imageWidth, (int) imageLength); } /** * Extracts pixel information from the given byte array according to the * bits per sample, photometric interpretation, and the specified byte * ordering. * No error checking is performed. * This method is tailored specifically for planar (separated) images. */ public static void planarUnpack(short[][] samples, int startIndex, byte[] bytes, int[] bitsPerSample, int photoInterp, boolean littleEndian, int strip, int numStrips) throws FormatException { int numChannels = bitsPerSample.length; // this should always be 3 if (bitsPerSample[bitsPerSample.length - 1] == 0) numChannels--; // determine which channel the strip belongs to int channelNum = strip / (numStrips / numChannels); startIndex = (strip % (numStrips / numChannels)) * bytes.length; int index = 0; int counter = 0; for (int j=0; j<bytes.length; j++) { int numBytes = bitsPerSample[0] / 8; if (bitsPerSample[0] % 8 != 0) { // bits per sample is not a multiple of 8 // // while images in this category are not in violation of baseline TIFF // specs, it's a bad idea to write bits per sample values that aren't // divisible by 8 if (index == bytes.length) { //throw new FormatException("bad index : i = " + i + ", j = " + j); index--; } short b = bytes[index]; index++; int offset = (bitsPerSample[0] * (samples.length*j + channelNum)) % 8; if (offset <= (8 - (bitsPerSample[0] % 8))) { index--; } if (channelNum == 0) counter++; if (counter % 4 == 0 && channelNum == 0) { index++; } int ndx = startIndex + j; if (ndx >= samples[channelNum].length) { ndx = samples[channelNum].length - 1; } samples[channelNum][ndx] = (short) (b < 0 ? 256 + b : b); if (photoInterp == WHITE_IS_ZERO || photoInterp == CMYK) { samples[channelNum][ndx] = (short) (Integer.MAX_VALUE - samples[channelNum][ndx]); } } else if (numBytes == 1) { float b = bytes[index]; index++; int ndx = startIndex + j; if (ndx < samples[channelNum].length) { samples[channelNum][ndx] = (short) (b < 0 ? 256 + b : b); if (photoInterp == WHITE_IS_ZERO) { // invert color value samples[channelNum][ndx] = (short) ((65535 - samples[channelNum][ndx]) & 0xffff); } else if (photoInterp == CMYK) { samples[channelNum][ndx] = (short) (Integer.MAX_VALUE - samples[channelNum][ndx]); } } } else { byte[] b = new byte[numBytes]; if (numBytes + index < bytes.length) { System.arraycopy(bytes, index, b, 0, numBytes); } else { System.arraycopy(bytes, bytes.length - numBytes, b, 0, numBytes); } index += numBytes; int ndx = startIndex + j; if (ndx >= samples[0].length) ndx = samples[0].length - 1; samples[channelNum][ndx] = (short) DataTools.bytesToLong(b, !littleEndian); if (photoInterp == WHITE_IS_ZERO) { // invert color value long max = 1; for (int q=0; q<numBytes; q++) max *= 8; samples[channelNum][ndx] = (short) (max - samples[channelNum][ndx]); } else if (photoInterp == CMYK) { samples[channelNum][ndx] = (short) (Integer.MAX_VALUE - samples[channelNum][ndx]); } } } } /** * Extracts pixel information from the given byte array according to the * bits per sample, photometric interpretation and color map IFD directory * entry values, and the specified byte ordering. * No error checking is performed. */ public static void unpackBytes(short[][] samples, int startIndex, byte[] bytes, int[] bitsPerSample, int photoInterp, int[] colorMap, boolean littleEndian, long maxValue, int planar, int strip, int numStrips, long imageWidth) throws FormatException { if (planar == 2) { planarUnpack(samples, startIndex, bytes, bitsPerSample, photoInterp, littleEndian, strip, numStrips); return; } int totalBits = 0; for (int i=0; i<bitsPerSample.length; i++) totalBits += bitsPerSample[i]; int sampleCount = 8 * bytes.length / totalBits; if (DEBUG) { debug("unpacking " + sampleCount + " samples (startIndex=" + startIndex + "; totalBits=" + totalBits + "; numBytes=" + bytes.length + ")"); } if (startIndex + sampleCount > samples[0].length) { int trunc = startIndex + sampleCount - samples[0].length; if (DEBUG) debug("WARNING: truncated " + trunc + " extra samples"); sampleCount -= trunc; } // rules on incrementing the index: // 1) if the planar configuration is set to 1 (interleaved), then add one // to the index // 2) if the planar configuration is set to 2 (separated), then go to // j + (i*(bytes.length / sampleCount)) int bps0 = bitsPerSample[0]; int bpsPow = (int) Math.pow(2, bps0); int numBytes = bps0 / 8; boolean noDiv8 = bps0 % 8 != 0; boolean bps8 = bps0 == 8; boolean bps16 = bps0 == 16; if (photoInterp == CFA_ARRAY) { imageWidth = colorMap[colorMap.length - 2]; } int row = 0, col = 0; if (imageWidth != 0) row = startIndex / (int) imageWidth; int cw = 0; int ch = 0; if (photoInterp == CFA_ARRAY) { byte[] c = new byte[2]; c[0] = (byte) colorMap[0]; c[1] = (byte) colorMap[1]; cw = DataTools.bytesToInt(c, littleEndian); c[0] = (byte) colorMap[2]; c[1] = (byte) colorMap[3]; ch = DataTools.bytesToInt(c, littleEndian); int[] tmp = colorMap; colorMap = new int[tmp.length - 6]; System.arraycopy(tmp, 4, colorMap, 0, colorMap.length); } int index = 0; int count = 0; BitBuffer bb = new BitBuffer(bytes); byte[] copyByteArray = new byte[numBytes]; ByteBuffer nioBytes = MappedByteBuffer.wrap(bytes); if (!littleEndian) nioBytes.order(ByteOrder.LITTLE_ENDIAN); for (int j=0; j<sampleCount; j++) { for (int i=0; i<samples.length; i++) { if (noDiv8) { // bits per sample is not a multiple of 8 int ndx = startIndex + j; short s = 0; if ((i == 0 && (photoInterp == CFA_ARRAY || photoInterp == RGB_PALETTE) || (photoInterp != CFA_ARRAY && photoInterp != RGB_PALETTE))) { s = (short) bb.getBits(bps0); if ((ndx % imageWidth) == imageWidth - 1) { bb.skipBits((imageWidth * bps0 * sampleCount) % 8); } } short b = s; if (photoInterp != CFA_ARRAY) samples[i][ndx] = s; if (photoInterp == WHITE_IS_ZERO || photoInterp == CMYK) { samples[i][ndx] = (short) (Integer.MAX_VALUE - samples[i][ndx]); // invert colors } else if (photoInterp == CFA_ARRAY) { if (i == 0) { int pixelIndex = (int) ((row + (count / cw))*imageWidth + col + (count % cw)); samples[colorMap[count]][pixelIndex] = s; count++; if (count == colorMap.length) { count = 0; col += cw*ch; if (col == imageWidth) col = cw; else if (col > imageWidth) { row += ch; col = 0; } } } } } else if (bps8) { // special case handles 8-bit data more quickly //if (planar == 2) { index = j+(i*(bytes.length / samples.length)); } short b = (short) (bytes[index] & 0xff); index++; int ndx = startIndex + j; samples[i][ndx] = (short) (b < 0 ? Integer.MAX_VALUE + b : b); if (photoInterp == WHITE_IS_ZERO) { // invert color value samples[i][ndx] = (short) ((65535 - samples[i][ndx]) & 0xffff); } else if (photoInterp == CMYK) { samples[i][ndx] = (short) (Integer.MAX_VALUE - samples[i][ndx]); } else if (photoInterp == Y_CB_CR) { if (i == bitsPerSample.length - 1) { int lumaRed = colorMap[0]; int lumaGreen = colorMap[1]; int lumaBlue = colorMap[2]; int red = (int) (samples[2][ndx]*(2 - 2*lumaRed) + samples[0][ndx]); int blue = (int) (samples[1][ndx]*(2 - 2*lumaBlue) + samples[0][ndx]); int green = (int) (samples[0][ndx] - lumaBlue*blue - lumaRed*red); if (lumaGreen != 0) green = green / lumaGreen; samples[0][ndx] = (short) (red - colorMap[4]); samples[1][ndx] = (short) (green - colorMap[6]); samples[2][ndx] = (short) (blue - colorMap[8]); } } } // End if (bps8) else if (bps16) { int ndx = startIndex + j; if (numBytes + index < bytes.length) { samples[i][ndx] = nioBytes.getShort(index); } else { samples[i][ndx] = nioBytes.getShort(bytes.length - numBytes); } index += numBytes; if (photoInterp == WHITE_IS_ZERO) { // invert color value long max = 1; for (int q=0; q<numBytes; q++) max *= 8; samples[i][ndx] = (short) (max - samples[i][ndx]); } else if (photoInterp == CMYK) { samples[i][ndx] = (short) (Integer.MAX_VALUE - samples[i][ndx]); } } // End if (bps16) else { if (numBytes + index < bytes.length) { System.arraycopy(bytes, index, copyByteArray, 0, numBytes); } else { System.arraycopy(bytes, bytes.length - numBytes, copyByteArray, 0, numBytes); } index += numBytes; int ndx = startIndex + j; samples[i][ndx] = (short) DataTools.bytesToLong(copyByteArray, !littleEndian); if (photoInterp == WHITE_IS_ZERO) { // invert color value long max = 1; for (int q=0; q<numBytes; q++) max *= 8; samples[i][ndx] = (short) (max - samples[i][ndx]); } else if (photoInterp == CMYK) { samples[i][ndx] = (short) (Integer.MAX_VALUE - samples[i][ndx]); } } // end else } } } // -- Decompression methods -- /** Decodes a strip of data compressed with the given compression scheme. */ public static byte[] uncompress(byte[] input, int compression, int size) throws FormatException, IOException { if (compression < 0) compression += 65536; if (compression == UNCOMPRESSED) return input; else if (compression == CCITT_1D) { throw new FormatException( "Sorry, CCITT Group 3 1-Dimensional Modified Huffman " + "run length encoding compression mode is not supported"); } else if (compression == GROUP_3_FAX) { throw new FormatException("Sorry, CCITT T.4 bi-level encoding " + "(Group 3 Fax) compression mode is not supported"); } else if (compression == GROUP_4_FAX) { throw new FormatException("Sorry, CCITT T.6 bi-level encoding " + "(Group 4 Fax) compression mode is not supported"); } else if (compression == LZW) { return new LZWCodec().decompress(input); } else if (compression == JPEG) { return new JPEGCodec().decompress(input, new Object[] {Boolean.TRUE, Boolean.TRUE}); } else if (compression == PACK_BITS) { return new PackbitsCodec().decompress(input, new Integer(size)); } else if (compression == PROPRIETARY_DEFLATE || compression == DEFLATE) { return new AdobeDeflateCodec().decompress(input); } else if (compression == THUNDERSCAN) { throw new FormatException("Sorry, " + "Thunderscan compression mode is not supported"); } else if (compression == NIKON) { //return new NikonCodec().decompress(input); throw new FormatException("Sorry, Nikon compression mode is not " + "supported; we hope to support it in the future"); } else if (compression == LURAWAVE) { return new LuraWaveCodec().decompress(input); } else { throw new FormatException( "Unknown Compression type (" + compression + ")"); } } /** Undoes in-place differencing according to the given predictor value. */ public static void undifference(byte[] input, int[] bitsPerSample, long width, int planarConfig, int predictor, boolean little) throws FormatException { if (predictor == 2) { if (DEBUG) debug("reversing horizontal differencing"); int len = bitsPerSample.length; if (bitsPerSample[len - 1] == 0) len = 1; if (bitsPerSample[0] <= 8) { for (int b=0; b<input.length; b++) { if (b / len % width == 0) continue; input[b] += input[b - len]; } } else if (bitsPerSample[0] <= 16) { short[] s = (short[]) DataTools.makeDataArray(input, 2, false, !little); for (int b=0; b<s.length; b++) { if (b / len % width == 0) continue; s[b] += s[b - len]; } for (int i=0; i<s.length; i++) { input[little ? i*2 + 1: i*2] = (byte) (s[i] & 0xff); input[little ? i*2 : i*2 + 1] = (byte) ((s[i] >> 8) & 0xff); } } } else if (predictor != 1) { throw new FormatException("Unknown Predictor (" + predictor + ")"); } } // --------------------------- Writing TIFF files --------------------------- // -- IFD population methods -- /** Adds a directory entry to an IFD. */ public static void putIFDValue(Hashtable ifd, int tag, Object value) { ifd.put(new Integer(tag), value); } /** Adds a directory entry of type BYTE to an IFD. */ public static void putIFDValue(Hashtable ifd, int tag, short value) { putIFDValue(ifd, tag, new Short(value)); } /** Adds a directory entry of type SHORT to an IFD. */ public static void putIFDValue(Hashtable ifd, int tag, int value) { putIFDValue(ifd, tag, new Integer(value)); } /** Adds a directory entry of type LONG to an IFD. */ public static void putIFDValue(Hashtable ifd, int tag, long value) { putIFDValue(ifd, tag, new Long(value)); } // -- IFD writing methods -- /** * Writes the given IFD value to the given output object. * @param ifdOut output object for writing IFD stream * @param extraBuf buffer to which "extra" IFD information should be written * @param extraOut data output wrapper for extraBuf (passed for efficiency) * @param offset global offset to use for IFD offset values * @param tag IFD tag to write * @param value IFD value to write */ public static void writeIFDValue(DataOutput ifdOut, ByteArrayOutputStream extraBuf, DataOutputStream extraOut, int offset, int tag, Object value) throws FormatException, IOException { // convert singleton objects into arrays, for simplicity if (value instanceof Short) { value = new short[] {((Short) value).shortValue()}; } else if (value instanceof Integer) { value = new int[] {((Integer) value).intValue()}; } else if (value instanceof Long) { value = new long[] {((Long) value).longValue()}; } else if (value instanceof TiffRational) { value = new TiffRational[] {(TiffRational) value}; } else if (value instanceof Float) { value = new float[] {((Float) value).floatValue()}; } else if (value instanceof Double) { value = new double[] {((Double) value).doubleValue()}; } // write directory entry to output buffers ifdOut.writeShort(tag); // tag if (value instanceof short[]) { // BYTE short[] q = (short[]) value; ifdOut.writeShort(BYTE); // type ifdOut.writeInt(q.length); // count if (q.length <= 4) { for (int i=0; i<q.length; i++) ifdOut.writeByte(q[i]); // value(s) for (int i=q.length; i<4; i++) ifdOut.writeByte(0); // padding } else { ifdOut.writeInt(offset + extraBuf.size()); // offset for (int i=0; i<q.length; i++) extraOut.writeByte(q[i]); // values } } else if (value instanceof String) { // ASCII char[] q = ((String) value).toCharArray(); ifdOut.writeShort(ASCII); // type ifdOut.writeInt(q.length + 1); // count if (q.length < 4) { for (int i=0; i<q.length; i++) ifdOut.writeByte(q[i]); // value(s) for (int i=q.length; i<4; i++) ifdOut.writeByte(0); // padding } else { ifdOut.writeInt(offset + extraBuf.size()); // offset for (int i=0; i<q.length; i++) extraOut.writeByte(q[i]); // values extraOut.writeByte(0); // concluding NULL byte } } else if (value instanceof int[]) { // SHORT int[] q = (int[]) value; ifdOut.writeShort(SHORT); // type ifdOut.writeInt(q.length); // count if (q.length <= 2) { for (int i=0; i<q.length; i++) ifdOut.writeShort(q[i]); // value(s) for (int i=q.length; i<2; i++) ifdOut.writeShort(0); // padding } else { ifdOut.writeInt(offset + extraBuf.size()); // offset for (int i=0; i<q.length; i++) extraOut.writeShort(q[i]); // values } } else if (value instanceof long[]) { // LONG long[] q = (long[]) value; ifdOut.writeShort(LONG); // type ifdOut.writeInt(q.length); // count if (q.length <= 1) { if (q.length == 1) ifdOut.writeInt((int) q[0]); // value else ifdOut.writeInt(0); // padding } else { ifdOut.writeInt(offset + extraBuf.size()); // offset for (int i=0; i<q.length; i++) { extraOut.writeInt((int) q[i]); // values } } } else if (value instanceof TiffRational[]) { // RATIONAL TiffRational[] q = (TiffRational[]) value; ifdOut.writeShort(RATIONAL); // type ifdOut.writeInt(q.length); // count ifdOut.writeInt(offset + extraBuf.size()); // offset for (int i=0; i<q.length; i++) { extraOut.writeInt((int) q[i].getNumerator()); // values extraOut.writeInt((int) q[i].getDenominator()); // values } } else if (value instanceof float[]) { // FLOAT float[] q = (float[]) value; ifdOut.writeShort(FLOAT); // type ifdOut.writeInt(q.length); // count if (q.length <= 1) { if (q.length == 1) ifdOut.writeFloat(q[0]); // value else ifdOut.writeInt(0); // padding } else { ifdOut.writeInt(offset + extraBuf.size()); // offset for (int i=0; i<q.length; i++) extraOut.writeFloat(q[i]); // values } } else if (value instanceof double[]) { // DOUBLE double[] q = (double[]) value; ifdOut.writeShort(DOUBLE); // type ifdOut.writeInt(q.length); // count ifdOut.writeInt(offset + extraBuf.size()); // offset for (int i=0; i<q.length; i++) extraOut.writeDouble(q[i]); // values } else { throw new FormatException("Unknown IFD value type (" + value.getClass().getName() + "): " + value); } } /** * Surgically overwrites an existing IFD value with the given one. This * method requires that the IFD directory entry already exist. It * intelligently updates the count field of the entry to match the new * length. If the new length is longer than the old length, it appends the * new data to the end of the file and updates the offset field; if not, or * if the old data is already at the end of the file, it overwrites the old * data in place. */ public static void overwriteIFDValue(RandomAccessFile raf, int ifd, int tag, Object value) throws FormatException, IOException { if (DEBUG) { debug("overwriteIFDValue (ifd=" + ifd + "; tag=" + tag + "; value=" + value + ")"); } byte[] header = new byte[4]; raf.seek(0); raf.readFully(header); if (!isValidHeader(header)) { throw new FormatException("Invalid TIFF header"); } boolean little = header[0] == LITTLE && header[1] == LITTLE; // II long offset = 4; // offset to the IFD int num = 0; // number of directory entries // skip to the correct IFD for (int i=0; i<=ifd; i++) { offset = DataTools.read4UnsignedBytes(raf, little); if (offset <= 0) { throw new FormatException("No such IFD (" + ifd + " of " + i + ")"); } raf.seek(offset); num = DataTools.read2UnsignedBytes(raf, little); if (i < ifd) raf.seek(offset + 2 + BYTES_PER_ENTRY * num); } // search directory entries for proper tag for (int i=0; i<num; i++) { int oldTag = DataTools.read2UnsignedBytes(raf, little); int oldType = DataTools.read2UnsignedBytes(raf, little); int oldCount = DataTools.read4SignedBytes(raf, little); int oldOffset = DataTools.read4SignedBytes(raf, little); if (oldTag == tag) { // write new value to buffers ByteArrayOutputStream ifdBuf = new ByteArrayOutputStream(14); DataOutputStream ifdOut = new DataOutputStream(ifdBuf); ByteArrayOutputStream extraBuf = new ByteArrayOutputStream(); DataOutputStream extraOut = new DataOutputStream(extraBuf); writeIFDValue(ifdOut, extraBuf, extraOut, oldOffset, tag, value); byte[] bytes = ifdBuf.toByteArray(); byte[] extra = extraBuf.toByteArray(); // extract new directory entry parameters int newTag = DataTools.bytesToInt(bytes, 0, 2, false); int newType = DataTools.bytesToInt(bytes, 2, 2, false); int newCount = DataTools.bytesToInt(bytes, 4, false); int newOffset = DataTools.bytesToInt(bytes, 8, false); boolean terminate = false; if (DEBUG) { debug("overwriteIFDValue:\n\told: (tag=" + oldTag + "; type=" + oldType + "; count=" + oldCount + "; offset=" + oldOffset + ");\n\tnew: (tag=" + newTag + "; type=" + newType + "; count=" + newCount + "; offset=" + newOffset + ")"); } // determine the best way to overwrite the old entry if (extra.length == 0) { // new entry is inline; if old entry wasn't, old data is orphaned // do not override new offset value since data is inline if (DEBUG) debug("overwriteIFDValue: new entry is inline"); } else if (oldOffset + oldCount * BYTES_PER_ELEMENT[oldType] == raf.length()) { // old entry was already at EOF; overwrite it newOffset = oldOffset; terminate = true; if (DEBUG) debug("overwriteIFDValue: old entry is at EOF"); } else if (newCount <= oldCount) { // new entry is as small or smaller than old entry; overwrite it newOffset = oldOffset; if (DEBUG) debug("overwriteIFDValue: new entry is <= old entry"); } else { // old entry was elsewhere; append to EOF, orphaning old entry newOffset = (int) raf.length(); if (DEBUG) debug("overwriteIFDValue: old entry will be orphaned"); } // overwrite old entry raf.seek(raf.getFilePointer() - 10); // jump back DataTools.writeShort(raf, newType, little); DataTools.writeInt(raf, newCount, little); DataTools.writeInt(raf, newOffset, little); if (extra.length > 0) { raf.seek(newOffset); raf.write(extra); } if (terminate) raf.setLength(raf.getFilePointer()); return; } } throw new FormatException("Tag not found (" + getIFDTagName(tag) + ")"); } /** Convenience method for overwriting a file's first ImageDescription. */ public static void overwriteComment(String id, Object value) throws FormatException, IOException { RandomAccessFile raf = new RandomAccessFile(id, "rw"); overwriteIFDValue(raf, 0, TiffTools.IMAGE_DESCRIPTION, value); raf.close(); } // -- Image writing methods -- /** * Writes the given field to the specified output stream using the given * byte offset and IFD, in big-endian format. * * @param img The field to write * @param ifd Hashtable representing the TIFF IFD; can be null * @param out The output stream to which the TIFF data should be written * @param offset The value to use for specifying byte offsets * @param last Whether this image is the final IFD entry of the TIFF data * @return total number of bytes written */ public static long writeImage(BufferedImage img, Hashtable ifd, OutputStream out, int offset, boolean last) throws FormatException, IOException { if (img == null) throw new FormatException("Image is null"); if (DEBUG) debug("writeImage (offset=" + offset + "; last=" + last + ")"); byte[][] values = ImageTools.getPixelBytes(img, false); int width = img.getWidth(); int height = img.getHeight(); if (values.length < 1 || values.length > 3) { throw new FormatException("Image has an unsupported " + "number of range components (" + values.length + ")"); } if (values.length == 2) { // pad values with extra set of zeroes values = new byte[][] { values[0], values[1], new byte[values[0].length] }; } int bytesPerPixel = values[0].length / (width * height); // populate required IFD directory entries (except strip information) if (ifd == null) ifd = new Hashtable(); putIFDValue(ifd, IMAGE_WIDTH, width); putIFDValue(ifd, IMAGE_LENGTH, height); if (getIFDValue(ifd, BITS_PER_SAMPLE) == null) { int bps = 8 * bytesPerPixel; int[] bpsArray = new int[values.length]; Arrays.fill(bpsArray, bps); putIFDValue(ifd, BITS_PER_SAMPLE, bpsArray); } if (img.getRaster().getTransferType() == DataBuffer.TYPE_FLOAT) { putIFDValue(ifd, SAMPLE_FORMAT, 3); } if (getIFDValue(ifd, COMPRESSION) == null) { putIFDValue(ifd, COMPRESSION, UNCOMPRESSED); } if (getIFDValue(ifd, PHOTOMETRIC_INTERPRETATION) == null) { putIFDValue(ifd, PHOTOMETRIC_INTERPRETATION, values.length == 1 ? 1 : 2); } if (getIFDValue(ifd, SAMPLES_PER_PIXEL) == null) { putIFDValue(ifd, SAMPLES_PER_PIXEL, values.length); } if (getIFDValue(ifd, X_RESOLUTION) == null) { putIFDValue(ifd, X_RESOLUTION, new TiffRational(1, 1)); // no unit } if (getIFDValue(ifd, Y_RESOLUTION) == null) { putIFDValue(ifd, Y_RESOLUTION, new TiffRational(1, 1)); // no unit } if (getIFDValue(ifd, RESOLUTION_UNIT) == null) { putIFDValue(ifd, RESOLUTION_UNIT, 1); // no unit } if (getIFDValue(ifd, SOFTWARE) == null) { putIFDValue(ifd, SOFTWARE, "LOCI Bio-Formats"); } if (getIFDValue(ifd, IMAGE_DESCRIPTION) == null) { putIFDValue(ifd, IMAGE_DESCRIPTION, ""); } // create pixel output buffers int stripSize = 8192; int rowsPerStrip = stripSize / (width * bytesPerPixel * values.length); int stripsPerImage = (height + rowsPerStrip - 1) / rowsPerStrip; int[] bps = (int[]) getIFDValue(ifd, BITS_PER_SAMPLE, true, int[].class); ByteArrayOutputStream[] stripBuf = new ByteArrayOutputStream[stripsPerImage]; DataOutputStream[] stripOut = new DataOutputStream[stripsPerImage]; for (int i=0; i<stripsPerImage; i++) { stripBuf[i] = new ByteArrayOutputStream(stripSize); stripOut[i] = new DataOutputStream(stripBuf[i]); } // write pixel strips to output buffers for (int y=0; y<height; y++) { int strip = y / rowsPerStrip; for (int x=0; x<width; x++) { int ndx = y * width * bytesPerPixel + x * bytesPerPixel; for (int c=0; c<values.length; c++) { int q = values[c][ndx]; if (bps[c] == 8) stripOut[strip].writeByte(q); else if (bps[c] == 16) { stripOut[strip].writeByte(q); stripOut[strip].writeByte(values[c][ndx+1]); } else if (bps[c] == 32) { for (int i=0; i<4; i++) { stripOut[strip].writeByte(values[c][ndx + i]); } } else { throw new FormatException("Unsupported bits per sample value (" + bps[c] + ")"); } } } } // compress strips according to given differencing and compression schemes int planarConfig = getIFDIntValue(ifd, PLANAR_CONFIGURATION, false, 1); int predictor = getIFDIntValue(ifd, PREDICTOR, false, 1); int compression = getIFDIntValue(ifd, COMPRESSION, false, UNCOMPRESSED); byte[][] strips = new byte[stripsPerImage][]; for (int i=0; i<stripsPerImage; i++) { strips[i] = stripBuf[i].toByteArray(); difference(strips[i], bps, width, planarConfig, predictor); strips[i] = compress(strips[i], compression); } // record strip byte counts and offsets long[] stripByteCounts = new long[stripsPerImage]; long[] stripOffsets = new long[stripsPerImage]; putIFDValue(ifd, STRIP_OFFSETS, stripOffsets); putIFDValue(ifd, ROWS_PER_STRIP, rowsPerStrip); putIFDValue(ifd, STRIP_BYTE_COUNTS, stripByteCounts); Object[] keys = ifd.keySet().toArray(); Arrays.sort(keys); // sort IFD tags in ascending order int ifdBytes = 2 + BYTES_PER_ENTRY * keys.length + 4; long pixelBytes = 0; for (int i=0; i<stripsPerImage; i++) { stripByteCounts[i] = strips[i].length; stripOffsets[i] = pixelBytes + offset + ifdBytes; pixelBytes += stripByteCounts[i]; } // create IFD output buffers ByteArrayOutputStream ifdBuf = new ByteArrayOutputStream(ifdBytes); DataOutputStream ifdOut = new DataOutputStream(ifdBuf); ByteArrayOutputStream extraBuf = new ByteArrayOutputStream(); DataOutputStream extraOut = new DataOutputStream(extraBuf); offset += ifdBytes + pixelBytes; // write IFD to output buffers ifdOut.writeShort(keys.length); // number of directory entries for (int k=0; k<keys.length; k++) { Object key = keys[k]; if (!(key instanceof Integer)) { throw new FormatException("Malformed IFD tag (" + key + ")"); } if (((Integer) key).intValue() == LITTLE_ENDIAN) continue; Object value = ifd.get(key); if (DEBUG) { String sk = getIFDTagName(((Integer) key).intValue()); String sv = value instanceof int[] ? ("int[" + ((int[]) value).length + "]") : value.toString(); debug("writeImage: writing " + sk + " (value=" + sv + ")"); } writeIFDValue(ifdOut, extraBuf, extraOut, offset, ((Integer) key).intValue(), value); } ifdOut.writeInt(last ? 0 : offset + extraBuf.size()); // offset to next IFD // flush buffers to output stream byte[] ifdArray = ifdBuf.toByteArray(); byte[] extraArray = extraBuf.toByteArray(); long numBytes = ifdArray.length + extraArray.length; out.write(ifdArray); for (int i=0; i<strips.length; i++) { out.write(strips[i]); numBytes += strips[i].length; } out.write(extraArray); out.flush(); return numBytes; } /** * Retrieves the image's width (TIFF tag ImageWidth) from a given TIFF IFD. * @param ifd a TIFF IFD hashtable. * @return the image's width. * @throws FormatException if there is a problem parsing the IFD metadata. */ public static long getImageWidth(Hashtable ifd) throws FormatException { return getIFDLongValue(ifd, IMAGE_WIDTH, true, 0); } /** * Retrieves the image's length (TIFF tag ImageLength) from a given TIFF IFD. * @param ifd a TIFF IFD hashtable. * @return the image's length. * @throws FormatException if there is a problem parsing the IFD metadata. */ public static long getImageLength(Hashtable ifd) throws FormatException { return getIFDLongValue(ifd, IMAGE_LENGTH, true, 0); } /** * Retrieves the image's bits per sample (TIFF tag BitsPerSample) from a given * TIFF IFD. * @param ifd a TIFF IFD hashtable. * @return the image's bits per sample. The length of the array is equal to * the number of samples per pixel. * @throws FormatException if there is a problem parsing the IFD metadata. * @see #getSamplesPerPixel(Hashtable) */ public static int[] getBitsPerSample(Hashtable ifd) throws FormatException { int[] bitsPerSample = getIFDIntArray(ifd, BITS_PER_SAMPLE, false); if (bitsPerSample == null) bitsPerSample = new int[] {1}; return bitsPerSample; } /** * Retrieves the number of samples per pixel for the image (TIFF tag * SamplesPerPixel) from a given TIFF IFD. * @param ifd a TIFF IFD hashtable. * @return the number of samples per pixel. * @throws FormatException if there is a problem parsing the IFD metadata. */ public static int getSamplesPerPixel(Hashtable ifd) throws FormatException { return getIFDIntValue(ifd, SAMPLES_PER_PIXEL, false, 1); } /** * Retrieves the image's compression type (TIFF tag Compression) from a * given TIFF IFD. * @param ifd a TIFF IFD hashtable. * @return the image's compression type. As of TIFF 6.0 this is one of: * <ul> * <li>Uncompressed (1)</li> * <li>CCITT 1D (2)</li> * <li>Group 3 Fax (3)</li> * <li>Group 4 Fax (4)</li> * <li>LZW (5)</li> * <li>JPEG (6)</li> * <li>PackBits (32773)</li> * </ul> * @throws FormatException if there is a problem parsing the IFD metadata. */ public static int getCompression(Hashtable ifd) throws FormatException { return getIFDIntValue(ifd, COMPRESSION, false, UNCOMPRESSED); } /** * Retrieves the image's photometric interpretation (TIFF tag * PhotometricInterpretation) from a given TIFF IFD. * @param ifd a TIFF IFD hashtable. * @return the image's photometric interpretation. As of TIFF 6.0 this is one * of: * <ul> * <li>WhiteIsZero (0)</li> * <li>BlackIsZero (1)</li> * <li>RGB (2)</li> * <li>RGB Palette (3)</li> * <li>Transparency mask (4)</li> * <li>CMYK (5)</li> * <li>YbCbCr (6)</li> * <li>CIELab (8)</li> * </ul> * * @throws FormatException if there is a problem parsing the IFD metadata. */ public static int getPhotometricInterpretation(Hashtable ifd) throws FormatException { return getIFDIntValue(ifd, PHOTOMETRIC_INTERPRETATION, true, 0); } /** * Retrieves the strip offsets for the image (TIFF tag StripOffsets) from a * given TIFF IFD. * @param ifd a TIFF IFD hashtable. * @return the strip offsets for the image. The lenght of the array is equal * to the number of strips per image. <i>StripsPerImage = * floor ((ImageLength + RowsPerStrip - 1) / RowsPerStrip)</i>. * @throws FormatException if there is a problem parsing the IFD metadata. * @see #getStripByteCounts(Hashtable) * @see #getRowsPerStrip(Hashtable) */ public static long[] getStripOffsets(Hashtable ifd) throws FormatException { return getIFDLongArray(ifd, STRIP_OFFSETS, false); } /** * Retrieves strip byte counts for the image (TIFF tag StripByteCounts) from a * given TIFF IFD. * @param ifd a TIFF IFD hashtable. * @return the byte counts for each strip. The length of the array is equal to * the number of strips per image. <i>StripsPerImage = * floor((ImageLength + RowsPerStrip - 1) / RowsPerStrip)</i>. * @throws FormatException if there is a problem parsing the IFD metadata. * @see #getStripOffsets(Hashtable) */ public static long[] getStripByteCounts(Hashtable ifd) throws FormatException { return getIFDLongArray(ifd, STRIP_BYTE_COUNTS, false); } /** * Retrieves the number of rows per strip for image (TIFF tag RowsPerStrip) * from a given TIFF IFD. * @param ifd a TIFF IFD hashtable. * @return the number of rows per strip. * @throws FormatException if there is a problem parsing the IFD metadata. */ public static long[] getRowsPerStrip(Hashtable ifd) throws FormatException { return getIFDLongArray(ifd, ROWS_PER_STRIP, false); } // -- Compression methods -- /** Encodes a strip of data with the given compression scheme. */ public static byte[] compress(byte[] input, int compression) throws FormatException, IOException { if (compression == UNCOMPRESSED) return input; else if (compression == CCITT_1D) { throw new FormatException( "Sorry, CCITT Group 3 1-Dimensional Modified Huffman " + "run length encoding compression mode is not supported"); } else if (compression == GROUP_3_FAX) { throw new FormatException("Sorry, CCITT T.4 bi-level encoding " + "(Group 3 Fax) compression mode is not supported"); } else if (compression == GROUP_4_FAX) { throw new FormatException("Sorry, CCITT T.6 bi-level encoding " + "(Group 4 Fax) compression mode is not supported"); } else if (compression == LZW) { LZWCodec c = new LZWCodec(); return c.compress(input, 0, 0, null, null); // return Compression.lzwCompress(input); } else if (compression == JPEG) { throw new FormatException( "Sorry, JPEG compression mode is not supported"); } else if (compression == PACK_BITS) { throw new FormatException( "Sorry, PackBits compression mode is not supported"); } else { throw new FormatException( "Unknown Compression type (" + compression + ")"); } } /** Performs in-place differencing according to the given predictor value. */ public static void difference(byte[] input, int[] bitsPerSample, long width, int planarConfig, int predictor) throws FormatException { if (predictor == 2) { if (DEBUG) debug("performing horizontal differencing"); for (int b=input.length-1; b>=0; b--) { if (b / bitsPerSample.length % width == 0) continue; input[b] -= input[b - bitsPerSample.length]; } } else if (predictor != 1) { throw new FormatException("Unknown Predictor (" + predictor + ")"); } } // -- Debugging -- /** Prints a debugging message with current time. */ public static void debug(String message) { LogTools.println(System.currentTimeMillis() + ": " + message); } }
false
true
public static byte[] getSamples(Hashtable ifd, RandomAccessStream in, byte[] buf) throws FormatException, IOException { if (DEBUG) debug("parsing IFD entries"); // get internal non-IFD entries boolean littleEndian = isLittleEndian(ifd); in.order(littleEndian); // get relevant IFD entries long imageWidth = getImageWidth(ifd); long imageLength = getImageLength(ifd); int[] bitsPerSample = getBitsPerSample(ifd); int samplesPerPixel = getSamplesPerPixel(ifd); int compression = getCompression(ifd); int photoInterp = getPhotometricInterpretation(ifd); long[] stripOffsets = getStripOffsets(ifd); long[] stripByteCounts = getStripByteCounts(ifd); long[] rowsPerStripArray = getRowsPerStrip(ifd); boolean fakeByteCounts = stripByteCounts == null; boolean fakeRPS = rowsPerStripArray == null; boolean isTiled = stripOffsets == null; long[] maxes = getIFDLongArray(ifd, MAX_SAMPLE_VALUE, false); long maxValue = maxes == null ? 0 : maxes[0]; if (isTiled) { stripOffsets = getIFDLongArray(ifd, TILE_OFFSETS, true); stripByteCounts = getIFDLongArray(ifd, TILE_BYTE_COUNTS, true); rowsPerStripArray = new long[] {imageLength}; } else if (fakeByteCounts) { // technically speaking, this shouldn't happen (since TIFF writers are // required to write the StripByteCounts tag), but we'll support it // anyway // don't rely on RowsPerStrip, since it's likely that if the file doesn't // have the StripByteCounts tag, it also won't have the RowsPerStrip tag stripByteCounts = new long[stripOffsets.length]; if (stripByteCounts.length == 1) { stripByteCounts[0] = imageWidth * imageLength * (bitsPerSample[0] / 8); } else { stripByteCounts[0] = stripOffsets[0]; for (int i=1; i<stripByteCounts.length; i++) { stripByteCounts[i] = stripOffsets[i] - stripByteCounts[i-1]; } } } boolean lastBitsZero = bitsPerSample[bitsPerSample.length - 1] == 0; if (fakeRPS && !isTiled) { // create a false rowsPerStripArray if one is not present // it's sort of a cheap hack, but here's how it's done: // RowsPerStrip = stripByteCounts / (imageLength * bitsPerSample) // since stripByteCounts and bitsPerSample are arrays, we have to // iterate through each item rowsPerStripArray = new long[bitsPerSample.length]; long temp = stripByteCounts[0]; stripByteCounts = new long[bitsPerSample.length]; for (int i=0; i<stripByteCounts.length; i++) stripByteCounts[i] = temp; temp = bitsPerSample[0]; if (temp == 0) temp = 8; bitsPerSample = new int[bitsPerSample.length]; for (int i=0; i<bitsPerSample.length; i++) bitsPerSample[i] = (int) temp; temp = stripOffsets[0]; /* stripOffsets = new long[bitsPerSample.length]; for (int i=0; i<bitsPerSample.length; i++) { stripOffsets[i] = i == 0 ? temp : stripOffsets[i - 1] + stripByteCounts[i]; } */ // we have two files that reverse the endianness for BitsPerSample, // StripOffsets, and StripByteCounts if (bitsPerSample[0] > 64) { byte[] bps = new byte[2]; byte[] stripOffs = new byte[4]; byte[] byteCounts = new byte[4]; if (littleEndian) { bps[0] = (byte) (bitsPerSample[0] & 0xff); bps[1] = (byte) ((bitsPerSample[0] >>> 8) & 0xff); int ndx = stripOffsets.length - 1; stripOffs[0] = (byte) (stripOffsets[ndx] & 0xff); stripOffs[1] = (byte) ((stripOffsets[ndx] >>> 8) & 0xff); stripOffs[2] = (byte) ((stripOffsets[ndx] >>> 16) & 0xff); stripOffs[3] = (byte) ((stripOffsets[ndx] >>> 24) & 0xff); ndx = stripByteCounts.length - 1; byteCounts[0] = (byte) (stripByteCounts[ndx] & 0xff); byteCounts[1] = (byte) ((stripByteCounts[ndx] >>> 8) & 0xff); byteCounts[2] = (byte) ((stripByteCounts[ndx] >>> 16) & 0xff); byteCounts[3] = (byte) ((stripByteCounts[ndx] >>> 24) & 0xff); } else { bps[1] = (byte) ((bitsPerSample[0] >>> 16) & 0xff); bps[0] = (byte) ((bitsPerSample[0] >>> 24) & 0xff); stripOffs[3] = (byte) (stripOffsets[0] & 0xff); stripOffs[2] = (byte) ((stripOffsets[0] >>> 8) & 0xff); stripOffs[1] = (byte) ((stripOffsets[0] >>> 16) & 0xff); stripOffs[0] = (byte) ((stripOffsets[0] >>> 24) & 0xff); byteCounts[3] = (byte) (stripByteCounts[0] & 0xff); byteCounts[2] = (byte) ((stripByteCounts[0] >>> 8) & 0xff); byteCounts[1] = (byte) ((stripByteCounts[0] >>> 16) & 0xff); byteCounts[0] = (byte) ((stripByteCounts[0] >>> 24) & 0xff); } bitsPerSample[0] = DataTools.bytesToInt(bps, !littleEndian); stripOffsets[0] = DataTools.bytesToInt(stripOffs, !littleEndian); stripByteCounts[0] = DataTools.bytesToInt(byteCounts, !littleEndian); } if (rowsPerStripArray.length == 1 && stripByteCounts[0] != (imageWidth * imageLength * (bitsPerSample[0] / 8)) && compression == UNCOMPRESSED) { for (int i=0; i<stripByteCounts.length; i++) { stripByteCounts[i] = imageWidth * imageLength * (bitsPerSample[i] / 8); stripOffsets[0] = (int) (in.length() - stripByteCounts[0] - 48 * imageWidth); if (i != 0) { stripOffsets[i] = stripOffsets[i - 1] + stripByteCounts[i]; } in.seek((int) stripOffsets[i]); in.read(buf, (int) (i*imageWidth), (int) imageWidth); boolean isZero = true; for (int j=0; j<imageWidth; j++) { if (buf[(int) (i*imageWidth + j)] != 0) { isZero = false; break; } } while (isZero) { stripOffsets[i] -= imageWidth; in.seek((int) stripOffsets[i]); in.read(buf, (int) (i*imageWidth), (int) imageWidth); for (int j=0; j<imageWidth; j++) { if (buf[(int) (i*imageWidth + j)] != 0) { isZero = false; stripOffsets[i] -= (stripByteCounts[i] - imageWidth); break; } } } } } for (int i=0; i<bitsPerSample.length; i++) { // case 1: we're still within bitsPerSample array bounds if (i < bitsPerSample.length) { if (i == samplesPerPixel) { bitsPerSample[i] = 0; lastBitsZero = true; } // remember that the universe collapses when we divide by 0 if (bitsPerSample[i] != 0) { rowsPerStripArray[i] = (long) stripByteCounts[i] / (imageWidth * (bitsPerSample[i] / 8)); } else if (bitsPerSample[i] == 0 && i > 0) { rowsPerStripArray[i] = (long) stripByteCounts[i] / (imageWidth * (bitsPerSample[i - 1] / 8)); bitsPerSample[i] = bitsPerSample[i - 1]; } else { throw new FormatException("BitsPerSample is 0"); } } // case 2: we're outside bitsPerSample array bounds else if (i >= bitsPerSample.length) { rowsPerStripArray[i] = (long) stripByteCounts[i] / (imageWidth * (bitsPerSample[bitsPerSample.length - 1] / 8)); } } for (int i=0; i<stripByteCounts.length; i++) { stripByteCounts[i] *= 2; } } if (lastBitsZero) { bitsPerSample[bitsPerSample.length - 1] = 0; //samplesPerPixel--; } TiffRational xResolution = getIFDRationalValue(ifd, X_RESOLUTION, false); TiffRational yResolution = getIFDRationalValue(ifd, Y_RESOLUTION, false); int planarConfig = getIFDIntValue(ifd, PLANAR_CONFIGURATION, false, 1); int resolutionUnit = getIFDIntValue(ifd, RESOLUTION_UNIT, false, 2); if (xResolution == null || yResolution == null) resolutionUnit = 0; int[] colorMap = getIFDIntArray(ifd, COLOR_MAP, false); int predictor = getIFDIntValue(ifd, PREDICTOR, false, 1); // If the subsequent color maps are empty, use the first IFD's color map //if (colorMap == null) { // colorMap = getIFDIntArray(getFirstIFD(in), COLOR_MAP, false); //} // use special color map for YCbCr if (photoInterp == Y_CB_CR) { int[] tempColorMap = getIFDIntArray(ifd, Y_CB_CR_COEFFICIENTS, false); int[] refBlackWhite = getIFDIntArray(ifd, REFERENCE_BLACK_WHITE, false); colorMap = new int[tempColorMap.length + refBlackWhite.length]; System.arraycopy(tempColorMap, 0, colorMap, 0, tempColorMap.length); System.arraycopy(refBlackWhite, 0, colorMap, tempColorMap.length, refBlackWhite.length); } if (DEBUG) { StringBuffer sb = new StringBuffer(); sb.append("IFD directory entry values:"); sb.append("\n\tLittleEndian="); sb.append(littleEndian); sb.append("\n\tImageWidth="); sb.append(imageWidth); sb.append("\n\tImageLength="); sb.append(imageLength); sb.append("\n\tBitsPerSample="); sb.append(bitsPerSample[0]); for (int i=1; i<bitsPerSample.length; i++) { sb.append(","); sb.append(bitsPerSample[i]); } sb.append("\n\tSamplesPerPixel="); sb.append(samplesPerPixel); sb.append("\n\tCompression="); sb.append(compression); sb.append("\n\tPhotometricInterpretation="); sb.append(photoInterp); sb.append("\n\tStripOffsets="); sb.append(stripOffsets[0]); for (int i=1; i<stripOffsets.length; i++) { sb.append(","); sb.append(stripOffsets[i]); } sb.append("\n\tRowsPerStrip="); sb.append(rowsPerStripArray[0]); for (int i=1; i<rowsPerStripArray.length; i++) { sb.append(","); sb.append(rowsPerStripArray[i]); } sb.append("\n\tStripByteCounts="); sb.append(stripByteCounts[0]); for (int i=1; i<stripByteCounts.length; i++) { sb.append(","); sb.append(stripByteCounts[i]); } sb.append("\n\tXResolution="); sb.append(xResolution); sb.append("\n\tYResolution="); sb.append(yResolution); sb.append("\n\tPlanarConfiguration="); sb.append(planarConfig); sb.append("\n\tResolutionUnit="); sb.append(resolutionUnit); sb.append("\n\tColorMap="); if (colorMap == null) sb.append("null"); else { sb.append(colorMap[0]); for (int i=1; i<colorMap.length; i++) { sb.append(","); sb.append(colorMap[i]); } } sb.append("\n\tPredictor="); sb.append(predictor); debug(sb.toString()); } for (int i=0; i<samplesPerPixel; i++) { if (bitsPerSample[i] < 1) { throw new FormatException("Illegal BitsPerSample (" + bitsPerSample[i] + ")"); } // don't support odd numbers of bits (except for 1) else if (bitsPerSample[i] % 2 != 0 && bitsPerSample[i] != 1) { throw new FormatException("Sorry, unsupported BitsPerSample (" + bitsPerSample[i] + ")"); } } if (bitsPerSample.length < samplesPerPixel) { throw new FormatException("BitsPerSample length (" + bitsPerSample.length + ") does not match SamplesPerPixel (" + samplesPerPixel + ")"); } else if (photoInterp == TRANSPARENCY_MASK) { throw new FormatException( "Sorry, Transparency Mask PhotometricInterpretation is not supported"); } else if (photoInterp == Y_CB_CR) { throw new FormatException( "Sorry, YCbCr PhotometricInterpretation is not supported"); } else if (photoInterp == CIE_LAB) { throw new FormatException( "Sorry, CIELAB PhotometricInterpretation is not supported"); } else if (photoInterp != WHITE_IS_ZERO && photoInterp != BLACK_IS_ZERO && photoInterp != RGB && photoInterp != RGB_PALETTE && photoInterp != CMYK && photoInterp != Y_CB_CR && photoInterp != CFA_ARRAY) { throw new FormatException("Unknown PhotometricInterpretation (" + photoInterp + ")"); } long rowsPerStrip = rowsPerStripArray[0]; for (int i=1; i<rowsPerStripArray.length; i++) { if (rowsPerStrip != rowsPerStripArray[i]) { throw new FormatException( "Sorry, non-uniform RowsPerStrip is not supported"); } } long numStrips = (imageLength + rowsPerStrip - 1) / rowsPerStrip; if (isTiled || fakeRPS) numStrips = stripOffsets.length; if (planarConfig == 2) numStrips *= samplesPerPixel; if (stripOffsets.length < numStrips && !fakeRPS) { throw new FormatException("StripOffsets length (" + stripOffsets.length + ") does not match expected " + "number of strips (" + numStrips + ")"); } else if (fakeRPS) numStrips = stripOffsets.length; if (stripByteCounts.length < numStrips) { throw new FormatException("StripByteCounts length (" + stripByteCounts.length + ") does not match expected " + "number of strips (" + numStrips + ")"); } if (imageWidth > Integer.MAX_VALUE || imageLength > Integer.MAX_VALUE || imageWidth * imageLength > Integer.MAX_VALUE) { throw new FormatException("Sorry, ImageWidth x ImageLength > " + Integer.MAX_VALUE + " is not supported (" + imageWidth + " x " + imageLength + ")"); } int numSamples = (int) (imageWidth * imageLength); if (planarConfig != 1 && planarConfig != 2) { throw new FormatException( "Unknown PlanarConfiguration (" + planarConfig + ")"); } // read in image strips if (DEBUG) { debug("reading image data (samplesPerPixel=" + samplesPerPixel + "; numSamples=" + numSamples + ")"); } if (photoInterp == CFA_ARRAY) { int[] tempMap = new int[colorMap.length + 2]; System.arraycopy(colorMap, 0, tempMap, 0, colorMap.length); tempMap[tempMap.length - 2] = (int) imageWidth; tempMap[tempMap.length - 1] = (int) imageLength; colorMap = tempMap; } if (stripOffsets.length > 1 && (stripOffsets[stripOffsets.length - 1] == stripOffsets[stripOffsets.length - 2])) { long[] tmp = stripOffsets; stripOffsets = new long[tmp.length - 1]; System.arraycopy(tmp, 0, stripOffsets, 0, stripOffsets.length); numStrips--; } short[][] samples = new short[samplesPerPixel][numSamples]; byte[] altBytes = new byte[0]; if (bitsPerSample[0] == 16) littleEndian = !littleEndian; byte[] jpegTable = null; if (compression == JPEG) { jpegTable = (byte[]) TiffTools.getIFDValue(ifd, JPEG_TABLES); } // number of uncompressed bytes in a strip int size = (int) (imageWidth * (bitsPerSample[0] / 8) * rowsPerStrip * samplesPerPixel); if (isTiled) { long tileWidth = getIFDLongValue(ifd, TILE_WIDTH, true, 0); long tileLength = getIFDLongValue(ifd, TILE_LENGTH, true, 0); byte[] data = new byte[(int) (imageWidth * imageLength * samplesPerPixel * (bitsPerSample[0] / 8))]; int row = 0; int col = 0; int bytes = bitsPerSample[0] / 8; for (int i=0; i<stripOffsets.length; i++) { byte[] b = new byte[(int) stripByteCounts[i]]; in.seek(stripOffsets[i]); in.read(b); int len = (int) (tileWidth * tileLength * samplesPerPixel * (bitsPerSample[0] / 8)); if (jpegTable != null) { byte[] q = new byte[jpegTable.length + b.length - 4]; System.arraycopy(jpegTable, 0, q, 0, jpegTable.length - 2); System.arraycopy(b, 2, q, jpegTable.length - 2, b.length - 2); b = uncompress(q, compression, len); } else b = uncompress(b, compression, len); int ext = (int) (b.length / (tileWidth * tileLength)); int rowBytes = (int) (tileWidth * ext); if (tileWidth + col > imageWidth) { rowBytes = (int) ((imageWidth - col) * ext); } for (int j=0; j<tileLength; j++) { if (row + j < imageLength) { System.arraycopy(b, rowBytes*j, data, (int) ((row + j)*imageWidth*ext + ext*col), rowBytes); } else break; } // update row and column col += (int) tileWidth; if (col >= imageWidth) { row += (int) tileLength; col = 0; } } undifference(data, bitsPerSample, imageWidth, planarConfig, predictor, littleEndian); unpackBytes(samples, 0, data, bitsPerSample, photoInterp, colorMap, littleEndian, maxValue, planarConfig, 0, 1, imageWidth); } else { int overallOffset = 0; for (int strip=0, row=0; strip<numStrips; strip++, row+=rowsPerStrip) { try { if (DEBUG) debug("reading image strip #" + strip); in.seek((int) stripOffsets[strip]); if (stripByteCounts[strip] > Integer.MAX_VALUE) { throw new FormatException("Sorry, StripByteCounts > " + Integer.MAX_VALUE + " is not supported"); } byte[] bytes = new byte[(int) stripByteCounts[strip]]; in.read(bytes); if (compression != PACK_BITS) { if (jpegTable != null) { byte[] q = new byte[jpegTable.length + bytes.length - 4]; System.arraycopy(jpegTable, 0, q, 0, jpegTable.length - 2); System.arraycopy(bytes, 2, q, jpegTable.length - 2, bytes.length - 2); bytes = uncompress(q, compression, size); } else bytes = uncompress(bytes, compression, size); undifference(bytes, bitsPerSample, imageWidth, planarConfig, predictor, littleEndian); int offset = (int) (imageWidth * row); if (planarConfig == 2) { offset = overallOffset / samplesPerPixel; } unpackBytes(samples, offset, bytes, bitsPerSample, photoInterp, colorMap, littleEndian, maxValue, planarConfig, strip, (int) numStrips, imageWidth); overallOffset += bytes.length / bitsPerSample.length; } else { // concatenate contents of bytes to altBytes byte[] tempPackBits = new byte[altBytes.length]; System.arraycopy(altBytes, 0, tempPackBits, 0, altBytes.length); altBytes = new byte[altBytes.length + bytes.length]; System.arraycopy(tempPackBits, 0, altBytes, 0, tempPackBits.length); System.arraycopy(bytes, 0, altBytes, tempPackBits.length, bytes.length); } } catch (Exception e) { // CTR TODO - eliminate catch-all exception handling if (strip == 0) { if (e instanceof FormatException) throw (FormatException) e; else throw new FormatException(e); } byte[] bytes = new byte[samples[0].length]; undifference(bytes, bitsPerSample, imageWidth, planarConfig, predictor, littleEndian); int offset = (int) (imageWidth * row); if (planarConfig == 2) offset = overallOffset / samplesPerPixel; unpackBytes(samples, offset, bytes, bitsPerSample, photoInterp, colorMap, littleEndian, maxValue, planarConfig, strip, (int) numStrips, imageWidth); overallOffset += bytes.length / bitsPerSample.length; } } } // only do this if the image uses PackBits compression if (altBytes.length != 0) { altBytes = uncompress(altBytes, compression, size); undifference(altBytes, bitsPerSample, imageWidth, planarConfig, predictor, littleEndian); unpackBytes(samples, (int) imageWidth, altBytes, bitsPerSample, photoInterp, colorMap, littleEndian, maxValue, planarConfig, 0, 1, imageWidth); } // construct field if (DEBUG) debug("constructing image"); // Since the lowest common denominator for all pixel operations is "byte" // we're going to normalize everything to byte. if (bitsPerSample[0] == 12) bitsPerSample[0] = 16; if (photoInterp == CFA_ARRAY) { samples = ImageTools.demosaic(samples, (int) imageWidth, (int) imageLength); } if (bitsPerSample[0] == 16) { int pt = 0; for (int i = 0; i < samplesPerPixel; i++) { for (int j = 0; j < numSamples; j++) { buf[pt++] = (byte) ((samples[i][j] & 0xff00) >> 8); buf[pt++] = (byte) (samples[i][j] & 0xff); } } } else if (bitsPerSample[0] == 32) { int pt = 0; for (int i=0; i<samplesPerPixel; i++) { for (int j=0; j<numSamples; j++) { buf[pt++] = (byte) ((samples[i][j] & 0xff000000) >> 24); buf[pt++] = (byte) ((samples[i][j] & 0xff0000) >> 16); buf[pt++] = (byte) ((samples[i][j] & 0xff00) >> 8); buf[pt++] = (byte) (samples[i][j] & 0xff); } } } else { for (int i=0; i<samplesPerPixel; i++) { for (int j=0; j<numSamples; j++) { buf[j + i*numSamples] = (byte) samples[i][j]; } } } return buf; }
public static byte[] getSamples(Hashtable ifd, RandomAccessStream in, byte[] buf) throws FormatException, IOException { if (DEBUG) debug("parsing IFD entries"); // get internal non-IFD entries boolean littleEndian = isLittleEndian(ifd); in.order(littleEndian); // get relevant IFD entries long imageWidth = getImageWidth(ifd); long imageLength = getImageLength(ifd); int[] bitsPerSample = getBitsPerSample(ifd); int samplesPerPixel = getSamplesPerPixel(ifd); int compression = getCompression(ifd); int photoInterp = getPhotometricInterpretation(ifd); long[] stripOffsets = getStripOffsets(ifd); long[] stripByteCounts = getStripByteCounts(ifd); long[] rowsPerStripArray = getRowsPerStrip(ifd); boolean fakeByteCounts = stripByteCounts == null; boolean fakeRPS = rowsPerStripArray == null; boolean isTiled = stripOffsets == null; long[] maxes = getIFDLongArray(ifd, MAX_SAMPLE_VALUE, false); long maxValue = maxes == null ? 0 : maxes[0]; if (isTiled) { stripOffsets = getIFDLongArray(ifd, TILE_OFFSETS, true); stripByteCounts = getIFDLongArray(ifd, TILE_BYTE_COUNTS, true); rowsPerStripArray = new long[] {imageLength}; } else if (fakeByteCounts) { // technically speaking, this shouldn't happen (since TIFF writers are // required to write the StripByteCounts tag), but we'll support it // anyway // don't rely on RowsPerStrip, since it's likely that if the file doesn't // have the StripByteCounts tag, it also won't have the RowsPerStrip tag stripByteCounts = new long[stripOffsets.length]; if (stripByteCounts.length == 1) { stripByteCounts[0] = imageWidth * imageLength * (bitsPerSample[0] / 8); } else { stripByteCounts[0] = stripOffsets[0]; for (int i=1; i<stripByteCounts.length; i++) { stripByteCounts[i] = stripOffsets[i] - stripByteCounts[i-1]; } } } boolean lastBitsZero = bitsPerSample[bitsPerSample.length - 1] == 0; if (fakeRPS && !isTiled) { // create a false rowsPerStripArray if one is not present // it's sort of a cheap hack, but here's how it's done: // RowsPerStrip = stripByteCounts / (imageLength * bitsPerSample) // since stripByteCounts and bitsPerSample are arrays, we have to // iterate through each item rowsPerStripArray = new long[bitsPerSample.length]; long temp = stripByteCounts[0]; stripByteCounts = new long[bitsPerSample.length]; for (int i=0; i<stripByteCounts.length; i++) stripByteCounts[i] = temp; temp = bitsPerSample[0]; if (temp == 0) temp = 8; bitsPerSample = new int[bitsPerSample.length]; for (int i=0; i<bitsPerSample.length; i++) bitsPerSample[i] = (int) temp; temp = stripOffsets[0]; /* stripOffsets = new long[bitsPerSample.length]; for (int i=0; i<bitsPerSample.length; i++) { stripOffsets[i] = i == 0 ? temp : stripOffsets[i - 1] + stripByteCounts[i]; } */ // we have two files that reverse the endianness for BitsPerSample, // StripOffsets, and StripByteCounts if (bitsPerSample[0] > 64) { byte[] bps = new byte[2]; byte[] stripOffs = new byte[4]; byte[] byteCounts = new byte[4]; if (littleEndian) { bps[0] = (byte) (bitsPerSample[0] & 0xff); bps[1] = (byte) ((bitsPerSample[0] >>> 8) & 0xff); int ndx = stripOffsets.length - 1; stripOffs[0] = (byte) (stripOffsets[ndx] & 0xff); stripOffs[1] = (byte) ((stripOffsets[ndx] >>> 8) & 0xff); stripOffs[2] = (byte) ((stripOffsets[ndx] >>> 16) & 0xff); stripOffs[3] = (byte) ((stripOffsets[ndx] >>> 24) & 0xff); ndx = stripByteCounts.length - 1; byteCounts[0] = (byte) (stripByteCounts[ndx] & 0xff); byteCounts[1] = (byte) ((stripByteCounts[ndx] >>> 8) & 0xff); byteCounts[2] = (byte) ((stripByteCounts[ndx] >>> 16) & 0xff); byteCounts[3] = (byte) ((stripByteCounts[ndx] >>> 24) & 0xff); } else { bps[1] = (byte) ((bitsPerSample[0] >>> 16) & 0xff); bps[0] = (byte) ((bitsPerSample[0] >>> 24) & 0xff); stripOffs[3] = (byte) (stripOffsets[0] & 0xff); stripOffs[2] = (byte) ((stripOffsets[0] >>> 8) & 0xff); stripOffs[1] = (byte) ((stripOffsets[0] >>> 16) & 0xff); stripOffs[0] = (byte) ((stripOffsets[0] >>> 24) & 0xff); byteCounts[3] = (byte) (stripByteCounts[0] & 0xff); byteCounts[2] = (byte) ((stripByteCounts[0] >>> 8) & 0xff); byteCounts[1] = (byte) ((stripByteCounts[0] >>> 16) & 0xff); byteCounts[0] = (byte) ((stripByteCounts[0] >>> 24) & 0xff); } bitsPerSample[0] = DataTools.bytesToInt(bps, !littleEndian); stripOffsets[0] = DataTools.bytesToInt(stripOffs, !littleEndian); stripByteCounts[0] = DataTools.bytesToInt(byteCounts, !littleEndian); } if (rowsPerStripArray.length == 1 && stripByteCounts[0] != (imageWidth * imageLength * (bitsPerSample[0] / 8)) && compression == UNCOMPRESSED) { for (int i=0; i<stripByteCounts.length; i++) { stripByteCounts[i] = imageWidth * imageLength * (bitsPerSample[i] / 8); stripOffsets[0] = (int) (in.length() - stripByteCounts[0] - 48 * imageWidth); if (i != 0) { stripOffsets[i] = stripOffsets[i - 1] + stripByteCounts[i]; } in.seek((int) stripOffsets[i]); in.read(buf, (int) (i*imageWidth), (int) imageWidth); boolean isZero = true; for (int j=0; j<imageWidth; j++) { if (buf[(int) (i*imageWidth + j)] != 0) { isZero = false; break; } } while (isZero) { stripOffsets[i] -= imageWidth; in.seek((int) stripOffsets[i]); in.read(buf, (int) (i*imageWidth), (int) imageWidth); for (int j=0; j<imageWidth; j++) { if (buf[(int) (i*imageWidth + j)] != 0) { isZero = false; stripOffsets[i] -= (stripByteCounts[i] - imageWidth); break; } } } } } for (int i=0; i<bitsPerSample.length; i++) { // case 1: we're still within bitsPerSample array bounds if (i < bitsPerSample.length) { if (i == samplesPerPixel) { bitsPerSample[i] = 0; lastBitsZero = true; } // remember that the universe collapses when we divide by 0 if (bitsPerSample[i] != 0) { rowsPerStripArray[i] = (long) stripByteCounts[i] / (imageWidth * (bitsPerSample[i] / 8)); } else if (bitsPerSample[i] == 0 && i > 0) { rowsPerStripArray[i] = (long) stripByteCounts[i] / (imageWidth * (bitsPerSample[i - 1] / 8)); bitsPerSample[i] = bitsPerSample[i - 1]; } else { throw new FormatException("BitsPerSample is 0"); } } // case 2: we're outside bitsPerSample array bounds else if (i >= bitsPerSample.length) { rowsPerStripArray[i] = (long) stripByteCounts[i] / (imageWidth * (bitsPerSample[bitsPerSample.length - 1] / 8)); } } for (int i=0; i<stripByteCounts.length; i++) { stripByteCounts[i] *= 2; } } if (lastBitsZero) { bitsPerSample[bitsPerSample.length - 1] = 0; //samplesPerPixel--; } TiffRational xResolution = getIFDRationalValue(ifd, X_RESOLUTION, false); TiffRational yResolution = getIFDRationalValue(ifd, Y_RESOLUTION, false); int planarConfig = getIFDIntValue(ifd, PLANAR_CONFIGURATION, false, 1); int resolutionUnit = getIFDIntValue(ifd, RESOLUTION_UNIT, false, 2); if (xResolution == null || yResolution == null) resolutionUnit = 0; int[] colorMap = getIFDIntArray(ifd, COLOR_MAP, false); int predictor = getIFDIntValue(ifd, PREDICTOR, false, 1); // If the subsequent color maps are empty, use the first IFD's color map //if (colorMap == null) { // colorMap = getIFDIntArray(getFirstIFD(in), COLOR_MAP, false); //} // use special color map for YCbCr if (photoInterp == Y_CB_CR) { int[] tempColorMap = getIFDIntArray(ifd, Y_CB_CR_COEFFICIENTS, false); int[] refBlackWhite = getIFDIntArray(ifd, REFERENCE_BLACK_WHITE, false); colorMap = new int[tempColorMap.length + refBlackWhite.length]; System.arraycopy(tempColorMap, 0, colorMap, 0, tempColorMap.length); System.arraycopy(refBlackWhite, 0, colorMap, tempColorMap.length, refBlackWhite.length); } if (DEBUG) { StringBuffer sb = new StringBuffer(); sb.append("IFD directory entry values:"); sb.append("\n\tLittleEndian="); sb.append(littleEndian); sb.append("\n\tImageWidth="); sb.append(imageWidth); sb.append("\n\tImageLength="); sb.append(imageLength); sb.append("\n\tBitsPerSample="); sb.append(bitsPerSample[0]); for (int i=1; i<bitsPerSample.length; i++) { sb.append(","); sb.append(bitsPerSample[i]); } sb.append("\n\tSamplesPerPixel="); sb.append(samplesPerPixel); sb.append("\n\tCompression="); sb.append(compression); sb.append("\n\tPhotometricInterpretation="); sb.append(photoInterp); sb.append("\n\tStripOffsets="); sb.append(stripOffsets[0]); for (int i=1; i<stripOffsets.length; i++) { sb.append(","); sb.append(stripOffsets[i]); } sb.append("\n\tRowsPerStrip="); sb.append(rowsPerStripArray[0]); for (int i=1; i<rowsPerStripArray.length; i++) { sb.append(","); sb.append(rowsPerStripArray[i]); } sb.append("\n\tStripByteCounts="); sb.append(stripByteCounts[0]); for (int i=1; i<stripByteCounts.length; i++) { sb.append(","); sb.append(stripByteCounts[i]); } sb.append("\n\tXResolution="); sb.append(xResolution); sb.append("\n\tYResolution="); sb.append(yResolution); sb.append("\n\tPlanarConfiguration="); sb.append(planarConfig); sb.append("\n\tResolutionUnit="); sb.append(resolutionUnit); sb.append("\n\tColorMap="); if (colorMap == null) sb.append("null"); else { sb.append(colorMap[0]); for (int i=1; i<colorMap.length; i++) { sb.append(","); sb.append(colorMap[i]); } } sb.append("\n\tPredictor="); sb.append(predictor); debug(sb.toString()); } for (int i=0; i<samplesPerPixel; i++) { if (bitsPerSample[i] < 1) { throw new FormatException("Illegal BitsPerSample (" + bitsPerSample[i] + ")"); } // don't support odd numbers of bits (except for 1) else if (bitsPerSample[i] % 2 != 0 && bitsPerSample[i] != 1) { throw new FormatException("Sorry, unsupported BitsPerSample (" + bitsPerSample[i] + ")"); } } if (bitsPerSample.length < samplesPerPixel) { throw new FormatException("BitsPerSample length (" + bitsPerSample.length + ") does not match SamplesPerPixel (" + samplesPerPixel + ")"); } else if (photoInterp == TRANSPARENCY_MASK) { throw new FormatException( "Sorry, Transparency Mask PhotometricInterpretation is not supported"); } else if (photoInterp == Y_CB_CR) { throw new FormatException( "Sorry, YCbCr PhotometricInterpretation is not supported"); } else if (photoInterp == CIE_LAB) { throw new FormatException( "Sorry, CIELAB PhotometricInterpretation is not supported"); } else if (photoInterp != WHITE_IS_ZERO && photoInterp != BLACK_IS_ZERO && photoInterp != RGB && photoInterp != RGB_PALETTE && photoInterp != CMYK && photoInterp != Y_CB_CR && photoInterp != CFA_ARRAY) { throw new FormatException("Unknown PhotometricInterpretation (" + photoInterp + ")"); } long rowsPerStrip = rowsPerStripArray[0]; for (int i=1; i<rowsPerStripArray.length; i++) { if (rowsPerStrip != rowsPerStripArray[i]) { throw new FormatException( "Sorry, non-uniform RowsPerStrip is not supported"); } } long numStrips = (imageLength + rowsPerStrip - 1) / rowsPerStrip; if (isTiled || fakeRPS) numStrips = stripOffsets.length; if (planarConfig == 2) numStrips *= samplesPerPixel; if (stripOffsets.length < numStrips && !fakeRPS) { throw new FormatException("StripOffsets length (" + stripOffsets.length + ") does not match expected " + "number of strips (" + numStrips + ")"); } else if (fakeRPS) numStrips = stripOffsets.length; if (stripByteCounts.length < numStrips) { throw new FormatException("StripByteCounts length (" + stripByteCounts.length + ") does not match expected " + "number of strips (" + numStrips + ")"); } if (imageWidth > Integer.MAX_VALUE || imageLength > Integer.MAX_VALUE || imageWidth * imageLength > Integer.MAX_VALUE) { throw new FormatException("Sorry, ImageWidth x ImageLength > " + Integer.MAX_VALUE + " is not supported (" + imageWidth + " x " + imageLength + ")"); } int numSamples = (int) (imageWidth * imageLength); if (planarConfig != 1 && planarConfig != 2) { throw new FormatException( "Unknown PlanarConfiguration (" + planarConfig + ")"); } // read in image strips if (DEBUG) { debug("reading image data (samplesPerPixel=" + samplesPerPixel + "; numSamples=" + numSamples + ")"); } if (photoInterp == CFA_ARRAY) { int[] tempMap = new int[colorMap.length + 2]; System.arraycopy(colorMap, 0, tempMap, 0, colorMap.length); tempMap[tempMap.length - 2] = (int) imageWidth; tempMap[tempMap.length - 1] = (int) imageLength; colorMap = tempMap; } if (stripOffsets.length > 1 && (stripOffsets[stripOffsets.length - 1] == stripOffsets[stripOffsets.length - 2])) { long[] tmp = stripOffsets; stripOffsets = new long[tmp.length - 1]; System.arraycopy(tmp, 0, stripOffsets, 0, stripOffsets.length); numStrips--; } short[][] samples = new short[samplesPerPixel][numSamples]; byte[] altBytes = new byte[0]; if (bitsPerSample[0] == 16) littleEndian = !littleEndian; byte[] jpegTable = null; if (compression == JPEG) { jpegTable = (byte[]) TiffTools.getIFDValue(ifd, JPEG_TABLES); } // number of uncompressed bytes in a strip int size = (int) (imageWidth * (bitsPerSample[0] / 8) * rowsPerStrip * samplesPerPixel); if (isTiled) { long tileWidth = getIFDLongValue(ifd, TILE_WIDTH, true, 0); long tileLength = getIFDLongValue(ifd, TILE_LENGTH, true, 0); byte[] data = new byte[(int) (imageWidth * imageLength * samplesPerPixel * (bitsPerSample[0] / 8))]; int row = 0; int col = 0; int bytes = bitsPerSample[0] / 8; for (int i=0; i<stripOffsets.length; i++) { byte[] b = new byte[(int) stripByteCounts[i]]; in.seek(stripOffsets[i]); in.read(b); int len = (int) (tileWidth * tileLength * samplesPerPixel * (bitsPerSample[0] / 8)); if (jpegTable != null) { byte[] q = new byte[jpegTable.length + b.length - 4]; System.arraycopy(jpegTable, 0, q, 0, jpegTable.length - 2); System.arraycopy(b, 2, q, jpegTable.length - 2, b.length - 2); b = uncompress(q, compression, len); } else b = uncompress(b, compression, len); int ext = (int) (b.length / (tileWidth * tileLength)); int rowBytes = (int) (tileWidth * ext); for (int j=0; j<tileLength; j++) { if (row + j < imageLength) { int rowLen = rowBytes; int offset = (int) ((row + j) * imageWidth * ext + ext * col); if (col + tileWidth > imageWidth) { rowLen = ext * (int) (imageWidth - col); } System.arraycopy(b, rowBytes*j, data, offset, rowLen); } else break; } // update row and column col += (int) tileWidth; if (col >= imageWidth) { row += (int) tileLength; col = 0; } } undifference(data, bitsPerSample, imageWidth, planarConfig, predictor, littleEndian); unpackBytes(samples, 0, data, bitsPerSample, photoInterp, colorMap, littleEndian, maxValue, planarConfig, 0, 1, imageWidth); } else { int overallOffset = 0; for (int strip=0, row=0; strip<numStrips; strip++, row+=rowsPerStrip) { try { if (DEBUG) debug("reading image strip #" + strip); in.seek((int) stripOffsets[strip]); if (stripByteCounts[strip] > Integer.MAX_VALUE) { throw new FormatException("Sorry, StripByteCounts > " + Integer.MAX_VALUE + " is not supported"); } byte[] bytes = new byte[(int) stripByteCounts[strip]]; in.read(bytes); if (compression != PACK_BITS) { if (jpegTable != null) { byte[] q = new byte[jpegTable.length + bytes.length - 4]; System.arraycopy(jpegTable, 0, q, 0, jpegTable.length - 2); System.arraycopy(bytes, 2, q, jpegTable.length - 2, bytes.length - 2); bytes = uncompress(q, compression, size); } else bytes = uncompress(bytes, compression, size); undifference(bytes, bitsPerSample, imageWidth, planarConfig, predictor, littleEndian); int offset = (int) (imageWidth * row); if (planarConfig == 2) { offset = overallOffset / samplesPerPixel; } unpackBytes(samples, offset, bytes, bitsPerSample, photoInterp, colorMap, littleEndian, maxValue, planarConfig, strip, (int) numStrips, imageWidth); overallOffset += bytes.length / bitsPerSample.length; } else { // concatenate contents of bytes to altBytes byte[] tempPackBits = new byte[altBytes.length]; System.arraycopy(altBytes, 0, tempPackBits, 0, altBytes.length); altBytes = new byte[altBytes.length + bytes.length]; System.arraycopy(tempPackBits, 0, altBytes, 0, tempPackBits.length); System.arraycopy(bytes, 0, altBytes, tempPackBits.length, bytes.length); } } catch (Exception e) { // CTR TODO - eliminate catch-all exception handling if (strip == 0) { if (e instanceof FormatException) throw (FormatException) e; else throw new FormatException(e); } byte[] bytes = new byte[samples[0].length]; undifference(bytes, bitsPerSample, imageWidth, planarConfig, predictor, littleEndian); int offset = (int) (imageWidth * row); if (planarConfig == 2) offset = overallOffset / samplesPerPixel; unpackBytes(samples, offset, bytes, bitsPerSample, photoInterp, colorMap, littleEndian, maxValue, planarConfig, strip, (int) numStrips, imageWidth); overallOffset += bytes.length / bitsPerSample.length; } } } // only do this if the image uses PackBits compression if (altBytes.length != 0) { altBytes = uncompress(altBytes, compression, size); undifference(altBytes, bitsPerSample, imageWidth, planarConfig, predictor, littleEndian); unpackBytes(samples, (int) imageWidth, altBytes, bitsPerSample, photoInterp, colorMap, littleEndian, maxValue, planarConfig, 0, 1, imageWidth); } // construct field if (DEBUG) debug("constructing image"); // Since the lowest common denominator for all pixel operations is "byte" // we're going to normalize everything to byte. if (bitsPerSample[0] == 12) bitsPerSample[0] = 16; if (photoInterp == CFA_ARRAY) { samples = ImageTools.demosaic(samples, (int) imageWidth, (int) imageLength); } if (bitsPerSample[0] == 16) { int pt = 0; for (int i = 0; i < samplesPerPixel; i++) { for (int j = 0; j < numSamples; j++) { buf[pt++] = (byte) ((samples[i][j] & 0xff00) >> 8); buf[pt++] = (byte) (samples[i][j] & 0xff); } } } else if (bitsPerSample[0] == 32) { int pt = 0; for (int i=0; i<samplesPerPixel; i++) { for (int j=0; j<numSamples; j++) { buf[pt++] = (byte) ((samples[i][j] & 0xff000000) >> 24); buf[pt++] = (byte) ((samples[i][j] & 0xff0000) >> 16); buf[pt++] = (byte) ((samples[i][j] & 0xff00) >> 8); buf[pt++] = (byte) (samples[i][j] & 0xff); } } } else { for (int i=0; i<samplesPerPixel; i++) { for (int j=0; j<numSamples; j++) { buf[j + i*numSamples] = (byte) samples[i][j]; } } } return buf; }
diff --git a/nuxeo-platform-importer-core/src/main/java/org/nuxeo/ecm/platform/importer/random/FrenchDictionaryHolder.java b/nuxeo-platform-importer-core/src/main/java/org/nuxeo/ecm/platform/importer/random/FrenchDictionaryHolder.java index fb5b1e19..a72217fe 100644 --- a/nuxeo-platform-importer-core/src/main/java/org/nuxeo/ecm/platform/importer/random/FrenchDictionaryHolder.java +++ b/nuxeo-platform-importer-core/src/main/java/org/nuxeo/ecm/platform/importer/random/FrenchDictionaryHolder.java @@ -1,79 +1,79 @@ package org.nuxeo.ecm.platform.importer.random; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.LinkedList; import java.util.List; import java.util.Random; import org.nuxeo.common.utils.FileUtils; public class FrenchDictionaryHolder implements DictionaryHolder { protected List<String> words = new LinkedList<String>(); protected Random generator; protected int wordCount; public FrenchDictionaryHolder() throws Exception { generator = new Random (System.currentTimeMillis()); } public void init() throws Exception { loadDic("fr_FR.dic"); wordCount = words.size(); } protected void loadDic(String dicName) throws Exception { //File dic = FileUtils.getResourceFileFromContext(dicName); URL url = Thread.currentThread().getContextClassLoader().getResource(dicName); BufferedReader reader = null; try { //InputStream in = new FileInputStream(dic); InputStream in = url.openStream(); reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { int idx = line.indexOf("/"); if (idx>0) { String word = line.substring(0, idx); words.add(word + " "); } else { - words.add(line); + words.add(line + " "); } } } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } } /* (non-Javadoc) * @see org.nuxeo.ecm.platform.importer.random.DictionaryHolder#getWordCount() */ public int getWordCount() { return wordCount; } /* (non-Javadoc) * @see org.nuxeo.ecm.platform.importer.random.DictionaryHolder#getRandomWord() */ public String getRandomWord() { int idx = generator.nextInt(wordCount); return words.get(idx); } }
true
true
protected void loadDic(String dicName) throws Exception { //File dic = FileUtils.getResourceFileFromContext(dicName); URL url = Thread.currentThread().getContextClassLoader().getResource(dicName); BufferedReader reader = null; try { //InputStream in = new FileInputStream(dic); InputStream in = url.openStream(); reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { int idx = line.indexOf("/"); if (idx>0) { String word = line.substring(0, idx); words.add(word + " "); } else { words.add(line); } } } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } }
protected void loadDic(String dicName) throws Exception { //File dic = FileUtils.getResourceFileFromContext(dicName); URL url = Thread.currentThread().getContextClassLoader().getResource(dicName); BufferedReader reader = null; try { //InputStream in = new FileInputStream(dic); InputStream in = url.openStream(); reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { int idx = line.indexOf("/"); if (idx>0) { String word = line.substring(0, idx); words.add(word + " "); } else { words.add(line + " "); } } } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } }
diff --git a/core/src/com/google/zxing/common/PerspectiveTransform.java b/core/src/com/google/zxing/common/PerspectiveTransform.java index bb987d31..4e0defce 100644 --- a/core/src/com/google/zxing/common/PerspectiveTransform.java +++ b/core/src/com/google/zxing/common/PerspectiveTransform.java @@ -1,156 +1,157 @@ /* * Copyright 2007 ZXing 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 com.google.zxing.common; /** * <p>This class implements a perspective transform in two dimensions. Given four source and four * destination points, it will compute the transformation implied between them. The code is based * directly upon section 3.4.2 of George Wolberg's "Digital Image Warping"; see pages 54-56.</p> * * @author Sean Owen */ public final class PerspectiveTransform { private final float a11; private final float a12; private final float a13; private final float a21; private final float a22; private final float a23; private final float a31; private final float a32; private final float a33; private PerspectiveTransform(float a11, float a21, float a31, float a12, float a22, float a32, float a13, float a23, float a33) { this.a11 = a11; this.a12 = a12; this.a13 = a13; this.a21 = a21; this.a22 = a22; this.a23 = a23; this.a31 = a31; this.a32 = a32; this.a33 = a33; } public static PerspectiveTransform quadrilateralToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float x0p, float y0p, float x1p, float y1p, float x2p, float y2p, float x3p, float y3p) { PerspectiveTransform qToS = quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3); PerspectiveTransform sToQ = squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p); return sToQ.times(qToS); } public void transformPoints(float[] points) { int max = points.length; float a11 = this.a11; float a12 = this.a12; float a13 = this.a13; float a21 = this.a21; float a22 = this.a22; float a23 = this.a23; float a31 = this.a31; float a32 = this.a32; float a33 = this.a33; for (int i = 0; i < max; i += 2) { float x = points[i]; float y = points[i + 1]; float denominator = a13 * x + a23 * y + a33; points[i] = (a11 * x + a21 * y + a31) / denominator; points[i + 1] = (a12 * x + a22 * y + a32) / denominator; } } /** Convenience method, not optimized for performance. */ public void transformPoints(float[] xValues, float[] yValues) { int n = xValues.length; for (int i = 0; i < n; i ++) { float x = xValues[i]; float y = yValues[i]; float denominator = a13 * x + a23 * y + a33; xValues[i] = (a11 * x + a21 * y + a31) / denominator; yValues[i] = (a12 * x + a22 * y + a32) / denominator; } } public static PerspectiveTransform squareToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) { - float dy2 = y3 - y2; + float dx3 = x0 - x1 + x2 - x3; float dy3 = y0 - y1 + y2 - y3; - if (dy2 == 0.0f && dy3 == 0.0f) { + if (dx3 == 0.0f && dy3 == 0.0f) { + // Affine return new PerspectiveTransform(x1 - x0, x2 - x1, x0, - y1 - y0, y2 - y1, y0, - 0.0f, 0.0f, 1.0f); + y1 - y0, y2 - y1, y0, + 0.0f, 0.0f, 1.0f); } else { float dx1 = x1 - x2; float dx2 = x3 - x2; - float dx3 = x0 - x1 + x2 - x3; float dy1 = y1 - y2; + float dy2 = y3 - y2; float denominator = dx1 * dy2 - dx2 * dy1; float a13 = (dx3 * dy2 - dx2 * dy3) / denominator; float a23 = (dx1 * dy3 - dx3 * dy1) / denominator; return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, - y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, - a13, a23, 1.0f); + y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, + a13, a23, 1.0f); } } public static PerspectiveTransform quadrilateralToSquare(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) { // Here, the adjoint serves as the inverse: return squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint(); } PerspectiveTransform buildAdjoint() { // Adjoint is the transpose of the cofactor matrix: return new PerspectiveTransform(a22 * a33 - a23 * a32, a23 * a31 - a21 * a33, a21 * a32 - a22 * a31, a13 * a32 - a12 * a33, a11 * a33 - a13 * a31, a12 * a31 - a11 * a32, a12 * a23 - a13 * a22, a13 * a21 - a11 * a23, a11 * a22 - a12 * a21); } PerspectiveTransform times(PerspectiveTransform other) { return new PerspectiveTransform(a11 * other.a11 + a21 * other.a12 + a31 * other.a13, a11 * other.a21 + a21 * other.a22 + a31 * other.a23, a11 * other.a31 + a21 * other.a32 + a31 * other.a33, a12 * other.a11 + a22 * other.a12 + a32 * other.a13, a12 * other.a21 + a22 * other.a22 + a32 * other.a23, a12 * other.a31 + a22 * other.a32 + a32 * other.a33, a13 * other.a11 + a23 * other.a12 + a33 * other.a13, a13 * other.a21 + a23 * other.a22 + a33 * other.a23, a13 * other.a31 + a23 * other.a32 + a33 * other.a33); } }
false
true
public static PerspectiveTransform squareToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) { float dy2 = y3 - y2; float dy3 = y0 - y1 + y2 - y3; if (dy2 == 0.0f && dy3 == 0.0f) { return new PerspectiveTransform(x1 - x0, x2 - x1, x0, y1 - y0, y2 - y1, y0, 0.0f, 0.0f, 1.0f); } else { float dx1 = x1 - x2; float dx2 = x3 - x2; float dx3 = x0 - x1 + x2 - x3; float dy1 = y1 - y2; float denominator = dx1 * dy2 - dx2 * dy1; float a13 = (dx3 * dy2 - dx2 * dy3) / denominator; float a23 = (dx1 * dy3 - dx3 * dy1) / denominator; return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, a13, a23, 1.0f); } }
public static PerspectiveTransform squareToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) { float dx3 = x0 - x1 + x2 - x3; float dy3 = y0 - y1 + y2 - y3; if (dx3 == 0.0f && dy3 == 0.0f) { // Affine return new PerspectiveTransform(x1 - x0, x2 - x1, x0, y1 - y0, y2 - y1, y0, 0.0f, 0.0f, 1.0f); } else { float dx1 = x1 - x2; float dx2 = x3 - x2; float dy1 = y1 - y2; float dy2 = y3 - y2; float denominator = dx1 * dy2 - dx2 * dy1; float a13 = (dx3 * dy2 - dx2 * dy3) / denominator; float a23 = (dx1 * dy3 - dx3 * dy1) / denominator; return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, a13, a23, 1.0f); } }
diff --git a/webac/src/main/java/ar/com/thinksoft/ac/webac/web/reclamo/detalleReclamo/DetalleReclamoForm.java b/webac/src/main/java/ar/com/thinksoft/ac/webac/web/reclamo/detalleReclamo/DetalleReclamoForm.java index 6bde556..84908fd 100644 --- a/webac/src/main/java/ar/com/thinksoft/ac/webac/web/reclamo/detalleReclamo/DetalleReclamoForm.java +++ b/webac/src/main/java/ar/com/thinksoft/ac/webac/web/reclamo/detalleReclamo/DetalleReclamoForm.java @@ -1,74 +1,75 @@ package ar.com.thinksoft.ac.webac.web.reclamo.detalleReclamo; import java.util.List; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Button; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.IModel; import ar.com.thinksoft.ac.intac.IImagen; import ar.com.thinksoft.ac.intac.IReclamo; import ar.com.thinksoft.ac.webac.HomePage; import ar.com.thinksoft.ac.webac.logging.LogFwk; import ar.com.thinksoft.ac.webac.predicates.PredicatePorUUID; import ar.com.thinksoft.ac.webac.reclamo.ImageFactory; import ar.com.thinksoft.ac.webac.reclamo.Reclamo; import ar.com.thinksoft.ac.webac.reclamo.ReclamoManager; import ar.com.thinksoft.ac.webac.web.reclamo.altaReclamo.AltaReclamoForm; import ar.com.thinksoft.ac.webac.web.reclamo.busquedaReclamo.BusquedaReclamoPage; @SuppressWarnings("serial") public class DetalleReclamoForm extends Form<Reclamo>{ private ImageFactory img = null; public DetalleReclamoForm(String id, String idReclamo) throws Exception { super(id); setMultiPart(true); List<IReclamo> lista = ReclamoManager.getInstance().obtenerReclamosFiltradosConPredicates(new PredicatePorUUID().filtrar(idReclamo)); if(lista.size()!= 1) throw new Exception("error en la base de datos, por favor, comuniquese con el equipo de soporte tecnico"); CompoundPropertyModel<Reclamo> model = new CompoundPropertyModel<Reclamo>(lista.get(0)); setModel(model); add(new Label("calleIncidente", this.createBind(model,"calleIncidente"))); add(new Label("alturaIncidente",this.createBind(model,"alturaIncidente"))); add(new Label("latitudIncidente",this.createBind(model,"latitudIncidente"))); add(new Label("longitudIncidente",this.createBind(model,"longitudIncidente"))); add(new Label("ciudadanoReclamo",this.createBind(model,"ciudadanoReclamo"))); add(new Label("prioridad",this.createBind(model,"prioridad"))); add(new Label("estadoDescripcion",this.createBind(model,"EstadoDescripcion"))); add(new Label("tipoIncidente", this.createBind(model,"tipoIncidente"))); add(new Label("observaciones",this.createBind(model, "observaciones"))); try{ IImagen imagen = lista.get(0).getImagen(); img = new ImageFactory(imagen); add(new Label("rutaImagen",imagen.getFileName())); }catch(Exception e){ LogFwk.getInstance(DetalleReclamoForm.class).error("no existe imagen para este reclamo"); + add(new Label("rutaImagen","")); } add(new Button("volver") { @Override public void onSubmit() { try{ img.deleteImage(); }catch(Exception e){ LogFwk.getInstance(AltaReclamoForm.class).error("No existe archivo para borrar."); } setResponsePage(BusquedaReclamoPage.class); } }); } private IModel<String> createBind(CompoundPropertyModel<Reclamo> model,String property){ return model.bind(property); } }
true
true
public DetalleReclamoForm(String id, String idReclamo) throws Exception { super(id); setMultiPart(true); List<IReclamo> lista = ReclamoManager.getInstance().obtenerReclamosFiltradosConPredicates(new PredicatePorUUID().filtrar(idReclamo)); if(lista.size()!= 1) throw new Exception("error en la base de datos, por favor, comuniquese con el equipo de soporte tecnico"); CompoundPropertyModel<Reclamo> model = new CompoundPropertyModel<Reclamo>(lista.get(0)); setModel(model); add(new Label("calleIncidente", this.createBind(model,"calleIncidente"))); add(new Label("alturaIncidente",this.createBind(model,"alturaIncidente"))); add(new Label("latitudIncidente",this.createBind(model,"latitudIncidente"))); add(new Label("longitudIncidente",this.createBind(model,"longitudIncidente"))); add(new Label("ciudadanoReclamo",this.createBind(model,"ciudadanoReclamo"))); add(new Label("prioridad",this.createBind(model,"prioridad"))); add(new Label("estadoDescripcion",this.createBind(model,"EstadoDescripcion"))); add(new Label("tipoIncidente", this.createBind(model,"tipoIncidente"))); add(new Label("observaciones",this.createBind(model, "observaciones"))); try{ IImagen imagen = lista.get(0).getImagen(); img = new ImageFactory(imagen); add(new Label("rutaImagen",imagen.getFileName())); }catch(Exception e){ LogFwk.getInstance(DetalleReclamoForm.class).error("no existe imagen para este reclamo"); } add(new Button("volver") { @Override public void onSubmit() { try{ img.deleteImage(); }catch(Exception e){ LogFwk.getInstance(AltaReclamoForm.class).error("No existe archivo para borrar."); } setResponsePage(BusquedaReclamoPage.class); } }); }
public DetalleReclamoForm(String id, String idReclamo) throws Exception { super(id); setMultiPart(true); List<IReclamo> lista = ReclamoManager.getInstance().obtenerReclamosFiltradosConPredicates(new PredicatePorUUID().filtrar(idReclamo)); if(lista.size()!= 1) throw new Exception("error en la base de datos, por favor, comuniquese con el equipo de soporte tecnico"); CompoundPropertyModel<Reclamo> model = new CompoundPropertyModel<Reclamo>(lista.get(0)); setModel(model); add(new Label("calleIncidente", this.createBind(model,"calleIncidente"))); add(new Label("alturaIncidente",this.createBind(model,"alturaIncidente"))); add(new Label("latitudIncidente",this.createBind(model,"latitudIncidente"))); add(new Label("longitudIncidente",this.createBind(model,"longitudIncidente"))); add(new Label("ciudadanoReclamo",this.createBind(model,"ciudadanoReclamo"))); add(new Label("prioridad",this.createBind(model,"prioridad"))); add(new Label("estadoDescripcion",this.createBind(model,"EstadoDescripcion"))); add(new Label("tipoIncidente", this.createBind(model,"tipoIncidente"))); add(new Label("observaciones",this.createBind(model, "observaciones"))); try{ IImagen imagen = lista.get(0).getImagen(); img = new ImageFactory(imagen); add(new Label("rutaImagen",imagen.getFileName())); }catch(Exception e){ LogFwk.getInstance(DetalleReclamoForm.class).error("no existe imagen para este reclamo"); add(new Label("rutaImagen","")); } add(new Button("volver") { @Override public void onSubmit() { try{ img.deleteImage(); }catch(Exception e){ LogFwk.getInstance(AltaReclamoForm.class).error("No existe archivo para borrar."); } setResponsePage(BusquedaReclamoPage.class); } }); }
diff --git a/gui/src/main/java/org/openpnp/machine/reference/feeder/ReferenceTrayFeeder.java b/gui/src/main/java/org/openpnp/machine/reference/feeder/ReferenceTrayFeeder.java index 43716f9684..8faa97db3d 100644 --- a/gui/src/main/java/org/openpnp/machine/reference/feeder/ReferenceTrayFeeder.java +++ b/gui/src/main/java/org/openpnp/machine/reference/feeder/ReferenceTrayFeeder.java @@ -1,145 +1,144 @@ /* Copyright (C) 2011 Jason von Nieda <[email protected]> This file is part of OpenPnP. OpenPnP 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. OpenPnP 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 OpenPnP. If not, see <http://www.gnu.org/licenses/>. For more information about OpenPnP visit http://openpnp.org */ package org.openpnp.machine.reference.feeder; import org.openpnp.gui.support.Wizard; import org.openpnp.machine.reference.ReferenceFeeder; import org.openpnp.machine.reference.feeder.wizards.ReferenceTrayFeederConfigurationWizard; import org.openpnp.model.LengthUnit; import org.openpnp.model.Location; import org.openpnp.model.Part; import org.openpnp.spi.Nozzle; import org.simpleframework.xml.Attribute; import org.simpleframework.xml.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implementation of Feeder that indexes based on an offset. This allows a tray of * parts to be picked from without moving any tape. Can handle trays of * arbitrary X and Y count. */ public class ReferenceTrayFeeder extends ReferenceFeeder { private final static Logger logger = LoggerFactory.getLogger(ReferenceTrayFeeder.class); @Attribute private int trayCountX = 1; @Attribute private int trayCountY = 1; @Element private Location offsets = new Location(LengthUnit.Millimeters); @Attribute private int feedCount = 0; private Location pickLocation; @Override public boolean canFeedToNozzle(Nozzle nozzle) { boolean result = (feedCount < (trayCountX * trayCountY)); logger.debug("{}.canFeedToNozzle({}) => {}", new Object[]{getId(), nozzle, result}); return result; } @Override public Location getPickLocation() throws Exception { if (pickLocation == null) { pickLocation = location; } logger.debug("{}.getPickLocation => {}", getId(), pickLocation); return pickLocation; } public void feed(Nozzle nozzle) throws Exception { logger.debug("{}.feed({})", getId(), nozzle); int partX, partY; if (trayCountX >= trayCountY) { // X major axis. partX = feedCount / trayCountY; partY = feedCount % trayCountY; } else { // Y major axis. partX = feedCount % trayCountX; partY = feedCount / trayCountX; } // Multiply the offsets by the X/Y part indexes to get the total offsets - // and then add the pickLocation to offset the final value. - pickLocation = offsets - .multiply(partX, partY, 0.0, 0.0) - .add(location); + // and then add them to the location to get the final pickLocation. + pickLocation = location.add( + offsets.multiply(partX, partY, 0.0, 0.0)); logger.debug(String.format( "Feeding part # %d, x %d, y %d, xPos %f, yPos %f", feedCount, partX, partY, pickLocation.getX(), pickLocation.getY())); feedCount++; } @Override public Wizard getConfigurationWizard() { return new ReferenceTrayFeederConfigurationWizard(this); } public int getTrayCountX() { return trayCountX; } public void setTrayCountX(int trayCountX) { this.trayCountX = trayCountX; } public int getTrayCountY() { return trayCountY; } public void setTrayCountY(int trayCountY) { this.trayCountY = trayCountY; } public Location getOffsets() { return offsets; } public void setOffsets(Location offsets) { this.offsets = offsets; } public int getFeedCount() { return feedCount; } public void setFeedCount(int feedCount) { this.feedCount = feedCount; } @Override public String toString() { return getId(); } }
true
true
public void feed(Nozzle nozzle) throws Exception { logger.debug("{}.feed({})", getId(), nozzle); int partX, partY; if (trayCountX >= trayCountY) { // X major axis. partX = feedCount / trayCountY; partY = feedCount % trayCountY; } else { // Y major axis. partX = feedCount % trayCountX; partY = feedCount / trayCountX; } // Multiply the offsets by the X/Y part indexes to get the total offsets // and then add the pickLocation to offset the final value. pickLocation = offsets .multiply(partX, partY, 0.0, 0.0) .add(location); logger.debug(String.format( "Feeding part # %d, x %d, y %d, xPos %f, yPos %f", feedCount, partX, partY, pickLocation.getX(), pickLocation.getY())); feedCount++; }
public void feed(Nozzle nozzle) throws Exception { logger.debug("{}.feed({})", getId(), nozzle); int partX, partY; if (trayCountX >= trayCountY) { // X major axis. partX = feedCount / trayCountY; partY = feedCount % trayCountY; } else { // Y major axis. partX = feedCount % trayCountX; partY = feedCount / trayCountX; } // Multiply the offsets by the X/Y part indexes to get the total offsets // and then add them to the location to get the final pickLocation. pickLocation = location.add( offsets.multiply(partX, partY, 0.0, 0.0)); logger.debug(String.format( "Feeding part # %d, x %d, y %d, xPos %f, yPos %f", feedCount, partX, partY, pickLocation.getX(), pickLocation.getY())); feedCount++; }
diff --git a/src/main/java/uk/ac/imperial/lpgdash/LPGCLI.java b/src/main/java/uk/ac/imperial/lpgdash/LPGCLI.java index 91ba7e0..21d96e7 100644 --- a/src/main/java/uk/ac/imperial/lpgdash/LPGCLI.java +++ b/src/main/java/uk/ac/imperial/lpgdash/LPGCLI.java @@ -1,331 +1,332 @@ package uk.ac.imperial.lpgdash; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.log4j.Logger; import uk.ac.imperial.lpgdash.db.Queries; import uk.ac.imperial.lpgdash.facts.Allocation; import uk.ac.imperial.presage2.core.cli.Presage2CLI; import uk.ac.imperial.presage2.core.db.persistent.PersistentSimulation; public class LPGCLI extends Presage2CLI { private final Logger logger = Logger.getLogger(LPGCLI.class); protected LPGCLI() { super(LPGCLI.class); } public static void main(String[] args) { Presage2CLI cli = new LPGCLI(); cli.invokeCommand(args); } @Command(name = "insert", description = "Insert a batch of simulations to run.") public void insert_batch(String[] args) { Options options = new Options(); // generate experiment types Map<String, String> experiments = new HashMap<String, String>(); experiments.put("lc_comparison", "Compare individual legitimate claims + fixed and SO weights."); experiments .put("het_hom", "Compare allocation methods in heterogeneous and homogeneous populations."); experiments .put("multi_cluster", "Multi-cluster scenario with lc_so and random allocations over beta {0.1,0.4}"); OptionGroup exprOptions = new OptionGroup(); for (String key : experiments.keySet()) { exprOptions.addOption(new Option(key, experiments.get(key))); } // check for experiment type argument if (args.length < 2 || !experiments.containsKey(args[1])) { options.addOptionGroup(exprOptions); HelpFormatter formatter = new HelpFormatter(); formatter.setOptPrefix(""); formatter.printHelp("presage2cli insert <experiment>", options, false); return; } // optional random seed arg options.addOption( "s", "seed", true, "Random seed to start with (subsequent repeats use incrementing seeds from this value)"); int repeats = 0; try { repeats = Integer.parseInt(args[2]); } catch (ArrayIndexOutOfBoundsException e) { logger.warn("REPEATS argument missing"); } catch (NumberFormatException e) { logger.warn("REPEATS argument is not a valid integer"); } if (repeats <= 0) { HelpFormatter formatter = new HelpFormatter(); // formatter.setOptPrefix(""); formatter.printHelp("presage2cli insert " + args[1] + " REPEATS", options, true); return; } CommandLineParser parser = new GnuParser(); CommandLine cmd; int seed = 0; try { cmd = parser.parse(options, args); seed = Integer.parseInt(cmd.getOptionValue("seed")); } catch (ParseException e) { e.printStackTrace(); return; } catch (NumberFormatException e) { } catch (NullPointerException e) { } if (args[1].equalsIgnoreCase("lc_comparison")) { lc_comparison(repeats, seed); } else if (args[1].equalsIgnoreCase("het_hom")) { het_hom(repeats, seed); } else if (args[1].equalsIgnoreCase("multi_cluster")) { multi_cluster(repeats, seed); } } void lc_comparison(int repeats, int seed) { Allocation[] clusters = { Allocation.LC_F1a, Allocation.LC_F1b, Allocation.LC_F1c, Allocation.LC_F2, Allocation.LC_F3, Allocation.LC_F4, Allocation.LC_F5, Allocation.LC_F6, Allocation.LC_FIXED, Allocation.LC_SO }; int rounds = 1002; for (int i = 0; i < repeats; i++) { for (Allocation cluster : clusters) { PersistentSimulation sim = getDatabase().createSimulation( cluster.name(), "uk.ac.imperial.lpgdash.LPGGameSimulation", "AUTO START", rounds); sim.addParameter("finishTime", Integer.toString(rounds)); sim.addParameter("alpha", Double.toString(0.1)); sim.addParameter("beta", Double.toString(0.1)); sim.addParameter("gamma", Double.toString(0.1)); sim.addParameter("cCount", Integer.toString(20)); sim.addParameter("cPCheat", Double.toString(0.02)); sim.addParameter("ncCount", Integer.toString(10)); sim.addParameter("ncPCheat", Double.toString(0.25)); sim.addParameter("seed", Integer.toString(seed + i)); sim.addParameter("soHack", Boolean.toString(true)); sim.addParameter("clusters", cluster.name()); sim.addParameter("cheatOn", Cheat.PROVISION.name()); logger.info("Created sim: " + sim.getID() + " - " + sim.getName()); } } stopDatabase(); } void het_hom(int repeats, int seed) { Allocation[] clusters = { Allocation.RATION, Allocation.RANDOM, Allocation.LC_FIXED, Allocation.LC_SO }; String[] populations = { "het01", "hom01", "hom04" }; int rounds = 1002; for (int i = 0; i < repeats; i++) { for (Allocation cluster : clusters) { for (String pop : populations) { double beta = 0.1; int c = 30; double cPCheat = 0.0; if (pop.endsWith("04")) beta = 0.4; if (pop.startsWith("het")) { c = 20; cPCheat = 0.02; } PersistentSimulation sim = getDatabase().createSimulation( cluster.name() + "_" + pop, "uk.ac.imperial.lpgdash.LPGGameSimulation", "AUTO START", rounds); sim.addParameter("finishTime", Integer.toString(rounds)); sim.addParameter("alpha", Double.toString(0.1)); sim.addParameter("beta", Double.toString(beta)); sim.addParameter("gamma", Double.toString(0.1)); sim.addParameter("cCount", Integer.toString(c)); sim.addParameter("cPCheat", Double.toString(cPCheat)); sim.addParameter("ncCount", Integer.toString(30 - c)); sim.addParameter("ncPCheat", Double.toString(0.25)); sim.addParameter("seed", Integer.toString(seed + i)); sim.addParameter("soHack", Boolean.toString(true)); sim.addParameter("clusters", cluster.name()); sim.addParameter("cheatOn", Cheat.PROVISION.name()); logger.info("Created sim: " + sim.getID() + " - " + sim.getName()); } } } stopDatabase(); } void multi_cluster(int repeats, int seed) { int rounds = 3000; double[] betas = { 0.1, 0.4 }; String cluster = Allocation.LC_SO.name() + "," + Allocation.RANDOM; for (int i = 0; i < repeats; i++) { for (double beta : betas) { PersistentSimulation sim = getDatabase().createSimulation( cluster + "_b=" + beta, "uk.ac.imperial.lpgdash.LPGGameSimulation", "AUTO START", rounds); sim.addParameter("finishTime", Integer.toString(rounds)); sim.addParameter("alpha", Double.toString(0.1)); sim.addParameter("beta", Double.toString(beta)); sim.addParameter("gamma", Double.toString(0.1)); sim.addParameter("cCount", Integer.toString(20)); sim.addParameter("cPCheat", Double.toString(0.02)); sim.addParameter("ncCount", Integer.toString(20)); sim.addParameter("ncPCheat", Double.toString(0.25)); sim.addParameter("seed", Integer.toString(seed + i)); sim.addParameter("soHack", Boolean.toString(true)); sim.addParameter("clusters", cluster); sim.addParameter("cheatOn", Cheat.PROVISION.name()); } } stopDatabase(); } @Command(name = "summarise", description = "Process raw simulation data to generate evaluation metrics.") public void summarise(String[] args) { logger.warn("This implementation assumes you are using postgresql >=9.1 with hstore, it will fail otherwise."); // get database to trigger injector creation getDatabase(); // pull JDBC connection from injector Connection conn = injector.getInstance(Connection.class); try { logger.info("Creating tables and views. "); logger.info("CREATE VIEW allocationRatios"); conn.createStatement().execute( Queries.getQuery("create_allocationratios")); logger.info("CREATE TABLE simulationSummary"); conn.createStatement().execute( Queries.getQuery("create_simulationsummary")); logger.info("CREATE VIEW aggregatedSimulations"); conn.createStatement().execute( Queries.getQuery("create_aggregatedsimulations")); logger.info("CREATE TABLE aggregatePlayerScore"); conn.createStatement().execute( Queries.getQuery("create_aggregateplayerscore")); logger.info("Processing simulations..."); // prepare statements PreparedStatement aggregatePlayerScore = conn .prepareStatement(Queries .getQuery("insert_aggregateplayerscore")); PreparedStatement clusterStats = conn.prepareStatement(Queries .getQuery("select_clusters")); PreparedStatement remaining = conn.prepareStatement(Queries .getQuery("select_agentsremaining")); PreparedStatement insertSummary = conn.prepareStatement(Queries .getQuery("insert_simulationsummary")); // get subset to process ResultSet unprocessed = conn.createStatement().executeQuery( Queries.getQuery("select_unprocessedsimulations")); while (unprocessed.next()) { long id = unprocessed.getLong(1); String name = unprocessed.getString(2); int finishTime = unprocessed.getInt(3); int cutoff = (int) (Math.floor(finishTime / 2)) - 1; logger.info(id + ": " + name); // START TRANSACTION conn.setAutoCommit(false); // generate player scores per cluster aggregatePlayerScore.setLong(1, id); aggregatePlayerScore.setLong(2, id); aggregatePlayerScore.execute(); clusterStats.setLong(1, id); ResultSet clusters = clusterStats.executeQuery(); logger.debug("Cutoff: " + cutoff); while (clusters.next()) { int cluster = clusters.getInt(1); logger.debug("Cluster " + cluster); // calculate c and nc remaining int crem = 0; int ncrem = 0; remaining.setLong(1, id); remaining.setString(2, "c%"); remaining.setInt(3, cutoff); + remaining.setInt(4, cluster); ResultSet rs = remaining.executeQuery(); if (rs.next()) { crem = rs.getInt(1); } remaining.setString(2, "nc%"); rs = remaining.executeQuery(); if (rs.next()) { ncrem = rs.getInt(1); } // insert summary insertSummary.setLong(1, id); insertSummary.setString(2, name); insertSummary.setInt(3, cluster); insertSummary.setDouble(4, clusters.getDouble(2)); insertSummary.setDouble(5, clusters.getDouble(3)); insertSummary.setDouble(6, clusters.getDouble(4)); insertSummary.setDouble(7, clusters.getDouble(5)); insertSummary.setDouble(8, clusters.getDouble(6)); insertSummary.setInt(9, crem); insertSummary.setInt(10, ncrem); insertSummary.execute(); } // COMMIT TRANSACTION conn.commit(); } } catch (SQLException e) { throw new RuntimeException(e); } finally { stopDatabase(); } } }
true
true
public void summarise(String[] args) { logger.warn("This implementation assumes you are using postgresql >=9.1 with hstore, it will fail otherwise."); // get database to trigger injector creation getDatabase(); // pull JDBC connection from injector Connection conn = injector.getInstance(Connection.class); try { logger.info("Creating tables and views. "); logger.info("CREATE VIEW allocationRatios"); conn.createStatement().execute( Queries.getQuery("create_allocationratios")); logger.info("CREATE TABLE simulationSummary"); conn.createStatement().execute( Queries.getQuery("create_simulationsummary")); logger.info("CREATE VIEW aggregatedSimulations"); conn.createStatement().execute( Queries.getQuery("create_aggregatedsimulations")); logger.info("CREATE TABLE aggregatePlayerScore"); conn.createStatement().execute( Queries.getQuery("create_aggregateplayerscore")); logger.info("Processing simulations..."); // prepare statements PreparedStatement aggregatePlayerScore = conn .prepareStatement(Queries .getQuery("insert_aggregateplayerscore")); PreparedStatement clusterStats = conn.prepareStatement(Queries .getQuery("select_clusters")); PreparedStatement remaining = conn.prepareStatement(Queries .getQuery("select_agentsremaining")); PreparedStatement insertSummary = conn.prepareStatement(Queries .getQuery("insert_simulationsummary")); // get subset to process ResultSet unprocessed = conn.createStatement().executeQuery( Queries.getQuery("select_unprocessedsimulations")); while (unprocessed.next()) { long id = unprocessed.getLong(1); String name = unprocessed.getString(2); int finishTime = unprocessed.getInt(3); int cutoff = (int) (Math.floor(finishTime / 2)) - 1; logger.info(id + ": " + name); // START TRANSACTION conn.setAutoCommit(false); // generate player scores per cluster aggregatePlayerScore.setLong(1, id); aggregatePlayerScore.setLong(2, id); aggregatePlayerScore.execute(); clusterStats.setLong(1, id); ResultSet clusters = clusterStats.executeQuery(); logger.debug("Cutoff: " + cutoff); while (clusters.next()) { int cluster = clusters.getInt(1); logger.debug("Cluster " + cluster); // calculate c and nc remaining int crem = 0; int ncrem = 0; remaining.setLong(1, id); remaining.setString(2, "c%"); remaining.setInt(3, cutoff); ResultSet rs = remaining.executeQuery(); if (rs.next()) { crem = rs.getInt(1); } remaining.setString(2, "nc%"); rs = remaining.executeQuery(); if (rs.next()) { ncrem = rs.getInt(1); } // insert summary insertSummary.setLong(1, id); insertSummary.setString(2, name); insertSummary.setInt(3, cluster); insertSummary.setDouble(4, clusters.getDouble(2)); insertSummary.setDouble(5, clusters.getDouble(3)); insertSummary.setDouble(6, clusters.getDouble(4)); insertSummary.setDouble(7, clusters.getDouble(5)); insertSummary.setDouble(8, clusters.getDouble(6)); insertSummary.setInt(9, crem); insertSummary.setInt(10, ncrem); insertSummary.execute(); } // COMMIT TRANSACTION conn.commit(); } } catch (SQLException e) { throw new RuntimeException(e); } finally { stopDatabase(); } }
public void summarise(String[] args) { logger.warn("This implementation assumes you are using postgresql >=9.1 with hstore, it will fail otherwise."); // get database to trigger injector creation getDatabase(); // pull JDBC connection from injector Connection conn = injector.getInstance(Connection.class); try { logger.info("Creating tables and views. "); logger.info("CREATE VIEW allocationRatios"); conn.createStatement().execute( Queries.getQuery("create_allocationratios")); logger.info("CREATE TABLE simulationSummary"); conn.createStatement().execute( Queries.getQuery("create_simulationsummary")); logger.info("CREATE VIEW aggregatedSimulations"); conn.createStatement().execute( Queries.getQuery("create_aggregatedsimulations")); logger.info("CREATE TABLE aggregatePlayerScore"); conn.createStatement().execute( Queries.getQuery("create_aggregateplayerscore")); logger.info("Processing simulations..."); // prepare statements PreparedStatement aggregatePlayerScore = conn .prepareStatement(Queries .getQuery("insert_aggregateplayerscore")); PreparedStatement clusterStats = conn.prepareStatement(Queries .getQuery("select_clusters")); PreparedStatement remaining = conn.prepareStatement(Queries .getQuery("select_agentsremaining")); PreparedStatement insertSummary = conn.prepareStatement(Queries .getQuery("insert_simulationsummary")); // get subset to process ResultSet unprocessed = conn.createStatement().executeQuery( Queries.getQuery("select_unprocessedsimulations")); while (unprocessed.next()) { long id = unprocessed.getLong(1); String name = unprocessed.getString(2); int finishTime = unprocessed.getInt(3); int cutoff = (int) (Math.floor(finishTime / 2)) - 1; logger.info(id + ": " + name); // START TRANSACTION conn.setAutoCommit(false); // generate player scores per cluster aggregatePlayerScore.setLong(1, id); aggregatePlayerScore.setLong(2, id); aggregatePlayerScore.execute(); clusterStats.setLong(1, id); ResultSet clusters = clusterStats.executeQuery(); logger.debug("Cutoff: " + cutoff); while (clusters.next()) { int cluster = clusters.getInt(1); logger.debug("Cluster " + cluster); // calculate c and nc remaining int crem = 0; int ncrem = 0; remaining.setLong(1, id); remaining.setString(2, "c%"); remaining.setInt(3, cutoff); remaining.setInt(4, cluster); ResultSet rs = remaining.executeQuery(); if (rs.next()) { crem = rs.getInt(1); } remaining.setString(2, "nc%"); rs = remaining.executeQuery(); if (rs.next()) { ncrem = rs.getInt(1); } // insert summary insertSummary.setLong(1, id); insertSummary.setString(2, name); insertSummary.setInt(3, cluster); insertSummary.setDouble(4, clusters.getDouble(2)); insertSummary.setDouble(5, clusters.getDouble(3)); insertSummary.setDouble(6, clusters.getDouble(4)); insertSummary.setDouble(7, clusters.getDouble(5)); insertSummary.setDouble(8, clusters.getDouble(6)); insertSummary.setInt(9, crem); insertSummary.setInt(10, ncrem); insertSummary.execute(); } // COMMIT TRANSACTION conn.commit(); } } catch (SQLException e) { throw new RuntimeException(e); } finally { stopDatabase(); } }
diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/framework/internal/defaultadaptor/DevClassPathHelper.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/framework/internal/defaultadaptor/DevClassPathHelper.java index be49aee8..ca2502a1 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/framework/internal/defaultadaptor/DevClassPathHelper.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/framework/internal/defaultadaptor/DevClassPathHelper.java @@ -1,103 +1,104 @@ /******************************************************************************* * Copyright (c) 2004 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.osgi.framework.internal.defaultadaptor; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.*; public class DevClassPathHelper { static protected boolean inDevelopmentMode = false; static protected String[] devDefaultClasspath; static protected Dictionary devProperties = null; static { // Check the osgi.dev property to see if dev classpath entries have been defined. String osgiDev = System.getProperty("osgi.dev"); //$NON-NLS-1$ if (osgiDev != null) { try { inDevelopmentMode = true; URL location = new URL(osgiDev); devProperties = load(location); if (devProperties != null) devDefaultClasspath = getArrayFromList((String) devProperties.get("*")); //$NON-NLS-1$ } catch (MalformedURLException e) { devDefaultClasspath = getArrayFromList(osgiDev); } } } private static String[] getDevClassPath(String id, Dictionary properties, String[] defaultClasspath) { String[] result = null; if (id != null && properties != null) { String entry = (String) properties.get(id); if (entry != null) result = getArrayFromList(entry); } if (result == null) result = defaultClasspath; return result; } public static String[] getDevClassPath(String id, Dictionary properties) { if (properties == null) return getDevClassPath(id, devProperties, devDefaultClasspath); return getDevClassPath(id, properties, getArrayFromList((String) properties.get("*"))); //$NON-NLS-1$ } public static String[] getDevClassPath(String id) { return getDevClassPath(id, null); } /** * Returns the result of converting a list of comma-separated tokens into an array * * @return the array of string tokens * @param prop the initial comma-separated string */ public static String[] getArrayFromList(String prop) { if (prop == null || prop.trim().equals("")) //$NON-NLS-1$ return new String[0]; Vector list = new Vector(); StringTokenizer tokens = new StringTokenizer(prop, ","); //$NON-NLS-1$ while (tokens.hasMoreTokens()) { String token = tokens.nextToken().trim(); if (!token.equals("")) //$NON-NLS-1$ list.addElement(token); } return list.isEmpty() ? new String[0] : (String[]) list.toArray(new String[list.size()]); } public static boolean inDevelopmentMode() { return inDevelopmentMode; } /* * Load the given properties file */ private static Properties load(URL url) { Properties props = new Properties(); try { InputStream is = null; try { is = url.openStream(); props.load(is); } finally { - is.close(); + if (is != null) + is.close(); } } catch (IOException e) { // TODO consider logging here } return props; } }
true
true
private static Properties load(URL url) { Properties props = new Properties(); try { InputStream is = null; try { is = url.openStream(); props.load(is); } finally { is.close(); } } catch (IOException e) { // TODO consider logging here } return props; }
private static Properties load(URL url) { Properties props = new Properties(); try { InputStream is = null; try { is = url.openStream(); props.load(is); } finally { if (is != null) is.close(); } } catch (IOException e) { // TODO consider logging here } return props; }
diff --git a/Servers/JavaServer/src/dbs/search/qb/QueryBuilder.java b/Servers/JavaServer/src/dbs/search/qb/QueryBuilder.java index 263190c7..49e2f663 100644 --- a/Servers/JavaServer/src/dbs/search/qb/QueryBuilder.java +++ b/Servers/JavaServer/src/dbs/search/qb/QueryBuilder.java @@ -1,1718 +1,1719 @@ package dbs.search.qb; import java.util.StringTokenizer; import java.util.ArrayList; import java.util.Vector; import java.util.List; import java.util.Iterator; import java.util.Set; import dbs.api.DBSApiDQLogic; import dbs.search.parser.Constraint; import dbs.search.graph.GraphUtil; import dbs.sql.DBSSql; import dbs.util.Validate; import edu.uci.ics.jung.graph.Vertex; import edu.uci.ics.jung.graph.Edge; public class QueryBuilder { int MAX_ITERATION = 999; KeyMap km; //RelationMap rm = new RelationMap(); private boolean upper; private ArrayList bindValues; private ArrayList bindIntValues; private List<String> listForOracleOrderInOutermostQuery; GraphUtil u = null; private String db = ""; private String countQuery = ""; public QueryBuilder(String db) { this.db = db; bindValues = new ArrayList(); bindIntValues = new ArrayList(); listForOracleOrderInOutermostQuery = new ArrayList<String>(); km = new KeyMap(); //u = GraphUtil.getInstance("/home/sekhri/DBS/Servers/JavaServer/etc/DBSSchemaGraph.xml"); u = GraphUtil.getInstance("WEB-INF/DBSSchemaGraph.xml"); upper = true; } private String owner() throws Exception { return DBSSql.owner(); } public String getCountQuery() { return countQuery; } public ArrayList getBindValues() { return bindValues; } public ArrayList getBindIntValues() { return bindIntValues; } public String genQuery(ArrayList kws, ArrayList cs, ArrayList okws) throws Exception{ return genQuery(kws, cs, okws, "", "", "", true); } private void checkMax(int iter) throws Exception { if(iter > MAX_ITERATION) throw new Exception("Unexpected query. Could not process this query"); } private void fixConstForLike(ArrayList cs) throws Exception { int iter = 0; for (int i =0 ; i!= cs.size(); ++i) { ++iter; checkMax(iter); Object obj = cs.get(i); try { Constraint co = (Constraint)obj; String key = (String)co.getKey(); String op = (String)co.getOp(); String val = (String)co.getValue(); if (key!=null) { if(isNotLike(op)) co.setOp("not like"); if((val.indexOf('%') != -1 ) || (val.indexOf('*') != -1) ) { if(Util.isSame(op, "in")) throw new Exception("Operator in CANNOT be used with values that have * or % in them"); //System.out.println("Fixing conts"); if(Util.isSame(op, "!=") || isNotLike(op)) co.setOp("not like"); else co.setOp("like"); } } } catch (ClassCastException e) { } } } private boolean isNotLike(String token) { if(token == null) return false; token = token.toLowerCase(); if(token.startsWith("not") && (token.endsWith("like"))) return true; return false; } //public String genQuery(ArrayList kws, ArrayList cs, String begin, String end) throws Exception{ public String genQuery(ArrayList kws, ArrayList cs, ArrayList okws, String orderingkw, String begin, String end, boolean upper) throws Exception{ this.upper = upper; //Store all the keywors both from select and where in allKws fixConstForLike(cs); String personJoinQuery = ""; String parentJoinQuery = ""; String childJoinQuery = ""; String blockParentJoinQuery = ""; String blockChildJoinQuery = ""; String pathParentWhereQuery = ""; String pathChildWhereQuery = ""; String groupByQuery = ""; String sumGroupByQuery = ""; String sumQuery = ""; String selectStr = "SELECT "; boolean invalidFile = false; boolean modByAdded = false; boolean createByAdded = false; boolean fileParentAdded = false; boolean fileChildAdded = false; boolean blockParentAdded = false; boolean blockChildAdded = false; boolean datasetParentAdded = false; boolean datasetChildAdded = false; boolean procDsParentAdded = false; boolean procDsChildAdded = false; boolean iLumi = isInList(kws, "ilumi"); boolean countPresent = false; boolean sumPresent = false; int iter = 0; ArrayList allKws = new ArrayList(); if(isInList(kws, "file") || isInList(kws, "file.status")) { invalidFile = true; allKws = addUniqueInList(allKws, "FileStatus"); } if(isInListRelaxed(kws, "file") && isInListRelaxed(kws, "run")) { //System.out.println("They are same ----------------------------------->"); allKws = addUniqueInList(allKws, "FileRunLumi"); } for (int i =0 ; i!= kws.size(); ++i) { ++iter; checkMax(iter); String aKw = (String)kws.get(i); if(aKw.toLowerCase().startsWith("count") || aKw.toLowerCase().endsWith("count")) countPresent = true; if(aKw.toLowerCase().startsWith("sum")) sumPresent = true; } if(sumPresent || countPresent) sumQuery += selectStr; String query = "SELECT DISTINCT \n\t"; // If requested CLOB data, such as QueryableParameterSet.Content // we should not either converted it to string data type if (isInList(kws, "config.content") ) { query = "SELECT \n\t"; } for (int i =0 ; i!= kws.size(); ++i) { ++iter; checkMax(iter); String aKw = (String)kws.get(i); if (i!=0) query += "\n\t,"; //If path supplied in select then always use block path. If supplied in where then user procDS ID if(Util.isSame(aKw, "ilumi")) { query += getIntLumiSelectQuery(); //System.out.println("line 2.1.1"); } else if(aKw.toLowerCase().startsWith("sum")) { checkMax(iter); aKw = aKw.toLowerCase(); String keyword = aKw.substring(aKw.indexOf("(") + 1, aKw.indexOf(")")); keyword = keyword.trim(); String asKeyword = keyword.replace('.', '_'); String entity = (new StringTokenizer(keyword, ".")).nextToken(); //System.out.println("entity " + entity); String realName = u.getMappedRealName(entity); allKws = addUniqueInList(allKws, realName); //if(!sumQuery.startsWith("SELECT")) sumQuery += " SELECT "; if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += "SUM(" + asKeyword + ") AS SUM_" + asKeyword + " "; //query += "SUM(" + km.getMappedValue(keyword, true) + ") AS SUM_" + keyword.replace('.', '_') ; String tmpKw = km.getMappedValue(keyword, true); query += tmpKw + " AS " + asKeyword ; if(iLumi) groupByQuery += tmpKw + ","; - String tmp = makeQueryFromDefaults(u.getMappedVertex(entity)); + /*String tmp = makeQueryFromDefaults(u.getMappedVertex(entity)); tmp = tmp.substring(0, tmp.length() - 1); // To get rid of last space query += "\n\t," + tmp + "_SUM "; + */ } else if(aKw.toLowerCase().startsWith("count")) { checkMax(iter); aKw = aKw.toLowerCase(); String entity = aKw.substring(aKw.indexOf("(") + 1, aKw.indexOf(")")); entity = entity.trim(); //System.out.println("entity = " + entity); String realName = u.getMappedRealName(entity); allKws = addUniqueInList(allKws, realName); String defaultStr = u.getDefaultFromVertex(u.getVertex(realName)); if(defaultStr.indexOf(",") != -1) throw new Exception("Cannot use count(" + entity + ")"); //query += "COUNT(DISTINCT " + realName + "." + defaultStr + ") AS COUNT"; query += realName + "." + defaultStr + " AS COUNT_SUB_" + realName; if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; //if(sumQuery.length() != 0) sumQuery += ",\n\t"; //else if(!sumQuery.startsWith("SELECT")) sumQuery += "SELECT "; sumQuery += "COUNT(DISTINCT COUNT_SUB_" + realName + ") AS COUNT_" + realName; /*if(sumPresent) { sumQuery += ",\n\t COUNT AS COUNT"; sumGroupByQuery += " COUNT ,"; }*/ } else if(Util.isSame(aKw, "dataset")) { checkMax(iter); allKws = addUniqueInList(allKws, "Block"); query += "Block.Path AS PATH"; if(iLumi) groupByQuery += "Block.Path,"; if(sumPresent || countPresent) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += " PATH AS PATH"; sumGroupByQuery += " PATH ,"; } } else { //System.out.println("line 2.2"); if(iLumi && (i < 2) ) { allKws = addUniqueInList(allKws, "Runs"); allKws = addUniqueInList(allKws, "LumiSection"); checkMax(iter); } StringTokenizer st = new StringTokenizer(aKw, "."); int count = st.countTokens(); String token = st.nextToken(); Vertex vFirst = u.getMappedVertex(token); String real = u.getRealFromVertex(vFirst); allKws = addUniqueInList(allKws, real); //System.out.println("line 4"); //if(Util.isSame(real, "LumiSection")) allKws = addUniqueInList(allKws, "Runs"); if(count == 1) { //Get default from vertex //System.out.println("line 5"); checkMax(iter); String tmp = makeQueryFromDefaults(vFirst); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(vFirst); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect; sumGroupByQuery += toSelect + ","; } } } else { //System.out.println("line 6"); checkMax(iter); boolean addQuery = true; String token2 = st.nextToken(); String tmpTableName = token + "_" + token2; /*if(Util.isSame(token2, "algo")) { allKws = addUniqueInList(allKws, "AppFamily"); allKws = addUniqueInList(allKws, "AppVersion"); allKws = addUniqueInList(allKws, "AppExecutable"); allKws = addUniqueInList(allKws, "QueryableParameterSet"); query += makeQueryFromDefaults(u.getVertex("AppFamily")); query += makeQueryFromDefaults(u.getVertex("AppVersion")); query += makeQueryFromDefaults(u.getVertex("AppExecutable")); query += makeQueryFromDefaults(u.getVertex("QueryableParameterSet")); adQuery = false; }*/ if(Util.isSame(token2, "release") || Util.isSame(token2, "tier")) { checkMax(iter); String realName = u.getMappedRealName(token2);//AppVersion allKws = addUniqueInList(allKws, realName); String tmp = makeQueryFromDefaults(u.getVertex(realName)); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(u.getVertex(realName)); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } /*if(Util.isSame(token, "release") || Util.isSame(token, "tier") ) { checkMax(iter); String realName = u.getMappedRealName(token);//AppVersion allKws = addUniqueInList(allKws, realName); String tmp = makeQueryFromDefaults(u.getVertex(realName)); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(u.getVertex(realName)); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; }*/ if(Util.isSame(token2, "count")) { checkMax(iter); String realName = u.getMappedRealName(token); String defaultStr = u.getDefaultFromVertex(u.getVertex(realName)); if(defaultStr.indexOf(",") != -1) throw new Exception("Cannot use count(" + token + ")"); query += realName + "." + defaultStr + " AS COUNT_SUB_" + realName; if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; //if(sumQuery.length() != 0) sumQuery += ",\n\t"; //else sumQuery += "SELECT "; sumQuery += "COUNT(DISTINCT COUNT_SUB_" + realName + ") AS COUNT_" + realName; /*query += "COUNT(DISTINCT " + realName + "." + defaultStr + ") AS COUNT"; if(sumPresent) { sumQuery += ",\n\t COUNT AS COUNT "; sumGroupByQuery += " COUNT ,"; }*/ addQuery = false; } if(Util.isSame(token2, "modby") || Util.isSame(token2, "createby")) { checkMax(iter); boolean dontJoin = false; String personField = "CreatedBy"; if(Util.isSame(token2, "modby")) { if(modByAdded) dontJoin = true; modByAdded = true; personField = "LastModifiedBy"; } else { if(createByAdded) dontJoin = true; createByAdded = true; } //String tmpTableName = token + "_" + token2; if(!dontJoin) { personJoinQuery += "\tJOIN " + owner() + "Person " + tmpTableName + "\n" + "\t\tON " + real + "." + personField + " = " + tmpTableName + ".ID\n"; } String fqName = tmpTableName + ".DistinguishedName"; query += fqName + makeAs(tmpTableName + "_DN"); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += tmpTableName + "_DN AS " + tmpTableName + "_DN "; sumGroupByQuery += tmpTableName + "_DN ,"; } addQuery = false; } //if(Util.isSame(token2, "evnum") && Util.isSame(token, "file")) { // throw new Exception("You can find file based on file.evnum (find file where file.evenum = blah) but cannot find file.evnum"); //} if(Util.isSame(token2, "evnum") && Util.isSame(token, "lumi")) { throw new Exception("You can find lumi based on lumi.evnum (find lumi where lumi.evenum = blah) but cannot find lumi.evnum"); } if(Util.isSame(token2, "parent") && Util.isSame(token, "file")) { checkMax(iter); boolean dontJoin = false; if(fileParentAdded) dontJoin = true; fileParentAdded = true; if(!dontJoin) parentJoinQuery += handleParent(tmpTableName, "Files", "FileParentage"); String fqName = tmpTableName + ".LogicalFileName"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "child") && Util.isSame(token, "file")) { checkMax(iter); boolean dontJoin = false; if(fileChildAdded) dontJoin = true; fileChildAdded = true; //System.out.println("childJoinQuery " + childJoinQuery+ " dontJoin " + dontJoin); if(!dontJoin) childJoinQuery += handleChild(tmpTableName, "Files", "FileParentage"); String fqName = tmpTableName + ".LogicalFileName"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "parent") && Util.isSame(token, "block")) { checkMax(iter); boolean dontJoin = false; if(blockParentAdded) dontJoin = true; blockParentAdded = true; if(!dontJoin) blockParentJoinQuery += handleParent(tmpTableName, "Block", "BlockParent"); String fqName = tmpTableName + ".Name"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "child") && Util.isSame(token, "block")) { checkMax(iter); boolean dontJoin = false; if(blockChildAdded) dontJoin = true; blockChildAdded = true; if(!dontJoin) blockChildJoinQuery += handleBlockChild(tmpTableName, "Block", "BlockParent"); String fqName = tmpTableName + ".Name"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "parent") && Util.isSame(token, "procds")) { checkMax(iter); boolean dontJoin = false; if(procDsParentAdded) dontJoin = true; procDsParentAdded = true; if(!dontJoin) parentJoinQuery += handleParent(tmpTableName, "ProcessedDataset", "ProcDSParent"); String fqName = tmpTableName + ".Name"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "child") && Util.isSame(token, "procds")) { checkMax(iter); boolean dontJoin = false; if(procDsChildAdded) dontJoin = true; procDsChildAdded = true; if(!dontJoin) parentJoinQuery += handleProcdsChild(tmpTableName, "ProcessedDataset", "ProcDSParent"); String fqName = tmpTableName + ".Name"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "parent") && Util.isSame(token, "dataset")) { //Lets have the same treatment as procds.parent checkMax(iter); allKws = addUniqueInList(allKws, "Block"); boolean dontJoin = false; if(datasetParentAdded) dontJoin = true; datasetParentAdded = true; if(!dontJoin) pathParentWhereQuery += handlePathParent(tmpTableName, "Block", "ProcDSParent"); String fqName = tmpTableName + ".Path"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } addQuery = false; } if(Util.isSame(token2, "child") && Util.isSame(token, "dataset")) { checkMax(iter); allKws = addUniqueInList(allKws, "Block"); boolean dontJoin = false; if(datasetChildAdded) dontJoin = true; datasetChildAdded = true; if(!dontJoin) pathChildWhereQuery += handlePathChild(tmpTableName, "Block", "ProcDSParent"); String fqName = tmpTableName + ".Path"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } addQuery = false; } /*if(Util.isSame(token2, "parent") && Util.isSame(token, "dataset")) { //Lets have the same treatment as procds.parent checkMax(iter); allKws = addUniqueInList(allKws, "Block"); boolean dontJoin = false; if(datasetParentAdded) dontJoin = true; datasetParentAdded = true; if(!dontJoin) pathParentWhereQuery += handlePathParent(); String fqName = "Block.Path AS Dataset_Parent"; query += fqName; if(iLumi) groupByQuery += "Block.Path ,"; if(sumPresent || countPresent) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += " Dataset_Parent AS Dataset_Parent "; sumGroupByQuery += " Dataset_Parent ,"; } addQuery = false; } if(Util.isSame(token2, "child") && Util.isSame(token, "dataset")) { //Lets have the same treatment as procds.parent checkMax(iter); allKws = addUniqueInList(allKws, "Block"); boolean dontJoin = false; if(datasetChildAdded) dontJoin = true; datasetChildAdded = true; if(!dontJoin) pathChildWhereQuery += handlePathChild(); String fqName = "Block.Path AS Dataset_Child"; query += fqName; if(iLumi) groupByQuery += "Block.Path ,"; if(sumPresent || countPresent) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += " Dataset_Child AS Dataset_Child "; sumGroupByQuery += " Dataset_Child ,"; } addQuery = false; }*/ /*if(Util.isSame(token, "dataset") && (!Util.isSame(token2, "parent"))) { checkMax(iter); allKws = addUniqueInList(allKws, "ProcessedDataset"); System.out.println("1111Adding ProcessedDataset >>>>>>>>>>>>>>>>>>>>>>"); }*/ Vertex vCombined = u.getMappedVertex(aKw); //System.out.println("\n\n---Changing vCombined " + aKw); if(vCombined == null) { //System.out.println("IT is NULLLLLLLLLLLLL"); checkMax(iter); if(addQuery) { String mapVal = km.getMappedValue(aKw, true); allKws = addUniqueInList(allKws, (new StringTokenizer(mapVal, ".")).nextToken()); //if(mapVal.equals(aKw)) throw new Exception("The keyword " + aKw + " not yet implemented in Query Builder" ); query += mapVal + makeAs(mapVal); if(iLumi) groupByQuery += mapVal + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(mapVal)); if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } } for(int ai = 0 ; ai != allKws.size() ; ++ai ) System.out.println("kw " + (String)allKws.get(ai)); } else { //System.out.println("in ELSE ---> u.getRealFromVertex " + u.getRealFromVertex(vCombined)); allKws = addUniqueInList(allKws, u.getRealFromVertex(vCombined)); checkMax(iter); if(addQuery) { checkMax(iter); String tmp = makeQueryFromDefaults(vCombined); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(vCombined); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } } for(int ai = 0 ; ai != allKws.size() ; ++ai ) System.out.println("kw else" + (String)allKws.get(ai)); } } } } checkMax(iter); if(iLumi && (cs.size() > 0) ) { allKws = addUniqueInList(allKws, "Runs"); allKws = addUniqueInList(allKws, "LumiSection"); } for (int i =0 ; i!= cs.size(); ++i) { ++iter; checkMax(iter); Object obj = cs.get(i); try { Constraint o = (Constraint)obj; String key = (String)o.getKey(); if (key!=null) { if(Util.isSame(key, "dataset")) { } else if(Util.isSame(key, "release")) { if(isInList(kws, "procds") || isInList(kws, "dataset")) allKws = addUniqueInList(allKws, "ProcAlgo"); else addUniqueInList(allKws, "FileAlgo"); } /*else if(Util.isSame(key, "tier")) { if(isInList(kws, "procds") || isInList(kws, "dataset")) allKws = addUniqueInList(allKws, "ProcDSTier"); else addUniqueInList(allKws, "FileTier"); }*/ else if(Util.isSame(key, "dq")) { allKws = addUniqueInList(allKws, km.getMappedValue(key, false)); } else if(Util.isSame(key, "pset")) { allKws = addUniqueInList(allKws, km.getMappedValue(key, false)); } else { if(Util.isSame(key, "file.status")) invalidFile = false; StringTokenizer st = new StringTokenizer(key, "."); int count = st.countTokens(); allKws = addUniqueInList(allKws, u.getMappedRealName(st.nextToken())); if(count != 1) { Vertex vCombined = u.getMappedVertex(key); if(vCombined != null) allKws = addUniqueInList(allKws, u.getRealFromVertex(vCombined)); } } /*else { //allKws = addUniqueInList(allKws, "ProcessedDataset"); allKws = addUniqueInList(allKws, "Block"); }*/ } } catch (ClassCastException e) { } } //Get the route which determines the join table if(allKws.size() > 0) allKws = makeCompleteListOfVertexs(allKws); //If File is not there then add Block //Otherwise for (int i =0 ; i!= cs.size(); ++i) { ++iter; checkMax(iter); Object obj = cs.get(i); try { Constraint o = (Constraint)obj; String key = (String)o.getKey(); if (key!=null) { if(Util.isSame(key, "dataset")) { if(!isIn(allKws, "Files")) allKws = addUniqueInList(allKws, "Block"); }else if(key.startsWith("dataset")) { allKws = addUniqueInList(allKws, "ProcessedDataset"); } } } catch (ClassCastException e) { } } if(allKws.size() > 0) { allKws = makeCompleteListOfVertexs(allKws); allKws = sortVertexs(allKws); } int len = allKws.size(); /*for(int i = 0 ; i != len ; ++i ) { System.out.println("kw " + (String)allKws.get(i)); }*/ if(isInList(kws, "ilumi")) { if(len == 0) query += getIntLumiFromQuery(); else { query += genJoins(allKws); query += getIntLumiJoinQuery(); } } else query += genJoins(allKws); query += personJoinQuery; query += parentJoinQuery; query += childJoinQuery; query += blockParentJoinQuery; query += blockChildJoinQuery; query += pathParentWhereQuery; query += pathChildWhereQuery; personJoinQuery = ""; parentJoinQuery = ""; childJoinQuery = ""; blockChildJoinQuery = ""; blockParentJoinQuery = ""; String queryWhere = ""; if (cs.size() > 0) queryWhere += "\nWHERE\n"; for (int i =0 ; i!= cs.size(); ++i) { ++iter; checkMax(iter); Object obj = cs.get(i); try { Constraint co = (Constraint)obj; String bracket = (String)co.getBracket(); String key = (String)co.getKey(); String op = (String)co.getOp(); String val = (String)co.getValue(); if (bracket!=null) { queryWhere += bracket; } if (key!=null) { if(Util.isSame(key, "dataset")) { /*if(pathParentWhereQuery.length() > 0) { queryWhere += pathParentWhereQuery + ""; bindValues.add(val); } else if(pathChildWhereQuery.length() > 0) { queryWhere += pathChildWhereQuery + ""; bindValues.add(val); }else {*/ // If path is given in where clause it should op should always be = //if(!Util.isSame(op, "=")) throw new Exception("When Path is provided operater should be = . Invalid operater given " + op); //queryWhere += "\tProcessedDataset.ID " + handlePath(val); if(isIn(allKws, "Files")) { queryWhere += "\tFiles.Block "; queryWhere += handlePath(val, op); } else { if(Util.isSame(op, "like") || Util.isSame(op, "not like")) queryWhere += "\tupper(Block.Path) "; else queryWhere += "\tBlock.Path "; queryWhere += handleOp(op, val, bindValues); } //} } else if(Util.isSame(key, "dq")) { if(!Util.isSame(op, "=")) throw new Exception("When dq is provided operator should be = . Invalid operator given " + op); queryWhere += "\tRuns.ID" + handleDQ(val, cs); } else if(Util.isSame(key, "pset")) { if(!Util.isSame(op, "=")) throw new Exception("When pset is provided operator should be = . Invalid operator given " + op); queryWhere += "\tQueryableParameterSet.Hash" + handlePset(val); } else if(Util.isSame(key, "site")) { //if(!Util.isSame(op, "=") && !Util.isSame(op, "in")) throw new Exception("When site is provided operator should be = . Invalid operator given " + op); queryWhere += "\t(StorageElement.SEName" + handleSite(val, op) + ")"; //queryWhere += "\tStorageElement.SEName" + handleSite(val, op); } else if(Util.isSame(key, "release")) { boolean useAnd = false; if(isInList(kws, "procds") || isInList(kws, "dataset")) { queryWhere += "\tProcAlgo.Algorithm " + handleRelease(op, val); useAnd = true; } else { if(useAnd) queryWhere += "\tAND\n"; queryWhere += "\tFileAlgo.Algorithm " + handleRelease(op, val); } } /*else if(Util.isSame(key, "tier")) { boolean useAnd = false; if(isInList(kws, "procds") || isInList(kws, "dataset")) { queryWhere += "\tProcDSTier.DataTier " + handleTier(op, val); useAnd = true; } else { if(useAnd) queryWhere += "\tAND\n"; queryWhere += "\tFileTier.DataTier " + handleTier(op, val); } }*/ else if(Util.isSame(key, "file.release")) { queryWhere += "\tFileAlgo.Algorithm" + handleRelease(op, val); } /*else if(Util.isSame(key, "file.tier")) { queryWhere += "\tFileTier.DataTier" + handleTier(op, val); }*/ else if(Util.isSame(key, "lumi.evnum")) { if(!Util.isSame(op, "=")) throw new Exception("When evnum is provided operator should be = . Invalid operator given " + op); queryWhere += handleEvNum(val); } else if(Util.isSame(key, "procds.release") || Util.isSame(key, "dataset.release")) { queryWhere += "\tProcAlgo.Algorithm " + handleRelease(op, val); } /*else if(Util.isSame(key, "procds.tier") || Util.isSame(key, "dataset.tier") ) { queryWhere += "\tProcDSTier.DataTier" + handleTier(op, val); }*/ else if(key.endsWith("createdate") || key.endsWith("moddate")) { queryWhere += "\t" + km.getMappedValue(key, true) + handleDate(op, val); } else { //if(key.indexOf(".") == -1) throw new Exception("In specifying constraints qualify keys with dot operater. Invalid key " + key); StringTokenizer st = new StringTokenizer(key, "."); int count = st.countTokens(); boolean doGeneric = false; if(count == 2) { String token = st.nextToken(); String token2 = st.nextToken(); String tmpTableName = token + "_" + token2; if(Util.isSame(token2, "modby") || Util.isSame(token2, "createby")) { boolean dontJoin = false; String personField = "CreatedBy"; if(Util.isSame(token2, "modby")) { if(modByAdded) dontJoin = true; personField = "LastModifiedBy"; modByAdded = true; } else { if(createByAdded) dontJoin = true; createByAdded = true; } //String tmpTableName = token + "_" + token2; if(!dontJoin) personJoinQuery += "\tJOIN " + owner() + "Person " + tmpTableName + "\n" + "\t\tON " + u.getMappedRealName(token) + "." + personField + " = " + tmpTableName + ".ID\n"; queryWhere += tmpTableName + ".DistinguishedName "; } else if(Util.isSame(token2, "parent") && Util.isSame(token, "file")) { throw new Exception("file.parent in where clause is not supported by DBSql anymore. Use file.child in find clause instead. For example find file.child where file = blah"); /*boolean dontJoin = false; if(fileParentAdded) dontJoin = true; fileParentAdded = true; if(!dontJoin) parentJoinQuery += handleParent(tmpTableName, "Files", "FileParentage"); queryWhere += tmpTableName + ".LogicalFileName "; */ } else if(Util.isSame(token2, "parent") && (Util.isSame(token, "procds") || (Util.isSame(token, "dataset")))) { throw new Exception("dataset.parent in where clause is not supported by DBSql anymore. Use dataset.child in find clause instead. For example find dataset.child where dataset = blah"); /*boolean dontJoin = false; if(procDsParentAdded) dontJoin = true; procDsParentAdded = true; //String tmpTableName = token + "_" + token2; if(!dontJoin) parentJoinQuery += handleParent(tmpTableName, "ProcessedDataset", "ProcDSParent"); queryWhere += tmpTableName + ".Name "; */ } else if(Util.isSame(token2, "child") && (Util.isSame(token, "procds") || (Util.isSame(token, "dataset")))) { throw new Exception("dataset.child in where clause is not supported by DBSql anymore. Use dataset.parent in find clause instead. For example find dataset.parent where dataset = blah"); } else if(Util.isSame(token2, "child") && Util.isSame(token, "file")) { throw new Exception("file.child in where clause is not supported by DBSql anymore. Use file.parent in find clause instead. For example find file.parent where file = blah"); /*boolean dontJoin = false; if(fileChildAdded) dontJoin = true; fileChildAdded = true; if(!dontJoin) childJoinQuery += handleChild(tmpTableName, "Files", "FileParentage"); queryWhere += tmpTableName + ".LogicalFileName "; */ } else if(Util.isSame(token2, "child") && Util.isSame(token, "block")) { throw new Exception("block.child in where clause is not supported by DBSql anymore. Use block.parent in find clause instead. For example find block.parent where block = blah"); } else if(Util.isSame(token2, "parent") && Util.isSame(token, "block")) { throw new Exception("block.parent in where clause is not supported by DBSql anymore. Use block.child in find clause instead. For example find block.child where block = blah"); } else doGeneric = true; }else doGeneric = true; if(doGeneric) { //Vertex vFirst = u.getMappedVertex(token); Vertex vCombined = u.getMappedVertex(key); if(vCombined == null) { if(Util.isSame(op, "like") || Util.isSame(op, "not like")) queryWhere += "\t " + makeUpper(km.getMappedValue(key, true)) ; else queryWhere += "\t" + km.getMappedValue(key, true) + " " ; } else { if(Util.isSame(op, "like") || Util.isSame(op, "not like")) queryWhere += "\t " + makeUpper(u.getRealFromVertex(vCombined) + "." + u.getDefaultFromVertex(vCombined)) ; else queryWhere += "\t" + u.getRealFromVertex(vCombined) + "." + u.getDefaultFromVertex(vCombined) + " "; //FIXME default can be list } } queryWhere += handleOp(op, val, bindValues); } } // end of if(key!=null) } catch (ClassCastException e) { queryWhere += "\n" + ((String)obj).toUpperCase() + "\n"; } } //System.out.println("\n\nFINAL query is \n\n" + query); String circularConst = ""; boolean useAnd = false; if((queryWhere.length() == 0) && isIn(allKws, "FileRunLumi")) circularConst = "\nWHERE "; if(isIn(allKws, "Files") && isIn(allKws, "FileRunLumi")) { if(queryWhere.length() != 0 || useAnd) circularConst += "\n\tAND "; circularConst += "FileRunLumi.Fileid = Files.ID"; useAnd = true; } if(isIn(allKws, "Runs") && isIn(allKws, "FileRunLumi")) { if(queryWhere.length() != 0 || useAnd) circularConst += "\n\tAND "; circularConst += "\n\tFileRunLumi.Run = Runs.ID"; useAnd = true; } if(isIn(allKws, "LumiSection") && isIn(allKws, "FileRunLumi")) { if(queryWhere.length() != 0 || useAnd) circularConst += "\n\tAND "; circularConst += "\n\tFileRunLumi.Lumi = LumiSection.ID"; } String invalidFileQuery = "FileStatus.Status <> ?"; String invalidConst = ""; if((queryWhere.length() == 0) && (circularConst.length() == 0) && (invalidFile)) { invalidConst = "\nWHERE " + invalidFileQuery; bindValues.add("INVALID"); } if(((queryWhere.length() != 0) || (circularConst.length() != 0)) && (invalidFile)) { invalidConst = "\nAND " + invalidFileQuery; bindValues.add("INVALID"); } query += personJoinQuery + parentJoinQuery + childJoinQuery + blockParentJoinQuery + blockChildJoinQuery + queryWhere + circularConst + invalidConst; if(groupByQuery.length() > 0) { groupByQuery = groupByQuery.substring(0, groupByQuery.length() - 1);// to get rid of extra comma query += "\n GROUP BY " + groupByQuery; } boolean orderOnce = false; for(Object o: okws){ ++iter; checkMax(iter); String orderBy = (String)o; if(!orderOnce) query += " ORDER BY "; if(orderOnce) query += ","; String orderToken = ""; if(Util.isSame(orderBy, "dataset")) orderToken = "Block.Path"; else if ((String)okws.get(0)==(String)kws.get(0) && (String)okws.get(0)==orderBy) { // if we pass order by keyword equal to first selected keyword // e.g. case of default ordering, we just need to lookup // first selected keyword from query and use it in order token int begIdx = query.indexOf("AS")+2; String[] temp = query.replace("\t"," ").replace("\n"," ").substring(begIdx, query.length()).split(" "); orderToken = temp[1]; // int endIdx = query.substring(begIdx,query.length()).indexOf(" "); // orderToken = query.substring(begIdx, endIdx); } else { Vertex vCombined = u.getMappedVertex(orderBy); if(vCombined == null) orderToken = km.getMappedValue(orderBy, true); else orderToken = u.getRealFromVertex(vCombined) + "." + u.getDefaultFromVertex(vCombined); // added by Valentin, the etc/DBSSchemaGraph.xml needs additional attribute which will provide mapping to real table.column in case of ambiguity try { String mappedName = u.getMappedFromVertex(vCombined); if (mappedName != null) { orderToken = mappedName; } } catch (Exception e) { } } query += orderToken; if (Util.isSame(orderToken, "Block.Path")) listForOracleOrderInOutermostQuery.add("PATH"); else listForOracleOrderInOutermostQuery.add(orderToken.replace('.', '_')); orderOnce = true; } if(okws.size() > 0) { if (Util.isSame(orderingkw, "asc")) query += " ASC"; else if (Util.isSame(orderingkw, "desc")) query += " DESC"; } if(sumQuery.length() != 0) { query = sumQuery + " FROM (" + query + ") sumtable "; if(sumGroupByQuery.length() > 0) { sumGroupByQuery = sumGroupByQuery.substring(0, sumGroupByQuery.length() - 1);// to get rid of extra comma query += "\n GROUP BY " + sumGroupByQuery; } } //countQuery = "SELECT COUNT(*) " + query.substring(query.indexOf("FROM")); countQuery = "SELECT COUNT(*) AS CNT FROM (" + query + ") x"; if(!begin.equals("") && !end.equals("")) { int bInt = Integer.parseInt(begin); int eInt = Integer.parseInt(end); bindIntValues.add(new Integer(bInt)); if(db.equals("mysql")) { bindIntValues.add(new Integer(eInt - bInt)); query += "\n\tLIMIT ?, ?"; } if(db.equals("oracle")) { bindIntValues.add(new Integer(eInt)); //query = "SELECT * FROM (SELECT x.*, rownum as rnum FROM (\n" + query + "\n) x) where rnum between ? and ?"; query = genOraclePageQuery(query); } } return query; } private String makeSumSelect(String tmp) { String asStr = "AS"; int asIndex = tmp.indexOf(asStr); if(asIndex != -1) { return tmp.substring(asIndex + asStr.length(), tmp.length()).trim(); } return ""; } private String makeUpper(String in) { if(upper) return " upper(" + in + ") "; return " " + in + " "; } private String makeAs(String in) { int len = in.length(); int endIndex = len; if (len > 30) endIndex = 30; return " AS " + in.replace('.', '_').substring(0, endIndex) + " "; } private String genOraclePageQuery(String query) throws Exception{ System.out.println(query); String tokenAS = "AS"; String tokenFrom = "FROM"; //String tokenDistinct = "DISTINCT"; String tokenDistinct = "SELECT"; int indexOfFrom = query.indexOf(tokenFrom); int indexOfDistinct = query.indexOf(tokenDistinct); if(indexOfFrom == -1 || indexOfDistinct == -1) return query; //System.out.println(indexOfFrom); //System.out.println(indexOfDistinct); String tmpStr = query.substring(indexOfDistinct + tokenDistinct.length(), indexOfFrom); //System.out.println("tmp str " + tmpStr); StringTokenizer st = new StringTokenizer(tmpStr, ","); int numberOfKeywords = st.countTokens(); String toReturn = "SELECT "; int iter = 0 ; for(int i = 0; i != numberOfKeywords; ++i) { ++iter; checkMax(iter); String tmpToken = st.nextToken(); int indexOfAs = tmpToken.indexOf(tokenAS); if(indexOfAs == -1) return query; String finalKeyword = tmpToken.substring(indexOfAs + tokenAS.length(), tmpToken.length()).trim(); //System.out.println("Keyword " + finalKeyword); if(i != 0) toReturn += ", "; toReturn += finalKeyword; } toReturn += " FROM (SELECT x.*, rownum as rnum FROM (\n" + query + "\n) x) where rnum between ? and ?"; boolean orderOnce = false; if (listForOracleOrderInOutermostQuery.size() > 0) { toReturn += " ORDER BY "; for(String orderToken: listForOracleOrderInOutermostQuery) { if(orderOnce) toReturn += " , "; toReturn += orderToken; orderOnce = true; } } return toReturn; } private String makeQueryFromDefaults(Vertex v) throws Exception { String realVal = u.getRealFromVertex(v); StringTokenizer st = new StringTokenizer(u.getDefaultFromVertex(v), ","); int countDefTokens = st.countTokens(); String query = ""; int iter = 0 ; for (int j = 0; j != countDefTokens; ++j) { ++iter; checkMax(iter); if(j != 0) query += ","; String token = st.nextToken(); query += realVal + "." + token + makeAs(realVal + "." + token); } return query; } private String makeGroupQueryFromDefaults(Vertex v) throws Exception { String realVal = u.getRealFromVertex(v); StringTokenizer st = new StringTokenizer(u.getDefaultFromVertex(v), ","); int countDefTokens = st.countTokens(); String query = ""; int iter = 0 ; for (int j = 0; j != countDefTokens; ++j) { ++iter; checkMax(iter); String token = st.nextToken(); query += realVal + "." + token + ","; } return query; } private String genJoins(ArrayList lKeywords) throws Exception { //ArrayList uniquePassed = new ArrayList(); int iter = 0 ; String prev = ""; String query = "\nFROM\n\t" + owner(); String firstToken = (String)lKeywords.get(0); if((Util.isSame(firstToken, "FileChildage"))) firstToken = "FileParentage" ; if((Util.isSame(firstToken, "BlockChild"))) firstToken = "BlockParent" ; if((Util.isSame(firstToken, "ProcDSChild"))) firstToken = "ProcDSParent" ; query += firstToken + "\n"; int len = lKeywords.size(); for(int i = 1 ; i != len ; ++i ) { ++iter; checkMax(iter); for(int j = (i-1) ; j != -1 ; --j ) { ++iter; checkMax(iter); String v1 = (String)lKeywords.get(i); String v2 = (String)lKeywords.get(j); //if(! (isIn(uniquePassed, v1 + "," + v2 )) && !(isIn(uniquePassed, v2 + "," + v1))) { if(u.doesEdgeExist(v1, v2)) { //System.out.println("Relation bwteen " + v1 + " and " + v2 + " is " + u.getRealtionFromVertex(v1, v2)); String tmp = u.getRealtionFromVertex(v1, v2); query += "\t"; if(Util.isSame(v1, "FileChildage")) v1 = "FileParentage"; if(Util.isSame(v1, "BlockChild")) v1 = "BlockParent"; if(Util.isSame(v1, "ProcDSChild")) v1 = "ProcDSParent"; if(Util.isSame(v1, "FileParentage") || Util.isSame(v1, "ProcDSParent") || Util.isSame(v1, "BlockParent")) query += "LEFT OUTER "; query += "JOIN " + owner() + v1 + "\n"; query += "\t\tON " + tmp + "\n"; //uniquePassed.add(v1 + "," + v2); break; } //} } } return query; } private boolean isIn(ArrayList aList, String key) throws Exception { int iter = 0 ; for (int i = 0 ; i != aList.size(); ++i) { if( ((String)(aList.get(i) )).equals(key)) return true; ++iter; checkMax(iter); } return false; } /*private String genJoins(String[] routes) { String prev = ""; String query = "\nFROM\n\t"; for(String s: routes) { if(!prev.equals("")) { //System.out.println(prev + "," + s); String tmp = rm.getMappedValue(prev + "," + s); //System.out.println(tmp); query += "\tJOIN " + s + "\n"; query += "\t\tON " + tmp + "\n"; } else query += s + "\n"; prev = s; } return query; }*/ private String handleParent(String tmpTableName, String table1, String table2) throws Exception { return ( "\tLEFT OUTER JOIN " + owner() + table1 + " " + tmpTableName + "\n" + "\t\tON " + tmpTableName + ".ID = " + table2 + ".ItsParent\n" ); } private String handleChild(String tmpTableName, String table1, String table2) throws Exception { return ( "\tLEFT OUTER JOIN " + owner() + table1 + " " + tmpTableName + "\n" + "\t\tON " + tmpTableName + ".ID = " + table2 + ".ThisFile\n" ); } private String handleProcdsChild(String tmpTableName, String table1, String table2) throws Exception { return ( "\tLEFT OUTER JOIN " + owner() + table1 + " " + tmpTableName + "\n" + "\t\tON " + tmpTableName + ".ID = " + table2 + ".ThisDataset\n" ); } private String handleBlockChild(String tmpTableName, String table1, String table2) throws Exception { return ( "\tLEFT OUTER JOIN " + owner() + table1 + " " + tmpTableName + "\n" + "\t\tON " + tmpTableName + ".ID = " + table2 + ".ThisBlock\n" ); } private String handlePathParent() throws Exception { String sql = "Block.ID in \n" + "\t(" + DBSSql.listPathParentOld() + ")\n"; return sql; } private String handlePathParent(String tmpTableName, String table1, String table2) throws Exception { String procdsTmpTableName = "proc" + tmpTableName; String sql = "\tLEFT OUTER JOIN " + owner() + "ProcessedDataset " + procdsTmpTableName + " \n" + "\t\t ON ProcDSParent.ItsParent = " + procdsTmpTableName + ".ID \n" + "\tLEFT OUTER JOIN " + owner() + table1 + " " + tmpTableName + "\n" + "\t\tON " + tmpTableName + ".Dataset = " + "" + procdsTmpTableName + ".ID \n"; // "\tWHERE bl.Path = ?\n"; return sql; } private String handlePathChild(String tmpTableName, String table1, String table2) throws Exception { String procdsTmpTableName = "proc" + tmpTableName; String sql = "\tLEFT OUTER JOIN " + owner() + "ProcessedDataset " + procdsTmpTableName + " \n" + "\t\t ON ProcDSParent.ThisDataset = " + procdsTmpTableName + ".ID \n" + "\tLEFT OUTER JOIN " + owner() + table1 + " " + tmpTableName + "\n" + "\t\tON " + tmpTableName + ".Dataset = " + "" + procdsTmpTableName + ".ID \n"; // "\tWHERE bl.Path = ?\n"; return sql; } private String handlePathChild() throws Exception { String sql = "Block.ID in \n" + "\t(" + DBSSql.listPathChild() + ")\n"; return sql; } private String handleLike(String val, List<String> bindValues) { bindValues.add(val.replace('*','%')); return "LIKE " + makeUpper("?"); } private String handleBetween(String val, List<String> bindValues) throws Exception { String token[] = val.split("and"); if(token.length != 2) throw new Exception("Invalid syntax is used for between keyword \n " + val + "\n The valid syntax exmaple is where abc between 34 and 13"); bindValues.add(token[0]); bindValues.add(token[1]); return "BETWEEN ? AND ?"; } private String handleNotLike(String val, List<String> bindValues) { bindValues.add(val.replace('*','%')); return "NOT LIKE " + makeUpper("?"); } private String handleIn(String val, List<String> bindValues) throws Exception { String query = "IN ("; StringTokenizer st = new StringTokenizer(val, ","); int count = st.countTokens(); int iter = 0 ; for(int k = 0 ; k != count ; ++k) { ++iter; checkMax(iter); if(k != 0) query += ","; //query += "'" + st.nextToken() + "'"; query += "?"; bindValues.add(st.nextToken().trim()); } query += ")"; return query; } private String handleOp(String op, String val, List<String> bindValues) throws Exception { String query = ""; if(Util.isSame(op, "in")) query += handleIn(val, bindValues); else if(Util.isSame(op, "like")) query += handleLike(val, bindValues); else if(Util.isSame(op, "not like")) query += handleNotLike(val, bindValues); else if(Util.isSame(op, "between")) query += handleBetween(val, bindValues); else { query += op + " ?\n"; bindValues.add(val); } return query; } private String handleEvNum(String val) { String query = "\tLumiSection.StartEventNumber <= ?\n" + "\t AND \n" + "\tLumiSection.EndEventNumber >= ?\n"; bindValues.add(val); bindValues.add(val); return query; } /*private String handlePath(String path) throws Exception { Validate.checkPath(path); String[] data = path.split("/"); if(data.length != 4) { throw new Exception("Invalid path " + path); } ArrayList route = new ArrayList(); route.add("PrimaryDataset"); route.add("ProcessedDataset"); String query = " IN ( \n" + "SELECT \n" + "\tProcessedDataset.ID " + genJoins(route) + "WHERE \n" + //"\tPrimaryDataset.Name = '" + data[1] + "'\n" + "\tPrimaryDataset.Name = ?\n" + "\tAND\n" + //"\tProcessedDataset.Name = '" + data[2] + "'" + "\tProcessedDataset.Name = ?" + ")"; bindValues.add(data[1]); bindValues.add(data[2]); return query; }*/ private String handleDate(String op, String val) throws Exception { if(Util.isSame(op, "in")) throw new Exception("Operator IN not supported with date. Please use =, < or >"); if(Util.isSame(op, "like") || Util.isSame(op, "not like")) throw new Exception("Operator LIKE is not supported with date. Please use =, < or >"); String query = ""; String epoch1 = String.valueOf(DateUtil.dateStr2Epoch(val) / 1000); if(Util.isSame(op, "=")) { String epoch2 = String.valueOf(DateUtil.getNextDate(val).getTime() / 1000); query += " BETWEEN ? AND ?\n"; bindValues.add(epoch1); bindValues.add(epoch2); } else { query += " " + op + " ?\n"; bindValues.add(epoch1); } return query; } private String handlePath(String path, String op) throws Exception { String query = " IN ( \n" + "SELECT \n" + "\tBlock.ID FROM " + owner() + "Block" + "\tWHERE \n" ; //"\tBlock.Path " + op + " '" + path + "'\n" + if(Util.isSame(op, "like") || Util.isSame(op, "not like")) query += "\t" + makeUpper("Block.Path"); else query += "\tBlock.Path ";// + op + " ?\n" + //")"; query += handleOp(op, path, bindValues) + ")"; return query; } private String handleDQ(String dqVal, List<?> cs) throws Exception { boolean found = false; int iter = 0; ArrayList<String> tmpBindValues = new ArrayList<String>(); StringBuffer dsQueryForDQ = new StringBuffer("SELECT Block.PATH FROM \n"); dsQueryForDQ.append(owner()); dsQueryForDQ.append("Block WHERE \n"); Object lastObj = new String(""); for (int i =0 ; i!= cs.size(); ++i) { ++iter; checkMax(iter); Object obj = cs.get(i); // if(i%2 == 0) { try { Constraint co = (Constraint)obj; String key = (String)co.getKey(); String op = (String)co.getOp(); String val = (String)co.getValue(); if (key!=null) { if(Util.isSame(key, "dataset")) { if(found) { dsQueryForDQ.append("\n"); dsQueryForDQ.append(((String)lastObj).toUpperCase()); dsQueryForDQ.append("\n"); } if(Util.isSame(op, "like") || Util.isSame(op, "not like")) dsQueryForDQ.append("\t" + makeUpper("Block.Path")); else dsQueryForDQ.append("\tBlock.Path "); dsQueryForDQ.append(handleOp(op, val, tmpBindValues)); found = true; } } } catch (ClassCastException e) { } lastObj = obj; } System.out.println("QUERY is " + dsQueryForDQ.toString()); //for (String s: tmpBindValues) System.out.println("BValue " + s); if(!found) throw new Exception("dataset is required when using dq queries. Please provide a dataset name in the query. Example query would be : find run where dq=blahblah and dataset = /prim/proc/tier"); //System.out.println("VAL is " + dqVal); //Pass in dsQueryForDQ.toString() and tmpBindValues to DBSSql.listRunsForRunLumiDQ //ArrayList sqlObj = DBSSql.listRunsForRunLumiDQ(null, dqVal); String dqQuery = ""; try { ArrayList sqlObj = (new DBSApiDQLogic(null)).listRunsForRunLumiDQ(null, dsQueryForDQ.toString(), tmpBindValues, dqVal); if(sqlObj.size() == 2) { dqQuery = (String)sqlObj.get(0); Vector bindVals = (Vector)sqlObj.get(1); iter = 0 ; for(Object s: bindVals) { ++iter; checkMax(iter); bindValues.add((String)s); } } } catch (Exception ex) { bindValues.add((String) "-1"); return (" IN ( \n ? )"); } return ( " IN ( \n" + dqQuery + ")" ); } private String handlePset(String val) throws Exception { System.out.println("VAL is " + val); CfgClient cc = new CfgClient(); List<String> hashs = cc.getPsetHash(val); String query = " IN ( \n"; int count = 0; int iter = 0 ; for (String aHash: hashs) { ++iter; checkMax(iter); //System.out.println("Hash is " + aHash); if(count != 0) query += ","; ++count; query += "?"; bindValues.add(aHash); } if(count == 0) { query += "?"; bindValues.add("HASH_NOT_RETURNED_FROM_INDEX_SERVICE"); } query += "\n)"; return query; } private String handleSite(String val, String op) throws Exception { System.out.println("VAL is " + val); String extraQuery = ""; if(Util.isSame(op, "like")) extraQuery = "\t" + makeUpper("StorageElement.SEName"); else extraQuery = "\tStorageElement.SEName "; if(Util.isSame(op, "not like")) throw new Exception("NOT LIKE is not supported with site"); String query = " IN ( \n"; if(Util.isSame(op, "!=")) query = " NOT IN ( \n"; SiteClient cc = new SiteClient(); int iter = 0 ; Vector tmpList = new Vector(); if(op.equals("in")) { extraQuery += "IN (" ; StringTokenizer st = new StringTokenizer(val, ","); int numTokens = st.countTokens(); for(int k = 0 ; k != numTokens ; ++k) { ++iter; checkMax(iter); String nextToken = st.nextToken().trim(); if(k != 0) extraQuery += ","; extraQuery += "?"; tmpList.add(nextToken); List<String> sites = cc.getSE(nextToken); int count = 0; for (String aSite: sites) { //System.out.println("Hash is " + aSite); if(k != 0 || count != 0) query += ","; ++count; query += "?"; bindValues.add(aSite); } } extraQuery += ")\n"; } else { val = val.replace('*', '%'); if(Util.isSame(op, "like")) extraQuery += " LIKE " + makeUpper("?") + "\n"; else extraQuery += " = ? \n"; tmpList.add(val); //System.out.println("-line 1 op is " + op ); List<String> sites = cc.getSE(val); if(sites.size() == 1) { bindValues.add((String)sites.get(0)); if(Util.isSame(op, "like")) query = " LIKE ? "; if(Util.isSame(op, "in")) query = " IN (?) "; if(Util.isSame(op, "=")) query = " = ? "; if(Util.isSame(op, "!=")) { query = " != ? "; return query; } query += "\n OR \n" + extraQuery; for(Object o: tmpList) bindValues.add((String)o); return query; } int count = 0; for (String aSite: sites) { ++iter; checkMax(iter); //System.out.println("Hash is " + aSite); if(count != 0) query += ","; ++count; query += "?"; bindValues.add(aSite); } /*if(count == 0) { query += "?"; bindValues.add("SITE_NOT_RETURNED_FROM_SITE_DB"); }*/ } query += "\n)"; if(Util.isSame(op, "!=")) return query; query += "\n OR \n" + extraQuery ; for(Object o: tmpList) bindValues.add((String)o); return query; } private String handleRelease(String op, String version) throws Exception { Validate.checkWord("AppVersion", version); ArrayList route = new ArrayList(); route.add("AlgorithmConfig"); route.add("AppVersion"); String query = " IN ( \n" + "SELECT \n" + "\tAlgorithmConfig.ID " + genJoins(route) + "WHERE \n" + //"\tAppVersion.Version = '" + version + "'\n" + "\tAppVersion.Version " + handleOp(op, version, bindValues) + "\n" + ")"; return query; } private String handleTier(String op, String tier) throws Exception { Validate.checkWord("DataTier", tier); ArrayList route = new ArrayList(); String query = " IN ( \n" + "SELECT \n" + "\tDataTier.ID FROM " + owner() + "DataTier " + "WHERE \n" + "\tDataTier.Name " + handleOp(op, tier, bindValues) + "\n" + ")"; return query; } private ArrayList addUniqueInList(ArrayList keyWords, String aKw) { for(Object kw: keyWords) { if(((String)kw).equals(aKw))return keyWords; } keyWords.add(aKw); return keyWords; } private boolean isInList(ArrayList keyWords, String aKw) { //System.out.println("line 3.1"); for(Object kw: keyWords) { if(((String)kw).equals(aKw))return true; } return false; } private boolean isInListRelaxed(ArrayList keyWords, String aKw) { for(Object kw: keyWords) { if( ((String)kw).indexOf(aKw) != -1 ) return true; } return false; } private String getIntLumiSelectQuery() { return ("\n\tSUM(ldblsum.INSTANT_LUMI * 93 * (1 - ldblsum.DEADTIME_NORMALIZATION) * ldblsum.NORMALIZATION) AS INTEGRATED_LUMINOSITY, " + "\n\tSUM(ldblsum.INSTANT_LUMI_ERR * ldblsum.INSTANT_LUMI_ERR) AS INTEGRATED_ERROR"); } private String getIntLumiFromQuery() { return ("\n\tFROM CMS_LUMI_PROD_OFFLINE.LUMI_SUMMARIES ldblsum" + "\n\tJOIN CMS_LUMI_PROD_OFFLINE.LUMI_SECTIONS ldbls" + "\n\t\tON ldblsum.SECTION_ID = ldbls.SECTION_ID" + "\n\tJOIN CMS_LUMI_PROD_OFFLINE.LUMI_VERSION_TAG_MAPS ldblvtm" + "\n\t\tON ldblvtm.LUMI_SUMMARY_ID = ldblsum.LUMI_SUMMARY_ID" + "\n\tJOIN CMS_LUMI_PROD_OFFLINE.LUMI_TAGS ldblt" + "\n\t\tON ldblt.LUMI_TAG_ID = ldblvtm.LUMI_TAG_ID"); } private String getIntLumiJoinQuery() { return ("\n\tJOIN CMS_LUMI_PROD_OFFLINE.LUMI_SECTIONS ldbls" + "\n\t\tON Runs.RunNumber = ldbls.RUN_NUMBER" + "\n\t\tAND LumiSection.LumiSectionNumber = ldbls.LUMI_SECTION_NUMBER" + "\n\tJOIN CMS_LUMI_PROD_OFFLINE.LUMI_SUMMARIES ldblsum" + "\n\t\tON ldblsum.SECTION_ID = ldbls.SECTION_ID" + "\n\tJOIN CMS_LUMI_PROD_OFFLINE.LUMI_VERSION_TAG_MAPS ldblvtm" + "\n\t\tON ldblvtm.LUMI_SUMMARY_ID = ldblsum.LUMI_SUMMARY_ID" + "\n\tJOIN CMS_LUMI_PROD_OFFLINE.LUMI_TAGS ldblt" + "\n\t\tON ldblt.LUMI_TAG_ID = ldblvtm.LUMI_TAG_ID"); } /*private ArrayList makeCompleteListOfVertexsOld(ArrayList lKeywords) throws Exception { int len = lKeywords.size(); if(len <= 1) return lKeywords; for(int i = 0 ; i != len ; ++i ) { boolean isEdge = false; for(int j = 0 ; j != len ; ++j ) { if(i != j) { //System.out.println("Checking " + lKeywords.get(i) + " with " + lKeywords.get(j) ); if(u.doesEdgeExist((String)lKeywords.get(i), (String)lKeywords.get(j))) { isEdge = true; break; } } } if(!isEdge) { //System.out.println("Shoertest edge in " + (String)lKeywords.get(i) + " --- " + (String)lKeywords.get((i+1)%len)); List<Edge> lEdges = u.getShortestPath((String)lKeywords.get(i), (String)lKeywords.get((i+1)%len)); for (Edge e: lEdges) { //System.out.println("PATH " + u.getFirstNameFromEdge(e) + " --- " + u.getSecondNameFromEdge(e)); lKeywords = addUniqueInList(lKeywords, u.getFirstNameFromEdge(e)); lKeywords = addUniqueInList(lKeywords, u.getSecondNameFromEdge(e)); } //System.out.println("No edge callin again ---------> \n"); lKeywords = makeCompleteListOfVertexs (lKeywords); return lKeywords; } } return lKeywords; }*/ private ArrayList makeCompleteListOfVertexs(ArrayList lKeywords) throws Exception { ArrayList myRoute = new ArrayList(); myRoute.add(lKeywords.get(0)); lKeywords.remove(0); int len = lKeywords.size(); int prevLen = 0; int iter = 0; while(len != 0) { ++iter; checkMax(iter); boolean breakFree = false; for(int i = 0 ; i != len ; ++i ) { ++iter; checkMax(iter); int lenRount = myRoute.size(); for(int j = 0 ; j != lenRount ; ++j ) { ++iter; checkMax(iter); String keyInMyRoute = (String)myRoute.get(j); String keyInArray = (String)lKeywords.get(i); if(keyInArray.equals(keyInMyRoute)) { lKeywords.remove(i); breakFree = true; break; } else if(u.doesEdgeExist(keyInMyRoute, keyInArray)) { myRoute = addUniqueInList(myRoute, keyInArray); lKeywords.remove(i); breakFree = true; break; } } if(breakFree) break; } if(prevLen == len) { //System.out.println("Shortest edge in " + (String)lKeywords.get(0) + " --- " + (String)myRoute.get(0)); List<Edge> lEdges = u.getShortestPath((String)lKeywords.get(0), (String)myRoute.get(0)); for (Edge e: lEdges) { //System.out.println("PATH " + u.getFirstNameFromEdge(e) + " --- " + u.getSecondNameFromEdge(e)); myRoute = addUniqueInList(myRoute, u.getFirstNameFromEdge(e)); myRoute = addUniqueInList(myRoute, u.getSecondNameFromEdge(e)); ++iter; checkMax(iter); } if(lEdges.size() > 0) lKeywords.remove(0); else { myRoute = addUniqueInList(myRoute, (String)lKeywords.get(0)); lKeywords.remove(0); ////System.out.println("Path length is 0"); } } prevLen = len; len = lKeywords.size(); } return myRoute; } public ArrayList sortVertexs(ArrayList lKeywords) throws Exception { //System.out.println("INSIDE sortVertexs"); int len = lKeywords.size(); String leaf = ""; int iter = 0; for(int i = 0 ; i != len ; ++i ) { ++iter; checkMax(iter); String aVertex = (String)lKeywords.get(i); if(isLeaf(aVertex, lKeywords)) { leaf = aVertex; break; } } //System.out.println("leaf " + leaf); if(leaf.equals("")) leaf = (String)lKeywords.get(0); //System.out.println("leaf again " + leaf); ArrayList toReturn = new ArrayList(); toReturn.add(leaf); int reps = -1; while( toReturn.size() != len) { ++reps; ++iter; checkMax(iter); for(int j = 0 ; j != len ; ++j ) { ++iter; checkMax(iter); String aVertex = (String)lKeywords.get(j); if(!aVertex.equals(leaf)) { if(!isIn(toReturn, aVertex)) { if(isLeaf(aVertex, lKeywords)) { //System.out.println(aVertex + " is a leaf toreturn size " + toReturn.size() + " len -1 " + (len - 1)); //if(toReturn.size() ==1) System.out.println("toReturn.0 " + (String)toReturn.get(0)); if(toReturn.size() == (len - 1)) toReturn = addUniqueInList(toReturn, aVertex); else if(reps > len) { toReturn = addUniqueInList(toReturn, aVertex); //System.out.println("adding " + aVertex); } } else { for (int k = (toReturn.size() - 1) ; k != -1 ; --k) { ++iter; checkMax(iter); //System.out.println("Cheking edge between " + (String)toReturn.get(k) + " and " + aVertex); if(u.doesEdgeExist((String)toReturn.get(k), aVertex)) { toReturn = addUniqueInList(toReturn, aVertex); break; } else { if(reps > len) toReturn = addUniqueInList(toReturn, aVertex); //System.out.println("no edge between " + (String)toReturn.get(k) + " and " + aVertex); } } } } } } } return toReturn; } private boolean isLeaf(String aVertex, ArrayList lKeyword) throws Exception { int count = 0; Set s = u.getVertex(aVertex).getNeighbors(); int iter = 0; for (Iterator eIt = s.iterator(); eIt.hasNext(); ) { ++iter; checkMax(iter); String neighbor = u.getRealFromVertex((Vertex) eIt.next()); //System.out.println("neighbour " + neighbor); if(isIn(lKeyword, neighbor)) ++count; } if(count == 1) return true; return false; } public static void main(String args[]) throws Exception{ QueryBuilder qb = new QueryBuilder("oracle"); ArrayList tmp = new ArrayList(); /*GraphUtil u = GraphUtil.getInstance("/home/sekhri/DBS/Servers/JavaServer/etc/DBSSchemaGraph.xml"); List<Edge> lEdges = u.getShortestPath("ProcessedDataset", "LumiSection"); for (Edge e: lEdges) { System.out.println("PATH " + u.getFirstNameFromEdge(e) + " --- " + u.getSecondNameFromEdge(e)); }*/ //tmp.add("PrimaryDataset"); tmp.add("file"); System.out.println(qb.genQuery(tmp, new ArrayList(),new ArrayList(),"", "4", "10", true)); //tmp.add("Runs"); //tmp.add("FileRunLumi"); //tmp.add("ProcessedDataset"); //tmp.add("FileType"); //tmp.add("ProcDSRuns"); /*tmp = qb.sortVertexs(tmp); //tmp = qb.makeCompleteListOfVertexs(tmp); for (int i =0 ; i!=tmp.size() ;++i ) { System.out.println("ID " + tmp.get(i)); }*/ } }
false
true
public String genQuery(ArrayList kws, ArrayList cs, ArrayList okws, String orderingkw, String begin, String end, boolean upper) throws Exception{ this.upper = upper; //Store all the keywors both from select and where in allKws fixConstForLike(cs); String personJoinQuery = ""; String parentJoinQuery = ""; String childJoinQuery = ""; String blockParentJoinQuery = ""; String blockChildJoinQuery = ""; String pathParentWhereQuery = ""; String pathChildWhereQuery = ""; String groupByQuery = ""; String sumGroupByQuery = ""; String sumQuery = ""; String selectStr = "SELECT "; boolean invalidFile = false; boolean modByAdded = false; boolean createByAdded = false; boolean fileParentAdded = false; boolean fileChildAdded = false; boolean blockParentAdded = false; boolean blockChildAdded = false; boolean datasetParentAdded = false; boolean datasetChildAdded = false; boolean procDsParentAdded = false; boolean procDsChildAdded = false; boolean iLumi = isInList(kws, "ilumi"); boolean countPresent = false; boolean sumPresent = false; int iter = 0; ArrayList allKws = new ArrayList(); if(isInList(kws, "file") || isInList(kws, "file.status")) { invalidFile = true; allKws = addUniqueInList(allKws, "FileStatus"); } if(isInListRelaxed(kws, "file") && isInListRelaxed(kws, "run")) { //System.out.println("They are same ----------------------------------->"); allKws = addUniqueInList(allKws, "FileRunLumi"); } for (int i =0 ; i!= kws.size(); ++i) { ++iter; checkMax(iter); String aKw = (String)kws.get(i); if(aKw.toLowerCase().startsWith("count") || aKw.toLowerCase().endsWith("count")) countPresent = true; if(aKw.toLowerCase().startsWith("sum")) sumPresent = true; } if(sumPresent || countPresent) sumQuery += selectStr; String query = "SELECT DISTINCT \n\t"; // If requested CLOB data, such as QueryableParameterSet.Content // we should not either converted it to string data type if (isInList(kws, "config.content") ) { query = "SELECT \n\t"; } for (int i =0 ; i!= kws.size(); ++i) { ++iter; checkMax(iter); String aKw = (String)kws.get(i); if (i!=0) query += "\n\t,"; //If path supplied in select then always use block path. If supplied in where then user procDS ID if(Util.isSame(aKw, "ilumi")) { query += getIntLumiSelectQuery(); //System.out.println("line 2.1.1"); } else if(aKw.toLowerCase().startsWith("sum")) { checkMax(iter); aKw = aKw.toLowerCase(); String keyword = aKw.substring(aKw.indexOf("(") + 1, aKw.indexOf(")")); keyword = keyword.trim(); String asKeyword = keyword.replace('.', '_'); String entity = (new StringTokenizer(keyword, ".")).nextToken(); //System.out.println("entity " + entity); String realName = u.getMappedRealName(entity); allKws = addUniqueInList(allKws, realName); //if(!sumQuery.startsWith("SELECT")) sumQuery += " SELECT "; if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += "SUM(" + asKeyword + ") AS SUM_" + asKeyword + " "; //query += "SUM(" + km.getMappedValue(keyword, true) + ") AS SUM_" + keyword.replace('.', '_') ; String tmpKw = km.getMappedValue(keyword, true); query += tmpKw + " AS " + asKeyword ; if(iLumi) groupByQuery += tmpKw + ","; String tmp = makeQueryFromDefaults(u.getMappedVertex(entity)); tmp = tmp.substring(0, tmp.length() - 1); // To get rid of last space query += "\n\t," + tmp + "_SUM "; } else if(aKw.toLowerCase().startsWith("count")) { checkMax(iter); aKw = aKw.toLowerCase(); String entity = aKw.substring(aKw.indexOf("(") + 1, aKw.indexOf(")")); entity = entity.trim(); //System.out.println("entity = " + entity); String realName = u.getMappedRealName(entity); allKws = addUniqueInList(allKws, realName); String defaultStr = u.getDefaultFromVertex(u.getVertex(realName)); if(defaultStr.indexOf(",") != -1) throw new Exception("Cannot use count(" + entity + ")"); //query += "COUNT(DISTINCT " + realName + "." + defaultStr + ") AS COUNT"; query += realName + "." + defaultStr + " AS COUNT_SUB_" + realName; if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; //if(sumQuery.length() != 0) sumQuery += ",\n\t"; //else if(!sumQuery.startsWith("SELECT")) sumQuery += "SELECT "; sumQuery += "COUNT(DISTINCT COUNT_SUB_" + realName + ") AS COUNT_" + realName; /*if(sumPresent) { sumQuery += ",\n\t COUNT AS COUNT"; sumGroupByQuery += " COUNT ,"; }*/ } else if(Util.isSame(aKw, "dataset")) { checkMax(iter); allKws = addUniqueInList(allKws, "Block"); query += "Block.Path AS PATH"; if(iLumi) groupByQuery += "Block.Path,"; if(sumPresent || countPresent) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += " PATH AS PATH"; sumGroupByQuery += " PATH ,"; } } else { //System.out.println("line 2.2"); if(iLumi && (i < 2) ) { allKws = addUniqueInList(allKws, "Runs"); allKws = addUniqueInList(allKws, "LumiSection"); checkMax(iter); } StringTokenizer st = new StringTokenizer(aKw, "."); int count = st.countTokens(); String token = st.nextToken(); Vertex vFirst = u.getMappedVertex(token); String real = u.getRealFromVertex(vFirst); allKws = addUniqueInList(allKws, real); //System.out.println("line 4"); //if(Util.isSame(real, "LumiSection")) allKws = addUniqueInList(allKws, "Runs"); if(count == 1) { //Get default from vertex //System.out.println("line 5"); checkMax(iter); String tmp = makeQueryFromDefaults(vFirst); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(vFirst); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect; sumGroupByQuery += toSelect + ","; } } } else { //System.out.println("line 6"); checkMax(iter); boolean addQuery = true; String token2 = st.nextToken(); String tmpTableName = token + "_" + token2; /*if(Util.isSame(token2, "algo")) { allKws = addUniqueInList(allKws, "AppFamily"); allKws = addUniqueInList(allKws, "AppVersion"); allKws = addUniqueInList(allKws, "AppExecutable"); allKws = addUniqueInList(allKws, "QueryableParameterSet"); query += makeQueryFromDefaults(u.getVertex("AppFamily")); query += makeQueryFromDefaults(u.getVertex("AppVersion")); query += makeQueryFromDefaults(u.getVertex("AppExecutable")); query += makeQueryFromDefaults(u.getVertex("QueryableParameterSet")); adQuery = false; }*/ if(Util.isSame(token2, "release") || Util.isSame(token2, "tier")) { checkMax(iter); String realName = u.getMappedRealName(token2);//AppVersion allKws = addUniqueInList(allKws, realName); String tmp = makeQueryFromDefaults(u.getVertex(realName)); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(u.getVertex(realName)); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } /*if(Util.isSame(token, "release") || Util.isSame(token, "tier") ) { checkMax(iter); String realName = u.getMappedRealName(token);//AppVersion allKws = addUniqueInList(allKws, realName); String tmp = makeQueryFromDefaults(u.getVertex(realName)); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(u.getVertex(realName)); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; }*/ if(Util.isSame(token2, "count")) { checkMax(iter); String realName = u.getMappedRealName(token); String defaultStr = u.getDefaultFromVertex(u.getVertex(realName)); if(defaultStr.indexOf(",") != -1) throw new Exception("Cannot use count(" + token + ")"); query += realName + "." + defaultStr + " AS COUNT_SUB_" + realName; if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; //if(sumQuery.length() != 0) sumQuery += ",\n\t"; //else sumQuery += "SELECT "; sumQuery += "COUNT(DISTINCT COUNT_SUB_" + realName + ") AS COUNT_" + realName; /*query += "COUNT(DISTINCT " + realName + "." + defaultStr + ") AS COUNT"; if(sumPresent) { sumQuery += ",\n\t COUNT AS COUNT "; sumGroupByQuery += " COUNT ,"; }*/ addQuery = false; } if(Util.isSame(token2, "modby") || Util.isSame(token2, "createby")) { checkMax(iter); boolean dontJoin = false; String personField = "CreatedBy"; if(Util.isSame(token2, "modby")) { if(modByAdded) dontJoin = true; modByAdded = true; personField = "LastModifiedBy"; } else { if(createByAdded) dontJoin = true; createByAdded = true; } //String tmpTableName = token + "_" + token2; if(!dontJoin) { personJoinQuery += "\tJOIN " + owner() + "Person " + tmpTableName + "\n" + "\t\tON " + real + "." + personField + " = " + tmpTableName + ".ID\n"; } String fqName = tmpTableName + ".DistinguishedName"; query += fqName + makeAs(tmpTableName + "_DN"); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += tmpTableName + "_DN AS " + tmpTableName + "_DN "; sumGroupByQuery += tmpTableName + "_DN ,"; } addQuery = false; } //if(Util.isSame(token2, "evnum") && Util.isSame(token, "file")) { // throw new Exception("You can find file based on file.evnum (find file where file.evenum = blah) but cannot find file.evnum"); //} if(Util.isSame(token2, "evnum") && Util.isSame(token, "lumi")) { throw new Exception("You can find lumi based on lumi.evnum (find lumi where lumi.evenum = blah) but cannot find lumi.evnum"); } if(Util.isSame(token2, "parent") && Util.isSame(token, "file")) { checkMax(iter); boolean dontJoin = false; if(fileParentAdded) dontJoin = true; fileParentAdded = true; if(!dontJoin) parentJoinQuery += handleParent(tmpTableName, "Files", "FileParentage"); String fqName = tmpTableName + ".LogicalFileName"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "child") && Util.isSame(token, "file")) { checkMax(iter); boolean dontJoin = false; if(fileChildAdded) dontJoin = true; fileChildAdded = true; //System.out.println("childJoinQuery " + childJoinQuery+ " dontJoin " + dontJoin); if(!dontJoin) childJoinQuery += handleChild(tmpTableName, "Files", "FileParentage"); String fqName = tmpTableName + ".LogicalFileName"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "parent") && Util.isSame(token, "block")) { checkMax(iter); boolean dontJoin = false; if(blockParentAdded) dontJoin = true; blockParentAdded = true; if(!dontJoin) blockParentJoinQuery += handleParent(tmpTableName, "Block", "BlockParent"); String fqName = tmpTableName + ".Name"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "child") && Util.isSame(token, "block")) { checkMax(iter); boolean dontJoin = false; if(blockChildAdded) dontJoin = true; blockChildAdded = true; if(!dontJoin) blockChildJoinQuery += handleBlockChild(tmpTableName, "Block", "BlockParent"); String fqName = tmpTableName + ".Name"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "parent") && Util.isSame(token, "procds")) { checkMax(iter); boolean dontJoin = false; if(procDsParentAdded) dontJoin = true; procDsParentAdded = true; if(!dontJoin) parentJoinQuery += handleParent(tmpTableName, "ProcessedDataset", "ProcDSParent"); String fqName = tmpTableName + ".Name"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "child") && Util.isSame(token, "procds")) { checkMax(iter); boolean dontJoin = false; if(procDsChildAdded) dontJoin = true; procDsChildAdded = true; if(!dontJoin) parentJoinQuery += handleProcdsChild(tmpTableName, "ProcessedDataset", "ProcDSParent"); String fqName = tmpTableName + ".Name"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "parent") && Util.isSame(token, "dataset")) { //Lets have the same treatment as procds.parent checkMax(iter); allKws = addUniqueInList(allKws, "Block"); boolean dontJoin = false; if(datasetParentAdded) dontJoin = true; datasetParentAdded = true; if(!dontJoin) pathParentWhereQuery += handlePathParent(tmpTableName, "Block", "ProcDSParent"); String fqName = tmpTableName + ".Path"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } addQuery = false; } if(Util.isSame(token2, "child") && Util.isSame(token, "dataset")) { checkMax(iter); allKws = addUniqueInList(allKws, "Block"); boolean dontJoin = false; if(datasetChildAdded) dontJoin = true; datasetChildAdded = true; if(!dontJoin) pathChildWhereQuery += handlePathChild(tmpTableName, "Block", "ProcDSParent"); String fqName = tmpTableName + ".Path"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } addQuery = false; } /*if(Util.isSame(token2, "parent") && Util.isSame(token, "dataset")) { //Lets have the same treatment as procds.parent checkMax(iter); allKws = addUniqueInList(allKws, "Block"); boolean dontJoin = false; if(datasetParentAdded) dontJoin = true; datasetParentAdded = true; if(!dontJoin) pathParentWhereQuery += handlePathParent(); String fqName = "Block.Path AS Dataset_Parent"; query += fqName; if(iLumi) groupByQuery += "Block.Path ,"; if(sumPresent || countPresent) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += " Dataset_Parent AS Dataset_Parent "; sumGroupByQuery += " Dataset_Parent ,"; } addQuery = false; }
public String genQuery(ArrayList kws, ArrayList cs, ArrayList okws, String orderingkw, String begin, String end, boolean upper) throws Exception{ this.upper = upper; //Store all the keywors both from select and where in allKws fixConstForLike(cs); String personJoinQuery = ""; String parentJoinQuery = ""; String childJoinQuery = ""; String blockParentJoinQuery = ""; String blockChildJoinQuery = ""; String pathParentWhereQuery = ""; String pathChildWhereQuery = ""; String groupByQuery = ""; String sumGroupByQuery = ""; String sumQuery = ""; String selectStr = "SELECT "; boolean invalidFile = false; boolean modByAdded = false; boolean createByAdded = false; boolean fileParentAdded = false; boolean fileChildAdded = false; boolean blockParentAdded = false; boolean blockChildAdded = false; boolean datasetParentAdded = false; boolean datasetChildAdded = false; boolean procDsParentAdded = false; boolean procDsChildAdded = false; boolean iLumi = isInList(kws, "ilumi"); boolean countPresent = false; boolean sumPresent = false; int iter = 0; ArrayList allKws = new ArrayList(); if(isInList(kws, "file") || isInList(kws, "file.status")) { invalidFile = true; allKws = addUniqueInList(allKws, "FileStatus"); } if(isInListRelaxed(kws, "file") && isInListRelaxed(kws, "run")) { //System.out.println("They are same ----------------------------------->"); allKws = addUniqueInList(allKws, "FileRunLumi"); } for (int i =0 ; i!= kws.size(); ++i) { ++iter; checkMax(iter); String aKw = (String)kws.get(i); if(aKw.toLowerCase().startsWith("count") || aKw.toLowerCase().endsWith("count")) countPresent = true; if(aKw.toLowerCase().startsWith("sum")) sumPresent = true; } if(sumPresent || countPresent) sumQuery += selectStr; String query = "SELECT DISTINCT \n\t"; // If requested CLOB data, such as QueryableParameterSet.Content // we should not either converted it to string data type if (isInList(kws, "config.content") ) { query = "SELECT \n\t"; } for (int i =0 ; i!= kws.size(); ++i) { ++iter; checkMax(iter); String aKw = (String)kws.get(i); if (i!=0) query += "\n\t,"; //If path supplied in select then always use block path. If supplied in where then user procDS ID if(Util.isSame(aKw, "ilumi")) { query += getIntLumiSelectQuery(); //System.out.println("line 2.1.1"); } else if(aKw.toLowerCase().startsWith("sum")) { checkMax(iter); aKw = aKw.toLowerCase(); String keyword = aKw.substring(aKw.indexOf("(") + 1, aKw.indexOf(")")); keyword = keyword.trim(); String asKeyword = keyword.replace('.', '_'); String entity = (new StringTokenizer(keyword, ".")).nextToken(); //System.out.println("entity " + entity); String realName = u.getMappedRealName(entity); allKws = addUniqueInList(allKws, realName); //if(!sumQuery.startsWith("SELECT")) sumQuery += " SELECT "; if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += "SUM(" + asKeyword + ") AS SUM_" + asKeyword + " "; //query += "SUM(" + km.getMappedValue(keyword, true) + ") AS SUM_" + keyword.replace('.', '_') ; String tmpKw = km.getMappedValue(keyword, true); query += tmpKw + " AS " + asKeyword ; if(iLumi) groupByQuery += tmpKw + ","; /*String tmp = makeQueryFromDefaults(u.getMappedVertex(entity)); tmp = tmp.substring(0, tmp.length() - 1); // To get rid of last space query += "\n\t," + tmp + "_SUM "; */ } else if(aKw.toLowerCase().startsWith("count")) { checkMax(iter); aKw = aKw.toLowerCase(); String entity = aKw.substring(aKw.indexOf("(") + 1, aKw.indexOf(")")); entity = entity.trim(); //System.out.println("entity = " + entity); String realName = u.getMappedRealName(entity); allKws = addUniqueInList(allKws, realName); String defaultStr = u.getDefaultFromVertex(u.getVertex(realName)); if(defaultStr.indexOf(",") != -1) throw new Exception("Cannot use count(" + entity + ")"); //query += "COUNT(DISTINCT " + realName + "." + defaultStr + ") AS COUNT"; query += realName + "." + defaultStr + " AS COUNT_SUB_" + realName; if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; //if(sumQuery.length() != 0) sumQuery += ",\n\t"; //else if(!sumQuery.startsWith("SELECT")) sumQuery += "SELECT "; sumQuery += "COUNT(DISTINCT COUNT_SUB_" + realName + ") AS COUNT_" + realName; /*if(sumPresent) { sumQuery += ",\n\t COUNT AS COUNT"; sumGroupByQuery += " COUNT ,"; }*/ } else if(Util.isSame(aKw, "dataset")) { checkMax(iter); allKws = addUniqueInList(allKws, "Block"); query += "Block.Path AS PATH"; if(iLumi) groupByQuery += "Block.Path,"; if(sumPresent || countPresent) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += " PATH AS PATH"; sumGroupByQuery += " PATH ,"; } } else { //System.out.println("line 2.2"); if(iLumi && (i < 2) ) { allKws = addUniqueInList(allKws, "Runs"); allKws = addUniqueInList(allKws, "LumiSection"); checkMax(iter); } StringTokenizer st = new StringTokenizer(aKw, "."); int count = st.countTokens(); String token = st.nextToken(); Vertex vFirst = u.getMappedVertex(token); String real = u.getRealFromVertex(vFirst); allKws = addUniqueInList(allKws, real); //System.out.println("line 4"); //if(Util.isSame(real, "LumiSection")) allKws = addUniqueInList(allKws, "Runs"); if(count == 1) { //Get default from vertex //System.out.println("line 5"); checkMax(iter); String tmp = makeQueryFromDefaults(vFirst); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(vFirst); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect; sumGroupByQuery += toSelect + ","; } } } else { //System.out.println("line 6"); checkMax(iter); boolean addQuery = true; String token2 = st.nextToken(); String tmpTableName = token + "_" + token2; /*if(Util.isSame(token2, "algo")) { allKws = addUniqueInList(allKws, "AppFamily"); allKws = addUniqueInList(allKws, "AppVersion"); allKws = addUniqueInList(allKws, "AppExecutable"); allKws = addUniqueInList(allKws, "QueryableParameterSet"); query += makeQueryFromDefaults(u.getVertex("AppFamily")); query += makeQueryFromDefaults(u.getVertex("AppVersion")); query += makeQueryFromDefaults(u.getVertex("AppExecutable")); query += makeQueryFromDefaults(u.getVertex("QueryableParameterSet")); adQuery = false; }*/ if(Util.isSame(token2, "release") || Util.isSame(token2, "tier")) { checkMax(iter); String realName = u.getMappedRealName(token2);//AppVersion allKws = addUniqueInList(allKws, realName); String tmp = makeQueryFromDefaults(u.getVertex(realName)); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(u.getVertex(realName)); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } /*if(Util.isSame(token, "release") || Util.isSame(token, "tier") ) { checkMax(iter); String realName = u.getMappedRealName(token);//AppVersion allKws = addUniqueInList(allKws, realName); String tmp = makeQueryFromDefaults(u.getVertex(realName)); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(u.getVertex(realName)); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; }*/ if(Util.isSame(token2, "count")) { checkMax(iter); String realName = u.getMappedRealName(token); String defaultStr = u.getDefaultFromVertex(u.getVertex(realName)); if(defaultStr.indexOf(",") != -1) throw new Exception("Cannot use count(" + token + ")"); query += realName + "." + defaultStr + " AS COUNT_SUB_" + realName; if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; //if(sumQuery.length() != 0) sumQuery += ",\n\t"; //else sumQuery += "SELECT "; sumQuery += "COUNT(DISTINCT COUNT_SUB_" + realName + ") AS COUNT_" + realName; /*query += "COUNT(DISTINCT " + realName + "." + defaultStr + ") AS COUNT"; if(sumPresent) { sumQuery += ",\n\t COUNT AS COUNT "; sumGroupByQuery += " COUNT ,"; }*/ addQuery = false; } if(Util.isSame(token2, "modby") || Util.isSame(token2, "createby")) { checkMax(iter); boolean dontJoin = false; String personField = "CreatedBy"; if(Util.isSame(token2, "modby")) { if(modByAdded) dontJoin = true; modByAdded = true; personField = "LastModifiedBy"; } else { if(createByAdded) dontJoin = true; createByAdded = true; } //String tmpTableName = token + "_" + token2; if(!dontJoin) { personJoinQuery += "\tJOIN " + owner() + "Person " + tmpTableName + "\n" + "\t\tON " + real + "." + personField + " = " + tmpTableName + ".ID\n"; } String fqName = tmpTableName + ".DistinguishedName"; query += fqName + makeAs(tmpTableName + "_DN"); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += tmpTableName + "_DN AS " + tmpTableName + "_DN "; sumGroupByQuery += tmpTableName + "_DN ,"; } addQuery = false; } //if(Util.isSame(token2, "evnum") && Util.isSame(token, "file")) { // throw new Exception("You can find file based on file.evnum (find file where file.evenum = blah) but cannot find file.evnum"); //} if(Util.isSame(token2, "evnum") && Util.isSame(token, "lumi")) { throw new Exception("You can find lumi based on lumi.evnum (find lumi where lumi.evenum = blah) but cannot find lumi.evnum"); } if(Util.isSame(token2, "parent") && Util.isSame(token, "file")) { checkMax(iter); boolean dontJoin = false; if(fileParentAdded) dontJoin = true; fileParentAdded = true; if(!dontJoin) parentJoinQuery += handleParent(tmpTableName, "Files", "FileParentage"); String fqName = tmpTableName + ".LogicalFileName"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "child") && Util.isSame(token, "file")) { checkMax(iter); boolean dontJoin = false; if(fileChildAdded) dontJoin = true; fileChildAdded = true; //System.out.println("childJoinQuery " + childJoinQuery+ " dontJoin " + dontJoin); if(!dontJoin) childJoinQuery += handleChild(tmpTableName, "Files", "FileParentage"); String fqName = tmpTableName + ".LogicalFileName"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "parent") && Util.isSame(token, "block")) { checkMax(iter); boolean dontJoin = false; if(blockParentAdded) dontJoin = true; blockParentAdded = true; if(!dontJoin) blockParentJoinQuery += handleParent(tmpTableName, "Block", "BlockParent"); String fqName = tmpTableName + ".Name"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "child") && Util.isSame(token, "block")) { checkMax(iter); boolean dontJoin = false; if(blockChildAdded) dontJoin = true; blockChildAdded = true; if(!dontJoin) blockChildJoinQuery += handleBlockChild(tmpTableName, "Block", "BlockParent"); String fqName = tmpTableName + ".Name"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "parent") && Util.isSame(token, "procds")) { checkMax(iter); boolean dontJoin = false; if(procDsParentAdded) dontJoin = true; procDsParentAdded = true; if(!dontJoin) parentJoinQuery += handleParent(tmpTableName, "ProcessedDataset", "ProcDSParent"); String fqName = tmpTableName + ".Name"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "child") && Util.isSame(token, "procds")) { checkMax(iter); boolean dontJoin = false; if(procDsChildAdded) dontJoin = true; procDsChildAdded = true; if(!dontJoin) parentJoinQuery += handleProcdsChild(tmpTableName, "ProcessedDataset", "ProcDSParent"); String fqName = tmpTableName + ".Name"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "parent") && Util.isSame(token, "dataset")) { //Lets have the same treatment as procds.parent checkMax(iter); allKws = addUniqueInList(allKws, "Block"); boolean dontJoin = false; if(datasetParentAdded) dontJoin = true; datasetParentAdded = true; if(!dontJoin) pathParentWhereQuery += handlePathParent(tmpTableName, "Block", "ProcDSParent"); String fqName = tmpTableName + ".Path"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } addQuery = false; } if(Util.isSame(token2, "child") && Util.isSame(token, "dataset")) { checkMax(iter); allKws = addUniqueInList(allKws, "Block"); boolean dontJoin = false; if(datasetChildAdded) dontJoin = true; datasetChildAdded = true; if(!dontJoin) pathChildWhereQuery += handlePathChild(tmpTableName, "Block", "ProcDSParent"); String fqName = tmpTableName + ".Path"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } addQuery = false; } /*if(Util.isSame(token2, "parent") && Util.isSame(token, "dataset")) { //Lets have the same treatment as procds.parent checkMax(iter); allKws = addUniqueInList(allKws, "Block"); boolean dontJoin = false; if(datasetParentAdded) dontJoin = true; datasetParentAdded = true; if(!dontJoin) pathParentWhereQuery += handlePathParent(); String fqName = "Block.Path AS Dataset_Parent"; query += fqName; if(iLumi) groupByQuery += "Block.Path ,"; if(sumPresent || countPresent) { if(!sumQuery.equals(selectStr)) sumQuery += ",\n\t"; sumQuery += " Dataset_Parent AS Dataset_Parent "; sumGroupByQuery += " Dataset_Parent ,"; } addQuery = false; }
diff --git a/mpicbg/ij/plugin/ElasticAlign.java b/mpicbg/ij/plugin/ElasticAlign.java index b46397d..4441b21 100644 --- a/mpicbg/ij/plugin/ElasticAlign.java +++ b/mpicbg/ij/plugin/ElasticAlign.java @@ -1,982 +1,984 @@ /** * License: GPL * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License 2 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package mpicbg.ij.plugin; import ij.IJ; import ij.ImagePlus; import ij.ImageStack; import ij.WindowManager; import ij.gui.GenericDialog; import ij.io.DirectoryChooser; import ij.measure.Calibration; import ij.plugin.PlugIn; import ij.process.FloatProcessor; import ij.process.ImageProcessor; import java.awt.TextField; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import mpicbg.ij.SIFT; import mpicbg.ij.TransformMeshMapping; import mpicbg.ij.blockmatching.BlockMatching; import mpicbg.imagefeatures.Feature; import mpicbg.imagefeatures.FloatArray2DSIFT; import mpicbg.models.AbstractModel; import mpicbg.models.AffineModel2D; import mpicbg.models.CoordinateTransformMesh; import mpicbg.models.ErrorStatistic; import mpicbg.models.HomographyModel2D; import mpicbg.models.InvertibleCoordinateTransform; import mpicbg.models.MovingLeastSquaresTransform; import mpicbg.models.NotEnoughDataPointsException; import mpicbg.models.Point; import mpicbg.models.PointMatch; import mpicbg.models.RigidModel2D; import mpicbg.models.SimilarityModel2D; import mpicbg.models.Spring; import mpicbg.models.SpringMesh; import mpicbg.models.Tile; import mpicbg.models.TileConfiguration; import mpicbg.models.Transforms; import mpicbg.models.TranslationModel2D; import mpicbg.models.Vertex; import mpicbg.util.Util; /** * @author Stephan Saalfeld <[email protected]> * @version 0.1a */ public class ElasticAlign implements PlugIn, KeyListener { final static private class Triple< A, B, C > { final public A a; final public B b; final public C c; Triple( final A a, final B b, final C c ) { this.a = a; this.b = b; this.c = c; } } final static private class Param implements Serializable { private static final long serialVersionUID = -4088939083329200368L; public String outputPath = ""; final public FloatArray2DSIFT.Param sift = new FloatArray2DSIFT.Param(); { sift.fdSize = 8; } public int maxNumThreadsSift = Runtime.getRuntime().availableProcessors(); /** * Closest/next closest neighbor distance ratio */ public float rod = 0.92f; /** * Maximal accepted alignment error in px */ public float maxEpsilon = 200.0f; /** * Inlier/candidates ratio */ public float minInlierRatio = 0.0f; /** * Minimal absolute number of inliers */ public int minNumInliers = 12; /** * Transformation models for choice */ final static public String[] modelStrings = new String[]{ "Translation", "Rigid", "Similarity", "Affine", "Perspective" }; public int modelIndex = 3; /** * Ignore identity transform up to a given tolerance */ public boolean rejectIdentity = true; public float identityTolerance = 5.0f; /** * Maximal number of consecutive sections to be tested for an alignment model */ public int maxNumNeighbors = 10; /** * Maximal number of consecutive slices for which no model could be found */ public int maxNumFailures = 3; public float sectionScale = -1; public float minR = 0.8f; public float maxCurvatureR = 3f; public float rodR = 0.8f; public boolean mask = false; public int modelIndexOptimize = 1; public int maxIterationsOptimize = 1000; public int maxPlateauwidthOptimize = 200; public int resolutionSpringMesh = 16; public float stiffnessSpringMesh = 0.1f; public float dampSpringMesh = 0.6f; public float maxStretchSpringMesh = 2000.0f; public int maxIterationsSpringMesh = 1000; public int maxPlateauwidthSpringMesh = 200; public boolean interpolate = true; public boolean visualize = true; public int resolutionOutput = 128; public boolean clearCache = true; public int maxNumThreads = Runtime.getRuntime().availableProcessors(); public boolean setup( final ImagePlus imp ) { DirectoryChooser.setDefaultDirectory( outputPath ); final DirectoryChooser dc = new DirectoryChooser( "Elastically align stack: Output directory" ); outputPath = dc.getDirectory(); if ( outputPath == null ) { outputPath = ""; return false; } else { final File d = new File( outputPath ); if ( d.exists() && d.isDirectory() ) outputPath += "/"; else return false; } final GenericDialog gdOutput = new GenericDialog( "Elastically align stack: Output" ); gdOutput.addCheckbox( "interpolate", interpolate ); gdOutput.addCheckbox( "visualize", visualize ); gdOutput.addNumericField( "resolution :", resolutionOutput, 0 ); gdOutput.showDialog(); if ( gdOutput.wasCanceled() ) return false; interpolate = gdOutput.getNextBoolean(); visualize = gdOutput.getNextBoolean(); resolutionOutput = ( int )gdOutput.getNextNumber(); /* SIFT */ final GenericDialog gd = new GenericDialog( "Elastically align stack: SIFT parameters" ); SIFT.addFields( gd, sift ); gd.addNumericField( "closest/next_closest_ratio :", rod, 2 ); gd.addMessage( "Geometric Consensus Filter:" ); gd.addNumericField( "maximal_alignment_error :", maxEpsilon, 2, 6, "px" ); gd.addNumericField( "minimal_inlier_ratio :", minInlierRatio, 2 ); gd.addNumericField( "minimal_number_of_inliers :", minNumInliers, 0 ); gd.addChoice( "approximate_transformation :", Param.modelStrings, Param.modelStrings[ modelIndex ] ); gd.addCheckbox( "ignore constant background", rejectIdentity ); gd.addNumericField( "tolerance :", identityTolerance, 2, 6, "px" ); gd.addMessage( "Matching:" ); gd.addNumericField( "test_maximally :", maxNumNeighbors, 0, 6, "layers" ); gd.addNumericField( "give_up_after :", maxNumFailures, 0, 6, "failures" ); gd.addMessage( "Miscellaneous:" ); gd.addCheckbox( "clear_cache", clearCache ); gd.addNumericField( "feature_extraction_threads :", maxNumThreadsSift, 0 ); gd.showDialog(); if ( gd.wasCanceled() ) return false; SIFT.readFields( gd, sift ); rod = ( float )gd.getNextNumber(); maxEpsilon = ( float )gd.getNextNumber(); minInlierRatio = ( float )gd.getNextNumber(); minNumInliers = ( int )gd.getNextNumber(); modelIndex = gd.getNextChoiceIndex(); rejectIdentity = gd.getNextBoolean(); identityTolerance = ( float )gd.getNextNumber(); maxNumNeighbors = ( int )gd.getNextNumber(); maxNumFailures = ( int )gd.getNextNumber(); clearCache = gd.getNextBoolean(); maxNumThreadsSift = ( int )gd.getNextNumber(); /* Block Matching */ if ( sectionScale < 0 ) { final Calibration calib = imp.getCalibration(); sectionScale = ( float )( calib.pixelWidth / calib.pixelDepth ); } final GenericDialog gdBlockMatching = new GenericDialog( "Elastically align stack: Block Matching parameters" ); gdBlockMatching.addMessage( "Block Matching:" ); gdBlockMatching.addNumericField( "scale :", sectionScale, 2 ); gdBlockMatching.addNumericField( "minimal_PMCC_r :", minR, 2 ); gdBlockMatching.addNumericField( "maximal_curvature_ratio :", maxCurvatureR, 2 ); gdBlockMatching.addNumericField( "maximal_second_best_r/best_r :", rodR, 2 ); gdBlockMatching.addNumericField( "resolution :", resolutionSpringMesh, 0 ); gdBlockMatching.addCheckbox( "green_mask_(TODO_more_colors)", mask ); gdBlockMatching.showDialog(); if ( gdBlockMatching.wasCanceled() ) return false; sectionScale = ( float )gdBlockMatching.getNextNumber(); minR = ( float )gdBlockMatching.getNextNumber(); maxCurvatureR = ( float )gdBlockMatching.getNextNumber(); rodR = ( float )gdBlockMatching.getNextNumber(); resolutionSpringMesh = ( int )gdBlockMatching.getNextNumber(); mask = gdBlockMatching.getNextBoolean(); /* Optimization */ final GenericDialog gdOptimize = new GenericDialog( "Elastically align stack: Optimization" ); gdOptimize.addMessage( "Approximate Optimizer:" ); gdOptimize.addChoice( "approximate_transformation :", Param.modelStrings, Param.modelStrings[ modelIndexOptimize ] ); gdOptimize.addNumericField( "maximal_iterations :", maxIterationsOptimize, 0 ); gdOptimize.addNumericField( "maximal_plateauwidth :", maxPlateauwidthOptimize, 0 ); gdOptimize.addMessage( "Spring Mesh:" ); gdOptimize.addNumericField( "stiffness :", stiffnessSpringMesh, 2 ); gdOptimize.addNumericField( "maximal_stretch :", maxStretchSpringMesh, 2, 6, "px" ); gdOptimize.addNumericField( "maximal_iterations :", maxIterationsSpringMesh, 0 ); gdOptimize.addNumericField( "maximal_plateauwidth :", maxPlateauwidthSpringMesh, 0 ); gdOptimize.showDialog(); if ( gdOptimize.wasCanceled() ) return false; modelIndexOptimize = gdOptimize.getNextChoiceIndex(); maxIterationsOptimize = ( int )gdOptimize.getNextNumber(); maxPlateauwidthOptimize = ( int )gdOptimize.getNextNumber(); stiffnessSpringMesh = ( float )gdOptimize.getNextNumber(); maxStretchSpringMesh = ( float )gdOptimize.getNextNumber(); maxIterationsSpringMesh = ( int )gdOptimize.getNextNumber(); maxPlateauwidthSpringMesh = ( int )gdOptimize.getNextNumber(); return true; } public boolean equalSiftPointMatchParams( final Param param ) { return sift.equals( param.sift ) && maxEpsilon == param.maxEpsilon && minInlierRatio == param.minInlierRatio && minNumInliers == param.minNumInliers && modelIndex == param.modelIndex && rejectIdentity == param.rejectIdentity && identityTolerance == param.identityTolerance && maxNumNeighbors == param.maxNumNeighbors && maxNumFailures == param.maxNumFailures; } } final static Param p = new Param(); final public void run( final String args ) { if ( IJ.versionLessThan( "1.41n" ) ) return; try { run(); } catch ( Throwable t ) { t.printStackTrace(); } } final public void run() throws Exception { final ImagePlus imp = WindowManager.getCurrentImage(); if ( imp == null ) { System.err.println( "There are no images open" ); return; } if ( !p.setup( imp ) ) return; final ImageStack stack = imp.getStack(); final double displayRangeMin = imp.getDisplayRangeMin(); final double displayRangeMax = imp.getDisplayRangeMax(); final ArrayList< Tile< ? > > tiles = new ArrayList< Tile<?> >(); for ( int i = 0; i < stack.getSize(); ++i ) { switch ( p.modelIndexOptimize ) { case 0: tiles.add( new Tile< TranslationModel2D >( new TranslationModel2D() ) ); break; case 1: tiles.add( new Tile< RigidModel2D >( new RigidModel2D() ) ); break; case 2: tiles.add( new Tile< SimilarityModel2D >( new SimilarityModel2D() ) ); break; case 3: tiles.add( new Tile< AffineModel2D >( new AffineModel2D() ) ); break; case 4: tiles.add( new Tile< HomographyModel2D >( new HomographyModel2D() ) ); break; default: return; } } final ExecutorService execSift = Executors.newFixedThreadPool( p.maxNumThreadsSift ); /* extract features for all slices and store them to disk */ final AtomicInteger counter = new AtomicInteger( 0 ); final ArrayList< Future< ArrayList< Feature > > > siftTasks = new ArrayList< Future< ArrayList< Feature > > >(); for ( int i = 1; i <= stack.getSize(); i++ ) { final int slice = i; siftTasks.add( execSift.submit( new Callable< ArrayList< Feature > >() { public ArrayList< Feature > call() { IJ.showProgress( counter.getAndIncrement(), stack.getSize() ); //final String path = p.outputPath + stack.getSliceLabel( slice ) + ".features"; final String path = p.outputPath + String.format( "%05d", slice - 1 ) + ".features"; - ArrayList< Feature > fs = deserializeFeatures( p.sift, path ); - if ( null == fs ) + ArrayList< Feature > fs = null; + if ( !p.clearCache ) + fs = deserializeFeatures( p.sift, path ); + if ( fs == null ) { final FloatArray2DSIFT sift = new FloatArray2DSIFT( p.sift ); final SIFT ijSIFT = new SIFT( sift ); fs = new ArrayList< Feature >(); final ImageProcessor ip = stack.getProcessor( slice ); ip.setMinAndMax( displayRangeMin, displayRangeMax ); ijSIFT.extractFeatures( ip, fs ); - if ( ! serializeFeatures( p.sift, fs, path ) ) + if ( !serializeFeatures( p.sift, fs, path ) ) { //IJ.log( "FAILED to store serialized features for " + stack.getSliceLabel( slice ) ); IJ.log( "FAILED to store serialized features for " + String.format( "%05d", slice - 1 ) ); } } //IJ.log( fs.size() + " features extracted for slice " + stack.getSliceLabel ( slice ) ); IJ.log( fs.size() + " features extracted for slice " + String.format( "%05d", slice - 1 ) ); return fs; } } ) ); } /* join */ for ( Future< ArrayList< Feature > > fu : siftTasks ) fu.get(); siftTasks.clear(); execSift.shutdown(); /* collect all pairs of slices for which a model could be found */ final ArrayList< Triple< Integer, Integer, AbstractModel< ? > > > pairs = new ArrayList< Triple< Integer, Integer, AbstractModel< ? > > >(); counter.set( 0 ); int numFailures = 0; for ( int i = 0; i < stack.getSize(); ++i ) { final ArrayList< Thread > threads = new ArrayList< Thread >( p.maxNumThreads ); final int sliceA = i; final int range = Math.min( stack.getSize(), i + p.maxNumNeighbors + 1 ); J: for ( int j = i + 1; j < range; ) { final int numThreads = Math.min( p.maxNumThreads, range - j ); final ArrayList< Triple< Integer, Integer, AbstractModel< ? > > > models = new ArrayList< Triple< Integer, Integer, AbstractModel< ? > > >( numThreads ); for ( int k = 0; k < numThreads; ++k ) models.add( null ); for ( int t = 0; t < numThreads && j < range; ++t, ++j ) { final int ti = t; final int sliceB = j; final Thread thread = new Thread() { public void run() { IJ.showProgress( sliceA, stack.getSize() - 1 ); IJ.log( "matching " + sliceB + " -> " + sliceA + "..." ); ArrayList< PointMatch > candidates = null; String path = p.outputPath + String.format( "%05d", sliceB ) + "-" + String.format( "%05d", sliceA ) + ".pointmatches"; if ( !p.clearCache ) candidates = deserializePointMatches( p, path ); if ( null == candidates ) { ArrayList< Feature > fs1 = deserializeFeatures( p.sift, p.outputPath + String.format( "%05d", sliceA ) + ".features" ); ArrayList< Feature > fs2 = deserializeFeatures( p.sift, p.outputPath + String.format( "%05d", sliceB ) + ".features" ); candidates = new ArrayList< PointMatch >( FloatArray2DSIFT.createMatches( fs2, fs1, p.rod ) ); if ( !serializePointMatches( p, candidates, path ) ) IJ.log( "Could not store point matches!" ); } AbstractModel< ? > model; switch ( p.modelIndex ) { case 0: model = new TranslationModel2D(); break; case 1: model = new RigidModel2D(); break; case 2: model = new SimilarityModel2D(); break; case 3: model = new AffineModel2D(); break; case 4: model = new HomographyModel2D(); break; default: return; } final ArrayList< PointMatch > inliers = new ArrayList< PointMatch >(); boolean modelFound; boolean again = false; try { do { modelFound = model.filterRansac( candidates, inliers, 1000, p.maxEpsilon, p.minInlierRatio, p.minNumInliers, 3 ); if ( modelFound && p.rejectIdentity ) { final ArrayList< Point > points = new ArrayList< Point >(); PointMatch.sourcePoints( inliers, points ); if ( Transforms.isIdentity( model, points, p.identityTolerance ) ) { IJ.log( "Identity transform for " + inliers.size() + " matches rejected." ); candidates.removeAll( inliers ); inliers.clear(); again = true; } } } while ( again ); } catch ( Exception e ) { modelFound = false; System.err.println( e.getMessage() ); } if ( modelFound ) { IJ.log( sliceB + " -> " + sliceA + ": " + inliers.size() + " corresponding features with an average displacement of " + PointMatch.meanDistance( inliers ) + "px identified." ); IJ.log( "Estimated transformation model: " + model ); models.set( ti, new Triple< Integer, Integer, AbstractModel< ? > >( sliceA, sliceB, model ) ); } else { IJ.log( sliceB + " -> " + sliceA + ": no correspondences found." ); return; } } }; threads.add( thread ); thread.start(); } try { for ( final Thread thread : threads ) thread.join(); } catch ( InterruptedException e ) { IJ.log( "Establishing feature correspondences interrupted." ); for ( final Thread thread : threads ) thread.interrupt(); try { for ( final Thread thread : threads ) thread.join(); } catch ( InterruptedException f ) {} return; } threads.clear(); /* collect successfully matches pairs and break the search on gaps */ for ( int t = 0; t < models.size(); ++t ) { final Triple< Integer, Integer, AbstractModel< ? > > pair = models.get( t ); if ( pair == null ) { if ( ++numFailures > p.maxNumFailures ) break J; } else { numFailures = 0; pairs.add( pair ); } } } } /* Elastic alignment */ /* Initialization */ final TileConfiguration initMeshes = new TileConfiguration(); final ArrayList< SpringMesh > meshes = new ArrayList< SpringMesh >( stack.getSize() ); for ( int i = 0; i < stack.getSize(); ++i ) meshes.add( new SpringMesh( p.resolutionSpringMesh, stack.getWidth(), stack.getHeight(), p.stiffnessSpringMesh, p.maxStretchSpringMesh, p.dampSpringMesh ) ); final int blockRadius = Math.max( 32, stack.getWidth() / p.resolutionSpringMesh / 2 ); /** TODO set this something more than the largest error by the approximate model */ final int searchRadius = Math.round( p.maxEpsilon ); for ( final Triple< Integer, Integer, AbstractModel< ? > > pair : pairs ) { final SpringMesh m1 = meshes.get( pair.a ); final SpringMesh m2 = meshes.get( pair.b ); ArrayList< PointMatch > pm12 = new ArrayList< PointMatch >(); ArrayList< PointMatch > pm21 = new ArrayList< PointMatch >(); final Collection< Vertex > v1 = m1.getVertices(); final Collection< Vertex > v2 = m2.getVertices(); final FloatProcessor ip1 = ( FloatProcessor )stack.getProcessor( pair.a + 1 ).convertToFloat().duplicate(); final FloatProcessor ip2 = ( FloatProcessor )stack.getProcessor( pair.b + 1 ).convertToFloat().duplicate(); final FloatProcessor ip1Mask; final FloatProcessor ip2Mask; if ( imp.getType() == ImagePlus.COLOR_RGB && p.mask ) { ip1Mask = createMask( stack.getProcessor( pair.a + 1 ) ); ip2Mask = createMask( stack.getProcessor( pair.b + 1 ) ); } else { ip1Mask = null; ip2Mask = null; } try { BlockMatching.matchByMaximalPMCC( ip1, ip2, ip1Mask, ip2Mask, Math.min( 1.0f, ( float )p.sectionScale ), ( ( InvertibleCoordinateTransform )pair.c ).createInverse(), blockRadius, blockRadius, searchRadius, searchRadius, p.minR, p.rodR, p.maxCurvatureR, v1, pm12, new ErrorStatistic( 1 ) ); } catch ( InterruptedException e ) { IJ.log( "Block matching interrupted." ); IJ.showProgress( 1.0 ); return; } if ( Thread.interrupted() ) { IJ.log( "Block matching interrupted." ); IJ.showProgress( 1.0 ); return; } IJ.log( pair.a + " > " + pair.b + ": found " + pm12.size() + " correspondences." ); /* <visualisation> */ // final List< Point > s1 = new ArrayList< Point >(); // PointMatch.sourcePoints( pm12, s1 ); // final ImagePlus imp1 = new ImagePlus( i + " >", ip1 ); // imp1.show(); // imp1.setOverlay( BlockMatching.illustrateMatches( pm12 ), Color.yellow, null ); // imp1.setRoi( Util.pointsToPointRoi( s1 ) ); // imp1.updateAndDraw(); /* </visualisation> */ try { BlockMatching.matchByMaximalPMCC( ip2, ip1, ip2Mask, ip1Mask, Math.min( 1.0f, ( float )p.sectionScale ), pair.c, blockRadius, blockRadius, searchRadius, searchRadius, p.minR, p.rodR, p.maxCurvatureR, v2, pm21, new ErrorStatistic( 1 ) ); } catch ( InterruptedException e ) { IJ.log( "Block matching interrupted." ); IJ.showProgress( 1.0 ); return; } if ( Thread.interrupted() ) { IJ.log( "Block matching interrupted." ); IJ.showProgress( 1.0 ); return; } IJ.log( pair.a + " < " + pair.b + ": found " + pm21.size() + " correspondences." ); /* <visualisation> */ // final List< Point > s2 = new ArrayList< Point >(); // PointMatch.sourcePoints( pm21, s2 ); // final ImagePlus imp2 = new ImagePlus( i + " <", ip2 ); // imp2.show(); // imp2.setOverlay( BlockMatching.illustrateMatches( pm21 ), Color.yellow, null ); // imp2.setRoi( Util.pointsToPointRoi( s2 ) ); // imp2.updateAndDraw(); /* </visualisation> */ final float springConstant = 1.0f / ( pair.b - pair.a ); IJ.log( pair.a + " <> " + pair.b + " spring constant = " + springConstant ); for ( final PointMatch pm : pm12 ) { final Vertex p1 = ( Vertex )pm.getP1(); final Vertex p2 = new Vertex( pm.getP2() ); p1.addSpring( p2, new Spring( 0, springConstant ) ); m2.addPassiveVertex( p2 ); } for ( final PointMatch pm : pm21 ) { final Vertex p1 = ( Vertex )pm.getP1(); final Vertex p2 = new Vertex( pm.getP2() ); p1.addSpring( p2, new Spring( 0, springConstant ) ); m1.addPassiveVertex( p2 ); } final Tile< ? > t1 = tiles.get( pair.a ); final Tile< ? > t2 = tiles.get( pair.b ); if ( pm12.size() > pair.c.getMinNumMatches() ) { initMeshes.addTile( t1 ); initMeshes.addTile( t2 ); t1.connect( t2, pm12 ); } if ( pm21.size() > pair.c.getMinNumMatches() ) { initMeshes.addTile( t1 ); initMeshes.addTile( t2 ); t2.connect( t1, pm21 ); } } /* pre-align by optimizing a piecewise linear model */ initMeshes.optimize( p.maxEpsilon, p.maxIterationsSpringMesh, p.maxPlateauwidthSpringMesh ); for ( int i = 0; i < stack.getSize(); ++i ) meshes.get( i ).init( tiles.get( i ).getModel() ); /* optimize the meshes */ try { long t0 = System.currentTimeMillis(); IJ.log("Optimizing spring meshes..."); SpringMesh.optimizeMeshes( meshes, p.maxEpsilon, p.maxIterationsSpringMesh, p.maxPlateauwidthSpringMesh, p.visualize ); IJ.log( "Done optimizing spring meshes. Took " + ( System.currentTimeMillis() - t0 ) + " ms" ); } catch ( NotEnoughDataPointsException e ) { IJ.log( "There were not enough data points to get the spring mesh optimizing." ); e.printStackTrace(); return; } /* calculate bounding box */ final float[] min = new float[ 2 ]; final float[] max = new float[ 2 ]; for ( final SpringMesh mesh : meshes ) { final float[] meshMin = new float[ 2 ]; final float[] meshMax = new float[ 2 ]; mesh.bounds( meshMin, meshMax ); Util.min( min, meshMin ); Util.max( max, meshMax ); } /* translate relative to bounding box */ for ( final SpringMesh mesh : meshes ) { for ( final Vertex vertex : mesh.getVertices() ) { final float[] w = vertex.getW(); w[ 0 ] -= min[ 0 ]; w[ 1 ] -= min[ 1 ]; } mesh.updateAffines(); mesh.updatePassiveVertices(); } final int width = ( int )Math.ceil( max[ 0 ] - min[ 0 ] ); final int height = ( int )Math.ceil( max[ 1 ] - min[ 1 ] ); for ( int i = 0; i < stack.getSize(); ++i ) { final int slice = i + 1; final MovingLeastSquaresTransform mlt = new MovingLeastSquaresTransform(); mlt.setModel( AffineModel2D.class ); mlt.setAlpha( 2.0f ); mlt.setMatches( meshes.get( i ).getVA().keySet() ); final TransformMeshMapping< CoordinateTransformMesh > mltMapping = new TransformMeshMapping< CoordinateTransformMesh >( new CoordinateTransformMesh( mlt, p.resolutionOutput, stack.getWidth(), stack.getHeight() ) ); final ImageProcessor ip = stack.getProcessor( slice ).createProcessor( width, height ); if ( p.interpolate ) { mltMapping.mapInterpolated( stack.getProcessor( slice ), ip ); } else { mltMapping.map( stack.getProcessor( slice ), ip ); } IJ.save( new ImagePlus( "elastic mlt " + i, ip ), p.outputPath + "elastic-" + String.format( "%05d", i ) + ".tif" ); } IJ.log( "Done." ); } static private FloatProcessor createMask( final ImageProcessor source ) { final FloatProcessor mask = new FloatProcessor( source.getWidth(), source.getHeight() ); final int maskColor = 0x0000ff00; final int n = source.getWidth() * source.getHeight(); final float[] maskPixels = ( float[] )mask.getPixels(); for ( int i = 0; i < n; ++i ) { final int sourcePixel = source.get( i ) & 0x00ffffff; if ( sourcePixel == maskColor ) maskPixels[ i ] = 0; else maskPixels[ i ] = 1; } return mask; } public void keyPressed(KeyEvent e) { if ( ( e.getKeyCode() == KeyEvent.VK_F1 ) && ( e.getSource() instanceof TextField ) ) { } } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } final static private class Features implements Serializable { private static final long serialVersionUID = 2668666732018368958L; final FloatArray2DSIFT.Param param; final ArrayList< Feature > features; Features( final FloatArray2DSIFT.Param p, final ArrayList< Feature > features ) { this.param = p; this.features = features; } } final static private boolean serializeFeatures( final FloatArray2DSIFT.Param param, final ArrayList< Feature > fs, final String path ) { return serialize( new Features( param, fs ), path ); } final static private ArrayList< Feature > deserializeFeatures( final FloatArray2DSIFT.Param param, final String path ) { Object o = deserialize( path ); if ( null == o ) return null; Features fs = (Features) o; if ( param.equals( fs.param ) ) return fs.features; return null; } final static private class PointMatches implements Serializable { private static final long serialVersionUID = 3718614767497404447L; ElasticAlign.Param param; ArrayList< PointMatch > pointMatches; PointMatches( final ElasticAlign.Param p, final ArrayList< PointMatch > pointMatches ) { this.param = p; this.pointMatches = pointMatches; } } final static private boolean serializePointMatches( final ElasticAlign.Param param, final ArrayList< PointMatch > pms, final String path ) { return serialize( new PointMatches( param, pms ), path ); } final static private ArrayList< PointMatch > deserializePointMatches( final ElasticAlign.Param param, final String path ) { Object o = deserialize( path ); if ( null == o ) return null; PointMatches pms = (PointMatches) o; if ( param.equalSiftPointMatchParams( pms.param ) ) return pms.pointMatches; return null; } /** Serializes the given object into the path. Returns false on failure. */ static public boolean serialize(final Object ob, final String path) { try { // 1 - Check that the parent chain of folders exists, and attempt to create it when not: File fdir = new File(path).getParentFile(); if (null == fdir) return false; fdir.mkdirs(); if (!fdir.exists()) { IJ.log("Could not create folder " + fdir.getAbsolutePath()); return false; } // 2 - Serialize the given object: final ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path)); out.writeObject(ob); out.close(); return true; } catch (Exception e) { e.printStackTrace(); } return false; } /** Attempts to find a file containing a serialized object. Returns null if no suitable file is found, or an error occurs while deserializing. */ static public Object deserialize(final String path) { try { if (!new File(path).exists()) return null; final ObjectInputStream in = new ObjectInputStream(new FileInputStream(path)); final Object ob = in.readObject(); in.close(); return ob; } catch (Exception e) { e.printStackTrace(); } return null; } }
false
true
final public void run() throws Exception { final ImagePlus imp = WindowManager.getCurrentImage(); if ( imp == null ) { System.err.println( "There are no images open" ); return; } if ( !p.setup( imp ) ) return; final ImageStack stack = imp.getStack(); final double displayRangeMin = imp.getDisplayRangeMin(); final double displayRangeMax = imp.getDisplayRangeMax(); final ArrayList< Tile< ? > > tiles = new ArrayList< Tile<?> >(); for ( int i = 0; i < stack.getSize(); ++i ) { switch ( p.modelIndexOptimize ) { case 0: tiles.add( new Tile< TranslationModel2D >( new TranslationModel2D() ) ); break; case 1: tiles.add( new Tile< RigidModel2D >( new RigidModel2D() ) ); break; case 2: tiles.add( new Tile< SimilarityModel2D >( new SimilarityModel2D() ) ); break; case 3: tiles.add( new Tile< AffineModel2D >( new AffineModel2D() ) ); break; case 4: tiles.add( new Tile< HomographyModel2D >( new HomographyModel2D() ) ); break; default: return; } } final ExecutorService execSift = Executors.newFixedThreadPool( p.maxNumThreadsSift ); /* extract features for all slices and store them to disk */ final AtomicInteger counter = new AtomicInteger( 0 ); final ArrayList< Future< ArrayList< Feature > > > siftTasks = new ArrayList< Future< ArrayList< Feature > > >(); for ( int i = 1; i <= stack.getSize(); i++ ) { final int slice = i; siftTasks.add( execSift.submit( new Callable< ArrayList< Feature > >() { public ArrayList< Feature > call() { IJ.showProgress( counter.getAndIncrement(), stack.getSize() ); //final String path = p.outputPath + stack.getSliceLabel( slice ) + ".features"; final String path = p.outputPath + String.format( "%05d", slice - 1 ) + ".features"; ArrayList< Feature > fs = deserializeFeatures( p.sift, path ); if ( null == fs ) { final FloatArray2DSIFT sift = new FloatArray2DSIFT( p.sift ); final SIFT ijSIFT = new SIFT( sift ); fs = new ArrayList< Feature >(); final ImageProcessor ip = stack.getProcessor( slice ); ip.setMinAndMax( displayRangeMin, displayRangeMax ); ijSIFT.extractFeatures( ip, fs ); if ( ! serializeFeatures( p.sift, fs, path ) ) { //IJ.log( "FAILED to store serialized features for " + stack.getSliceLabel( slice ) ); IJ.log( "FAILED to store serialized features for " + String.format( "%05d", slice - 1 ) ); } } //IJ.log( fs.size() + " features extracted for slice " + stack.getSliceLabel ( slice ) ); IJ.log( fs.size() + " features extracted for slice " + String.format( "%05d", slice - 1 ) ); return fs; } } ) ); } /* join */ for ( Future< ArrayList< Feature > > fu : siftTasks ) fu.get(); siftTasks.clear(); execSift.shutdown(); /* collect all pairs of slices for which a model could be found */ final ArrayList< Triple< Integer, Integer, AbstractModel< ? > > > pairs = new ArrayList< Triple< Integer, Integer, AbstractModel< ? > > >(); counter.set( 0 ); int numFailures = 0; for ( int i = 0; i < stack.getSize(); ++i ) { final ArrayList< Thread > threads = new ArrayList< Thread >( p.maxNumThreads ); final int sliceA = i; final int range = Math.min( stack.getSize(), i + p.maxNumNeighbors + 1 ); J: for ( int j = i + 1; j < range; ) { final int numThreads = Math.min( p.maxNumThreads, range - j ); final ArrayList< Triple< Integer, Integer, AbstractModel< ? > > > models = new ArrayList< Triple< Integer, Integer, AbstractModel< ? > > >( numThreads ); for ( int k = 0; k < numThreads; ++k ) models.add( null ); for ( int t = 0; t < numThreads && j < range; ++t, ++j ) { final int ti = t; final int sliceB = j; final Thread thread = new Thread() { public void run() { IJ.showProgress( sliceA, stack.getSize() - 1 ); IJ.log( "matching " + sliceB + " -> " + sliceA + "..." ); ArrayList< PointMatch > candidates = null; String path = p.outputPath + String.format( "%05d", sliceB ) + "-" + String.format( "%05d", sliceA ) + ".pointmatches"; if ( !p.clearCache ) candidates = deserializePointMatches( p, path ); if ( null == candidates ) { ArrayList< Feature > fs1 = deserializeFeatures( p.sift, p.outputPath + String.format( "%05d", sliceA ) + ".features" ); ArrayList< Feature > fs2 = deserializeFeatures( p.sift, p.outputPath + String.format( "%05d", sliceB ) + ".features" ); candidates = new ArrayList< PointMatch >( FloatArray2DSIFT.createMatches( fs2, fs1, p.rod ) ); if ( !serializePointMatches( p, candidates, path ) ) IJ.log( "Could not store point matches!" ); } AbstractModel< ? > model; switch ( p.modelIndex ) { case 0: model = new TranslationModel2D(); break; case 1: model = new RigidModel2D(); break; case 2: model = new SimilarityModel2D(); break; case 3: model = new AffineModel2D(); break; case 4: model = new HomographyModel2D(); break; default: return; } final ArrayList< PointMatch > inliers = new ArrayList< PointMatch >(); boolean modelFound; boolean again = false; try { do { modelFound = model.filterRansac( candidates, inliers, 1000, p.maxEpsilon, p.minInlierRatio, p.minNumInliers, 3 ); if ( modelFound && p.rejectIdentity ) { final ArrayList< Point > points = new ArrayList< Point >(); PointMatch.sourcePoints( inliers, points ); if ( Transforms.isIdentity( model, points, p.identityTolerance ) ) { IJ.log( "Identity transform for " + inliers.size() + " matches rejected." ); candidates.removeAll( inliers ); inliers.clear(); again = true; } } } while ( again ); } catch ( Exception e ) { modelFound = false; System.err.println( e.getMessage() ); } if ( modelFound ) { IJ.log( sliceB + " -> " + sliceA + ": " + inliers.size() + " corresponding features with an average displacement of " + PointMatch.meanDistance( inliers ) + "px identified." ); IJ.log( "Estimated transformation model: " + model ); models.set( ti, new Triple< Integer, Integer, AbstractModel< ? > >( sliceA, sliceB, model ) ); } else { IJ.log( sliceB + " -> " + sliceA + ": no correspondences found." ); return; } } }; threads.add( thread ); thread.start(); } try { for ( final Thread thread : threads ) thread.join(); } catch ( InterruptedException e ) { IJ.log( "Establishing feature correspondences interrupted." ); for ( final Thread thread : threads ) thread.interrupt(); try { for ( final Thread thread : threads ) thread.join(); } catch ( InterruptedException f ) {} return; } threads.clear(); /* collect successfully matches pairs and break the search on gaps */ for ( int t = 0; t < models.size(); ++t ) { final Triple< Integer, Integer, AbstractModel< ? > > pair = models.get( t ); if ( pair == null ) { if ( ++numFailures > p.maxNumFailures ) break J; } else { numFailures = 0; pairs.add( pair ); } } } } /* Elastic alignment */ /* Initialization */ final TileConfiguration initMeshes = new TileConfiguration(); final ArrayList< SpringMesh > meshes = new ArrayList< SpringMesh >( stack.getSize() ); for ( int i = 0; i < stack.getSize(); ++i ) meshes.add( new SpringMesh( p.resolutionSpringMesh, stack.getWidth(), stack.getHeight(), p.stiffnessSpringMesh, p.maxStretchSpringMesh, p.dampSpringMesh ) ); final int blockRadius = Math.max( 32, stack.getWidth() / p.resolutionSpringMesh / 2 ); /** TODO set this something more than the largest error by the approximate model */ final int searchRadius = Math.round( p.maxEpsilon ); for ( final Triple< Integer, Integer, AbstractModel< ? > > pair : pairs ) { final SpringMesh m1 = meshes.get( pair.a ); final SpringMesh m2 = meshes.get( pair.b ); ArrayList< PointMatch > pm12 = new ArrayList< PointMatch >(); ArrayList< PointMatch > pm21 = new ArrayList< PointMatch >(); final Collection< Vertex > v1 = m1.getVertices(); final Collection< Vertex > v2 = m2.getVertices(); final FloatProcessor ip1 = ( FloatProcessor )stack.getProcessor( pair.a + 1 ).convertToFloat().duplicate(); final FloatProcessor ip2 = ( FloatProcessor )stack.getProcessor( pair.b + 1 ).convertToFloat().duplicate(); final FloatProcessor ip1Mask; final FloatProcessor ip2Mask; if ( imp.getType() == ImagePlus.COLOR_RGB && p.mask ) { ip1Mask = createMask( stack.getProcessor( pair.a + 1 ) ); ip2Mask = createMask( stack.getProcessor( pair.b + 1 ) ); } else { ip1Mask = null; ip2Mask = null; } try { BlockMatching.matchByMaximalPMCC( ip1, ip2, ip1Mask, ip2Mask, Math.min( 1.0f, ( float )p.sectionScale ), ( ( InvertibleCoordinateTransform )pair.c ).createInverse(), blockRadius, blockRadius, searchRadius, searchRadius, p.minR, p.rodR, p.maxCurvatureR, v1, pm12, new ErrorStatistic( 1 ) ); } catch ( InterruptedException e ) { IJ.log( "Block matching interrupted." ); IJ.showProgress( 1.0 ); return; } if ( Thread.interrupted() ) { IJ.log( "Block matching interrupted." ); IJ.showProgress( 1.0 ); return; } IJ.log( pair.a + " > " + pair.b + ": found " + pm12.size() + " correspondences." ); /* <visualisation> */ // final List< Point > s1 = new ArrayList< Point >(); // PointMatch.sourcePoints( pm12, s1 ); // final ImagePlus imp1 = new ImagePlus( i + " >", ip1 ); // imp1.show(); // imp1.setOverlay( BlockMatching.illustrateMatches( pm12 ), Color.yellow, null ); // imp1.setRoi( Util.pointsToPointRoi( s1 ) ); // imp1.updateAndDraw(); /* </visualisation> */ try { BlockMatching.matchByMaximalPMCC( ip2, ip1, ip2Mask, ip1Mask, Math.min( 1.0f, ( float )p.sectionScale ), pair.c, blockRadius, blockRadius, searchRadius, searchRadius, p.minR, p.rodR, p.maxCurvatureR, v2, pm21, new ErrorStatistic( 1 ) ); } catch ( InterruptedException e ) { IJ.log( "Block matching interrupted." ); IJ.showProgress( 1.0 ); return; } if ( Thread.interrupted() ) { IJ.log( "Block matching interrupted." ); IJ.showProgress( 1.0 ); return; } IJ.log( pair.a + " < " + pair.b + ": found " + pm21.size() + " correspondences." ); /* <visualisation> */ // final List< Point > s2 = new ArrayList< Point >(); // PointMatch.sourcePoints( pm21, s2 ); // final ImagePlus imp2 = new ImagePlus( i + " <", ip2 ); // imp2.show(); // imp2.setOverlay( BlockMatching.illustrateMatches( pm21 ), Color.yellow, null ); // imp2.setRoi( Util.pointsToPointRoi( s2 ) ); // imp2.updateAndDraw(); /* </visualisation> */ final float springConstant = 1.0f / ( pair.b - pair.a ); IJ.log( pair.a + " <> " + pair.b + " spring constant = " + springConstant ); for ( final PointMatch pm : pm12 ) { final Vertex p1 = ( Vertex )pm.getP1(); final Vertex p2 = new Vertex( pm.getP2() ); p1.addSpring( p2, new Spring( 0, springConstant ) ); m2.addPassiveVertex( p2 ); } for ( final PointMatch pm : pm21 ) { final Vertex p1 = ( Vertex )pm.getP1(); final Vertex p2 = new Vertex( pm.getP2() ); p1.addSpring( p2, new Spring( 0, springConstant ) ); m1.addPassiveVertex( p2 ); } final Tile< ? > t1 = tiles.get( pair.a ); final Tile< ? > t2 = tiles.get( pair.b ); if ( pm12.size() > pair.c.getMinNumMatches() ) { initMeshes.addTile( t1 ); initMeshes.addTile( t2 ); t1.connect( t2, pm12 ); } if ( pm21.size() > pair.c.getMinNumMatches() ) { initMeshes.addTile( t1 ); initMeshes.addTile( t2 ); t2.connect( t1, pm21 ); } } /* pre-align by optimizing a piecewise linear model */ initMeshes.optimize( p.maxEpsilon, p.maxIterationsSpringMesh, p.maxPlateauwidthSpringMesh ); for ( int i = 0; i < stack.getSize(); ++i ) meshes.get( i ).init( tiles.get( i ).getModel() ); /* optimize the meshes */ try { long t0 = System.currentTimeMillis(); IJ.log("Optimizing spring meshes..."); SpringMesh.optimizeMeshes( meshes, p.maxEpsilon, p.maxIterationsSpringMesh, p.maxPlateauwidthSpringMesh, p.visualize ); IJ.log( "Done optimizing spring meshes. Took " + ( System.currentTimeMillis() - t0 ) + " ms" ); } catch ( NotEnoughDataPointsException e ) { IJ.log( "There were not enough data points to get the spring mesh optimizing." ); e.printStackTrace(); return; } /* calculate bounding box */ final float[] min = new float[ 2 ]; final float[] max = new float[ 2 ]; for ( final SpringMesh mesh : meshes ) { final float[] meshMin = new float[ 2 ]; final float[] meshMax = new float[ 2 ]; mesh.bounds( meshMin, meshMax ); Util.min( min, meshMin ); Util.max( max, meshMax ); } /* translate relative to bounding box */ for ( final SpringMesh mesh : meshes ) { for ( final Vertex vertex : mesh.getVertices() ) { final float[] w = vertex.getW(); w[ 0 ] -= min[ 0 ]; w[ 1 ] -= min[ 1 ]; } mesh.updateAffines(); mesh.updatePassiveVertices(); } final int width = ( int )Math.ceil( max[ 0 ] - min[ 0 ] ); final int height = ( int )Math.ceil( max[ 1 ] - min[ 1 ] ); for ( int i = 0; i < stack.getSize(); ++i ) { final int slice = i + 1; final MovingLeastSquaresTransform mlt = new MovingLeastSquaresTransform(); mlt.setModel( AffineModel2D.class ); mlt.setAlpha( 2.0f ); mlt.setMatches( meshes.get( i ).getVA().keySet() ); final TransformMeshMapping< CoordinateTransformMesh > mltMapping = new TransformMeshMapping< CoordinateTransformMesh >( new CoordinateTransformMesh( mlt, p.resolutionOutput, stack.getWidth(), stack.getHeight() ) ); final ImageProcessor ip = stack.getProcessor( slice ).createProcessor( width, height ); if ( p.interpolate ) { mltMapping.mapInterpolated( stack.getProcessor( slice ), ip ); } else { mltMapping.map( stack.getProcessor( slice ), ip ); } IJ.save( new ImagePlus( "elastic mlt " + i, ip ), p.outputPath + "elastic-" + String.format( "%05d", i ) + ".tif" ); } IJ.log( "Done." ); }
final public void run() throws Exception { final ImagePlus imp = WindowManager.getCurrentImage(); if ( imp == null ) { System.err.println( "There are no images open" ); return; } if ( !p.setup( imp ) ) return; final ImageStack stack = imp.getStack(); final double displayRangeMin = imp.getDisplayRangeMin(); final double displayRangeMax = imp.getDisplayRangeMax(); final ArrayList< Tile< ? > > tiles = new ArrayList< Tile<?> >(); for ( int i = 0; i < stack.getSize(); ++i ) { switch ( p.modelIndexOptimize ) { case 0: tiles.add( new Tile< TranslationModel2D >( new TranslationModel2D() ) ); break; case 1: tiles.add( new Tile< RigidModel2D >( new RigidModel2D() ) ); break; case 2: tiles.add( new Tile< SimilarityModel2D >( new SimilarityModel2D() ) ); break; case 3: tiles.add( new Tile< AffineModel2D >( new AffineModel2D() ) ); break; case 4: tiles.add( new Tile< HomographyModel2D >( new HomographyModel2D() ) ); break; default: return; } } final ExecutorService execSift = Executors.newFixedThreadPool( p.maxNumThreadsSift ); /* extract features for all slices and store them to disk */ final AtomicInteger counter = new AtomicInteger( 0 ); final ArrayList< Future< ArrayList< Feature > > > siftTasks = new ArrayList< Future< ArrayList< Feature > > >(); for ( int i = 1; i <= stack.getSize(); i++ ) { final int slice = i; siftTasks.add( execSift.submit( new Callable< ArrayList< Feature > >() { public ArrayList< Feature > call() { IJ.showProgress( counter.getAndIncrement(), stack.getSize() ); //final String path = p.outputPath + stack.getSliceLabel( slice ) + ".features"; final String path = p.outputPath + String.format( "%05d", slice - 1 ) + ".features"; ArrayList< Feature > fs = null; if ( !p.clearCache ) fs = deserializeFeatures( p.sift, path ); if ( fs == null ) { final FloatArray2DSIFT sift = new FloatArray2DSIFT( p.sift ); final SIFT ijSIFT = new SIFT( sift ); fs = new ArrayList< Feature >(); final ImageProcessor ip = stack.getProcessor( slice ); ip.setMinAndMax( displayRangeMin, displayRangeMax ); ijSIFT.extractFeatures( ip, fs ); if ( !serializeFeatures( p.sift, fs, path ) ) { //IJ.log( "FAILED to store serialized features for " + stack.getSliceLabel( slice ) ); IJ.log( "FAILED to store serialized features for " + String.format( "%05d", slice - 1 ) ); } } //IJ.log( fs.size() + " features extracted for slice " + stack.getSliceLabel ( slice ) ); IJ.log( fs.size() + " features extracted for slice " + String.format( "%05d", slice - 1 ) ); return fs; } } ) ); } /* join */ for ( Future< ArrayList< Feature > > fu : siftTasks ) fu.get(); siftTasks.clear(); execSift.shutdown(); /* collect all pairs of slices for which a model could be found */ final ArrayList< Triple< Integer, Integer, AbstractModel< ? > > > pairs = new ArrayList< Triple< Integer, Integer, AbstractModel< ? > > >(); counter.set( 0 ); int numFailures = 0; for ( int i = 0; i < stack.getSize(); ++i ) { final ArrayList< Thread > threads = new ArrayList< Thread >( p.maxNumThreads ); final int sliceA = i; final int range = Math.min( stack.getSize(), i + p.maxNumNeighbors + 1 ); J: for ( int j = i + 1; j < range; ) { final int numThreads = Math.min( p.maxNumThreads, range - j ); final ArrayList< Triple< Integer, Integer, AbstractModel< ? > > > models = new ArrayList< Triple< Integer, Integer, AbstractModel< ? > > >( numThreads ); for ( int k = 0; k < numThreads; ++k ) models.add( null ); for ( int t = 0; t < numThreads && j < range; ++t, ++j ) { final int ti = t; final int sliceB = j; final Thread thread = new Thread() { public void run() { IJ.showProgress( sliceA, stack.getSize() - 1 ); IJ.log( "matching " + sliceB + " -> " + sliceA + "..." ); ArrayList< PointMatch > candidates = null; String path = p.outputPath + String.format( "%05d", sliceB ) + "-" + String.format( "%05d", sliceA ) + ".pointmatches"; if ( !p.clearCache ) candidates = deserializePointMatches( p, path ); if ( null == candidates ) { ArrayList< Feature > fs1 = deserializeFeatures( p.sift, p.outputPath + String.format( "%05d", sliceA ) + ".features" ); ArrayList< Feature > fs2 = deserializeFeatures( p.sift, p.outputPath + String.format( "%05d", sliceB ) + ".features" ); candidates = new ArrayList< PointMatch >( FloatArray2DSIFT.createMatches( fs2, fs1, p.rod ) ); if ( !serializePointMatches( p, candidates, path ) ) IJ.log( "Could not store point matches!" ); } AbstractModel< ? > model; switch ( p.modelIndex ) { case 0: model = new TranslationModel2D(); break; case 1: model = new RigidModel2D(); break; case 2: model = new SimilarityModel2D(); break; case 3: model = new AffineModel2D(); break; case 4: model = new HomographyModel2D(); break; default: return; } final ArrayList< PointMatch > inliers = new ArrayList< PointMatch >(); boolean modelFound; boolean again = false; try { do { modelFound = model.filterRansac( candidates, inliers, 1000, p.maxEpsilon, p.minInlierRatio, p.minNumInliers, 3 ); if ( modelFound && p.rejectIdentity ) { final ArrayList< Point > points = new ArrayList< Point >(); PointMatch.sourcePoints( inliers, points ); if ( Transforms.isIdentity( model, points, p.identityTolerance ) ) { IJ.log( "Identity transform for " + inliers.size() + " matches rejected." ); candidates.removeAll( inliers ); inliers.clear(); again = true; } } } while ( again ); } catch ( Exception e ) { modelFound = false; System.err.println( e.getMessage() ); } if ( modelFound ) { IJ.log( sliceB + " -> " + sliceA + ": " + inliers.size() + " corresponding features with an average displacement of " + PointMatch.meanDistance( inliers ) + "px identified." ); IJ.log( "Estimated transformation model: " + model ); models.set( ti, new Triple< Integer, Integer, AbstractModel< ? > >( sliceA, sliceB, model ) ); } else { IJ.log( sliceB + " -> " + sliceA + ": no correspondences found." ); return; } } }; threads.add( thread ); thread.start(); } try { for ( final Thread thread : threads ) thread.join(); } catch ( InterruptedException e ) { IJ.log( "Establishing feature correspondences interrupted." ); for ( final Thread thread : threads ) thread.interrupt(); try { for ( final Thread thread : threads ) thread.join(); } catch ( InterruptedException f ) {} return; } threads.clear(); /* collect successfully matches pairs and break the search on gaps */ for ( int t = 0; t < models.size(); ++t ) { final Triple< Integer, Integer, AbstractModel< ? > > pair = models.get( t ); if ( pair == null ) { if ( ++numFailures > p.maxNumFailures ) break J; } else { numFailures = 0; pairs.add( pair ); } } } } /* Elastic alignment */ /* Initialization */ final TileConfiguration initMeshes = new TileConfiguration(); final ArrayList< SpringMesh > meshes = new ArrayList< SpringMesh >( stack.getSize() ); for ( int i = 0; i < stack.getSize(); ++i ) meshes.add( new SpringMesh( p.resolutionSpringMesh, stack.getWidth(), stack.getHeight(), p.stiffnessSpringMesh, p.maxStretchSpringMesh, p.dampSpringMesh ) ); final int blockRadius = Math.max( 32, stack.getWidth() / p.resolutionSpringMesh / 2 ); /** TODO set this something more than the largest error by the approximate model */ final int searchRadius = Math.round( p.maxEpsilon ); for ( final Triple< Integer, Integer, AbstractModel< ? > > pair : pairs ) { final SpringMesh m1 = meshes.get( pair.a ); final SpringMesh m2 = meshes.get( pair.b ); ArrayList< PointMatch > pm12 = new ArrayList< PointMatch >(); ArrayList< PointMatch > pm21 = new ArrayList< PointMatch >(); final Collection< Vertex > v1 = m1.getVertices(); final Collection< Vertex > v2 = m2.getVertices(); final FloatProcessor ip1 = ( FloatProcessor )stack.getProcessor( pair.a + 1 ).convertToFloat().duplicate(); final FloatProcessor ip2 = ( FloatProcessor )stack.getProcessor( pair.b + 1 ).convertToFloat().duplicate(); final FloatProcessor ip1Mask; final FloatProcessor ip2Mask; if ( imp.getType() == ImagePlus.COLOR_RGB && p.mask ) { ip1Mask = createMask( stack.getProcessor( pair.a + 1 ) ); ip2Mask = createMask( stack.getProcessor( pair.b + 1 ) ); } else { ip1Mask = null; ip2Mask = null; } try { BlockMatching.matchByMaximalPMCC( ip1, ip2, ip1Mask, ip2Mask, Math.min( 1.0f, ( float )p.sectionScale ), ( ( InvertibleCoordinateTransform )pair.c ).createInverse(), blockRadius, blockRadius, searchRadius, searchRadius, p.minR, p.rodR, p.maxCurvatureR, v1, pm12, new ErrorStatistic( 1 ) ); } catch ( InterruptedException e ) { IJ.log( "Block matching interrupted." ); IJ.showProgress( 1.0 ); return; } if ( Thread.interrupted() ) { IJ.log( "Block matching interrupted." ); IJ.showProgress( 1.0 ); return; } IJ.log( pair.a + " > " + pair.b + ": found " + pm12.size() + " correspondences." ); /* <visualisation> */ // final List< Point > s1 = new ArrayList< Point >(); // PointMatch.sourcePoints( pm12, s1 ); // final ImagePlus imp1 = new ImagePlus( i + " >", ip1 ); // imp1.show(); // imp1.setOverlay( BlockMatching.illustrateMatches( pm12 ), Color.yellow, null ); // imp1.setRoi( Util.pointsToPointRoi( s1 ) ); // imp1.updateAndDraw(); /* </visualisation> */ try { BlockMatching.matchByMaximalPMCC( ip2, ip1, ip2Mask, ip1Mask, Math.min( 1.0f, ( float )p.sectionScale ), pair.c, blockRadius, blockRadius, searchRadius, searchRadius, p.minR, p.rodR, p.maxCurvatureR, v2, pm21, new ErrorStatistic( 1 ) ); } catch ( InterruptedException e ) { IJ.log( "Block matching interrupted." ); IJ.showProgress( 1.0 ); return; } if ( Thread.interrupted() ) { IJ.log( "Block matching interrupted." ); IJ.showProgress( 1.0 ); return; } IJ.log( pair.a + " < " + pair.b + ": found " + pm21.size() + " correspondences." ); /* <visualisation> */ // final List< Point > s2 = new ArrayList< Point >(); // PointMatch.sourcePoints( pm21, s2 ); // final ImagePlus imp2 = new ImagePlus( i + " <", ip2 ); // imp2.show(); // imp2.setOverlay( BlockMatching.illustrateMatches( pm21 ), Color.yellow, null ); // imp2.setRoi( Util.pointsToPointRoi( s2 ) ); // imp2.updateAndDraw(); /* </visualisation> */ final float springConstant = 1.0f / ( pair.b - pair.a ); IJ.log( pair.a + " <> " + pair.b + " spring constant = " + springConstant ); for ( final PointMatch pm : pm12 ) { final Vertex p1 = ( Vertex )pm.getP1(); final Vertex p2 = new Vertex( pm.getP2() ); p1.addSpring( p2, new Spring( 0, springConstant ) ); m2.addPassiveVertex( p2 ); } for ( final PointMatch pm : pm21 ) { final Vertex p1 = ( Vertex )pm.getP1(); final Vertex p2 = new Vertex( pm.getP2() ); p1.addSpring( p2, new Spring( 0, springConstant ) ); m1.addPassiveVertex( p2 ); } final Tile< ? > t1 = tiles.get( pair.a ); final Tile< ? > t2 = tiles.get( pair.b ); if ( pm12.size() > pair.c.getMinNumMatches() ) { initMeshes.addTile( t1 ); initMeshes.addTile( t2 ); t1.connect( t2, pm12 ); } if ( pm21.size() > pair.c.getMinNumMatches() ) { initMeshes.addTile( t1 ); initMeshes.addTile( t2 ); t2.connect( t1, pm21 ); } } /* pre-align by optimizing a piecewise linear model */ initMeshes.optimize( p.maxEpsilon, p.maxIterationsSpringMesh, p.maxPlateauwidthSpringMesh ); for ( int i = 0; i < stack.getSize(); ++i ) meshes.get( i ).init( tiles.get( i ).getModel() ); /* optimize the meshes */ try { long t0 = System.currentTimeMillis(); IJ.log("Optimizing spring meshes..."); SpringMesh.optimizeMeshes( meshes, p.maxEpsilon, p.maxIterationsSpringMesh, p.maxPlateauwidthSpringMesh, p.visualize ); IJ.log( "Done optimizing spring meshes. Took " + ( System.currentTimeMillis() - t0 ) + " ms" ); } catch ( NotEnoughDataPointsException e ) { IJ.log( "There were not enough data points to get the spring mesh optimizing." ); e.printStackTrace(); return; } /* calculate bounding box */ final float[] min = new float[ 2 ]; final float[] max = new float[ 2 ]; for ( final SpringMesh mesh : meshes ) { final float[] meshMin = new float[ 2 ]; final float[] meshMax = new float[ 2 ]; mesh.bounds( meshMin, meshMax ); Util.min( min, meshMin ); Util.max( max, meshMax ); } /* translate relative to bounding box */ for ( final SpringMesh mesh : meshes ) { for ( final Vertex vertex : mesh.getVertices() ) { final float[] w = vertex.getW(); w[ 0 ] -= min[ 0 ]; w[ 1 ] -= min[ 1 ]; } mesh.updateAffines(); mesh.updatePassiveVertices(); } final int width = ( int )Math.ceil( max[ 0 ] - min[ 0 ] ); final int height = ( int )Math.ceil( max[ 1 ] - min[ 1 ] ); for ( int i = 0; i < stack.getSize(); ++i ) { final int slice = i + 1; final MovingLeastSquaresTransform mlt = new MovingLeastSquaresTransform(); mlt.setModel( AffineModel2D.class ); mlt.setAlpha( 2.0f ); mlt.setMatches( meshes.get( i ).getVA().keySet() ); final TransformMeshMapping< CoordinateTransformMesh > mltMapping = new TransformMeshMapping< CoordinateTransformMesh >( new CoordinateTransformMesh( mlt, p.resolutionOutput, stack.getWidth(), stack.getHeight() ) ); final ImageProcessor ip = stack.getProcessor( slice ).createProcessor( width, height ); if ( p.interpolate ) { mltMapping.mapInterpolated( stack.getProcessor( slice ), ip ); } else { mltMapping.map( stack.getProcessor( slice ), ip ); } IJ.save( new ImagePlus( "elastic mlt " + i, ip ), p.outputPath + "elastic-" + String.format( "%05d", i ) + ".tif" ); } IJ.log( "Done." ); }
diff --git a/GAE/src/org/waterforpeople/mapping/dao/SurveyInstanceDAO.java b/GAE/src/org/waterforpeople/mapping/dao/SurveyInstanceDAO.java index 928bfd469..975ee083f 100644 --- a/GAE/src/org/waterforpeople/mapping/dao/SurveyInstanceDAO.java +++ b/GAE/src/org/waterforpeople/mapping/dao/SurveyInstanceDAO.java @@ -1,274 +1,274 @@ package org.waterforpeople.mapping.dao; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.jdo.PersistenceManager; import javax.jdo.Query; import org.waterforpeople.mapping.domain.QuestionAnswerStore; import org.waterforpeople.mapping.domain.Status.StatusCode; import org.waterforpeople.mapping.domain.SurveyInstance; import com.gallatinsystems.device.domain.DeviceFiles; import com.gallatinsystems.framework.dao.BaseDAO; import com.gallatinsystems.framework.servlet.PersistenceFilter; public class SurveyInstanceDAO extends BaseDAO<SurveyInstance> { private static HashMap<String, String> replaceList = new HashMap<String, String>(); private void loadReplaceList() { replaceList .put("Gravity Fed, Public Taps", "Gravity Fed - Public Taps"); replaceList.put( "Gravity Fed, Combination of Household and Public Taps", "Gravity Fed Combination of Household and Public Taps"); replaceList.put("Cyinzuzi, Budakiranya", "Cyinzuzi, Budakiranya"); } private static final Logger logger = Logger .getLogger(SurveyInstanceDAO.class.getName()); public SurveyInstance save(Date collectionDate, DeviceFiles deviceFile, Long userID, List<String> unparsedLines) { SurveyInstance si = new SurveyInstance(); boolean hasErrors = false; si.setDeviceFile(deviceFile); si.setUserID(userID); ArrayList<QuestionAnswerStore> qasList = new ArrayList<QuestionAnswerStore>(); for (String line : unparsedLines) { // Check for problem string Gravity Fed, Public Taps // for (Map.Entry<String, String> item : replaceList.entrySet()) { // if (line.contains(item.getKey())) // line = line.replace(item.getKey(), item.getValue()); // } String[] parts = line.split(","); //TODO: this will have to be removed when we use Strength and ScoredValue Questions while (parts.length > 9) { try { Date testDate = new Date(new Long(parts[7].trim())); break; } catch (Exception e) { - logger.log(Level.WARNING, - "Removing comma because 7th pos doesn't pass", e); + logger.log(Level.INFO, + "Removing comma because 7th pos doesn't pass got string: " + parts[7]+"instead of date"); } log.log(Level.SEVERE, "Has too many commas: " + line); int startIndex = 0; int iCount = 0; while((startIndex=line.indexOf(",", startIndex+1))!=-1){ if(iCount==4){ String firstPart = line.substring(0, startIndex); String secondPart = line.substring(startIndex+1, line.length()); line = firstPart + secondPart; break; } iCount++; } parts = line.split(","); } QuestionAnswerStore qas = new QuestionAnswerStore(); Date collDate = collectionDate; try { collDate = new Date(new Long(parts[7].trim())); } catch (Exception e) { logger.log(Level.WARNING, "Could not construct collection date", e); deviceFile .addProcessingMessage("Could not construct collection date from: " + parts[7]); hasErrors = true; } if (si.getSurveyId() == null) { try { si.setCollectionDate(collDate); si.setSurveyId(Long.parseLong(parts[0].trim())); si = save(si); } catch (NumberFormatException e) { logger.log(Level.SEVERE, "Could not parse survey id: " + parts[0], e); deviceFile .addProcessingMessage("Could not parse survey id: " + parts[0] + e.getMessage()); hasErrors = true; } } qas.setSurveyId(si.getSurveyId()); qas.setSurveyInstanceId(si.getKey().getId()); qas.setArbitratyNumber(new Long(parts[1].trim())); qas.setQuestionID(parts[2].trim()); qas.setType(parts[3].trim()); qas.setCollectionDate(collDate); if (parts.length > 4) { qas.setValue(parts[4].trim()); } if (parts.length >= 5) { if (si.getSubmitterName() == null) { si.setSubmitterName(parts[5].trim()); } } if (parts.length >= 9) { if (si.getDeviceIdentifier() == null) { si.setDeviceIdentifier(parts[8].trim()); } } if (parts.length >= 10) { qas.setScoredValue(parts[9].trim()); } if (parts.length >= 11) { qas.setStrength(parts[10].trim()); } qasList.add(qas); } save(qasList); deviceFile.setSurveyInstanceId(si.getKey().getId()); if (!hasErrors) { si.getDeviceFile().setProcessedStatus( StatusCode.PROCESSED_NO_ERRORS); } else { si.getDeviceFile().setProcessedStatus( StatusCode.PROCESSED_WITH_ERRORS); } si.setQuestionAnswersStore(qasList); return si; } public SurveyInstanceDAO() { super(SurveyInstance.class); //loadReplaceList(); } @SuppressWarnings("unchecked") public List<SurveyInstance> listByDateRange(Date beginDate, Date endDate, String cursorString) { PersistenceManager pm = PersistenceFilter.getManager(); javax.jdo.Query q = pm.newQuery(SurveyInstance.class); q.setFilter("collectionDate >= pBeginDate"); q.declareParameters("java.util.Date pBeginDate"); q.setOrdering("collectionDate desc"); prepareCursor(cursorString, q); return (List<SurveyInstance>) q.execute(beginDate); } /** * finds a questionAnswerStore object for the surveyInstance and questionId * passed in (if it exists) * * @param surveyInstanceId * @param questionId * @return */ @SuppressWarnings("unchecked") public QuestionAnswerStore findQuestionAnswerStoreForQuestion( Long surveyInstanceId, String questionId) { PersistenceManager pm = PersistenceFilter.getManager(); Query q = pm.newQuery(QuestionAnswerStore.class); q.setFilter("surveyInstanceId == surveyInstanceIdParam && questionID == questionIdParam"); q.declareParameters("Long surveyInstanceIdParam, String questionIdParam"); List<QuestionAnswerStore> result = (List<QuestionAnswerStore>) q .execute(surveyInstanceId, questionId); if (result != null && result.size() > 0) { return result.get(0); } else { return null; } } /** * lists all questionAnswerStore objects for a survey instance * * @param instanceId * @return */ @SuppressWarnings("unchecked") public List<QuestionAnswerStore> listQuestionAnswerStore(Long instanceId, Integer count) { PersistenceManager pm = PersistenceFilter.getManager(); Query q = pm.newQuery(QuestionAnswerStore.class); q.setFilter("surveyInstanceId == surveyInstanceIdParam"); q.declareParameters("Long surveyInstanceIdParam"); if (count != null) { q.setRange(0, count); } return (List<QuestionAnswerStore>) q.execute(instanceId); } @SuppressWarnings("unchecked") public List<QuestionAnswerStore> listQuestionAnswerStoreGeoQuestions( Long instanceId) { PersistenceManager pm = PersistenceFilter.getManager(); Query q = pm.newQuery(QuestionAnswerStore.class); q.setFilter("surveyInstanceId == surveyInstanceIdParam"); q.declareParameters("Long surveyInstanceIdParam"); q.setFilter("type=typeParam"); q.setFilter("String typeParam"); return (List<QuestionAnswerStore>) q.execute(instanceId, "GEO"); } /** * lists all questionAnswerStore objects for a specific question * * @param questionId * @return */ @SuppressWarnings("unchecked") public List<QuestionAnswerStore> listQuestionAnswerStoreForQuestion( String questionId, String cursorString) { PersistenceManager pm = PersistenceFilter.getManager(); javax.jdo.Query q = pm.newQuery(QuestionAnswerStore.class); q.setFilter("questionID == qidParam"); q.declareParameters("String qidParam"); prepareCursor(cursorString, q); return (List<QuestionAnswerStore>) q.execute(questionId); } /** * lists all surveyInstance records for a given survey * * @param surveyId * @return */ @SuppressWarnings("unchecked") public List<SurveyInstance> listSurveyInstanceBySurvey(Long surveyId, Integer count) { PersistenceManager pm = PersistenceFilter.getManager(); Query q = pm.newQuery(SurveyInstance.class); q.setFilter("surveyId == surveyIdParam"); q.declareParameters("Long surveyIdParam"); if (count != null) { q.setRange(0, count); } return (List<SurveyInstance>) q.execute(surveyId); } @SuppressWarnings("unchecked") public List<SurveyInstance> listSurveyInstanceBySurveyId(Long surveyId, String cursorString) { PersistenceManager pm = PersistenceFilter.getManager(); Query q = pm.newQuery(SurveyInstance.class); q.setFilter("surveyId == surveyIdParam"); q.declareParameters("Long surveyIdParam"); if (cursorString == null || !cursorString.equals("all")) { prepareCursor(cursorString, q); } List<SurveyInstance> siList = (List<SurveyInstance>) q .execute(surveyId); return siList; } }
true
true
public SurveyInstance save(Date collectionDate, DeviceFiles deviceFile, Long userID, List<String> unparsedLines) { SurveyInstance si = new SurveyInstance(); boolean hasErrors = false; si.setDeviceFile(deviceFile); si.setUserID(userID); ArrayList<QuestionAnswerStore> qasList = new ArrayList<QuestionAnswerStore>(); for (String line : unparsedLines) { // Check for problem string Gravity Fed, Public Taps // for (Map.Entry<String, String> item : replaceList.entrySet()) { // if (line.contains(item.getKey())) // line = line.replace(item.getKey(), item.getValue()); // } String[] parts = line.split(","); //TODO: this will have to be removed when we use Strength and ScoredValue Questions while (parts.length > 9) { try { Date testDate = new Date(new Long(parts[7].trim())); break; } catch (Exception e) { logger.log(Level.WARNING, "Removing comma because 7th pos doesn't pass", e); } log.log(Level.SEVERE, "Has too many commas: " + line); int startIndex = 0; int iCount = 0; while((startIndex=line.indexOf(",", startIndex+1))!=-1){ if(iCount==4){ String firstPart = line.substring(0, startIndex); String secondPart = line.substring(startIndex+1, line.length()); line = firstPart + secondPart; break; } iCount++; } parts = line.split(","); } QuestionAnswerStore qas = new QuestionAnswerStore(); Date collDate = collectionDate; try { collDate = new Date(new Long(parts[7].trim())); } catch (Exception e) { logger.log(Level.WARNING, "Could not construct collection date", e); deviceFile .addProcessingMessage("Could not construct collection date from: " + parts[7]); hasErrors = true; } if (si.getSurveyId() == null) { try { si.setCollectionDate(collDate); si.setSurveyId(Long.parseLong(parts[0].trim())); si = save(si); } catch (NumberFormatException e) { logger.log(Level.SEVERE, "Could not parse survey id: " + parts[0], e); deviceFile .addProcessingMessage("Could not parse survey id: " + parts[0] + e.getMessage()); hasErrors = true; } } qas.setSurveyId(si.getSurveyId()); qas.setSurveyInstanceId(si.getKey().getId()); qas.setArbitratyNumber(new Long(parts[1].trim())); qas.setQuestionID(parts[2].trim()); qas.setType(parts[3].trim()); qas.setCollectionDate(collDate); if (parts.length > 4) { qas.setValue(parts[4].trim()); } if (parts.length >= 5) { if (si.getSubmitterName() == null) { si.setSubmitterName(parts[5].trim()); } } if (parts.length >= 9) { if (si.getDeviceIdentifier() == null) { si.setDeviceIdentifier(parts[8].trim()); } } if (parts.length >= 10) { qas.setScoredValue(parts[9].trim()); } if (parts.length >= 11) { qas.setStrength(parts[10].trim()); } qasList.add(qas); } save(qasList); deviceFile.setSurveyInstanceId(si.getKey().getId()); if (!hasErrors) { si.getDeviceFile().setProcessedStatus( StatusCode.PROCESSED_NO_ERRORS); } else { si.getDeviceFile().setProcessedStatus( StatusCode.PROCESSED_WITH_ERRORS); } si.setQuestionAnswersStore(qasList); return si; }
public SurveyInstance save(Date collectionDate, DeviceFiles deviceFile, Long userID, List<String> unparsedLines) { SurveyInstance si = new SurveyInstance(); boolean hasErrors = false; si.setDeviceFile(deviceFile); si.setUserID(userID); ArrayList<QuestionAnswerStore> qasList = new ArrayList<QuestionAnswerStore>(); for (String line : unparsedLines) { // Check for problem string Gravity Fed, Public Taps // for (Map.Entry<String, String> item : replaceList.entrySet()) { // if (line.contains(item.getKey())) // line = line.replace(item.getKey(), item.getValue()); // } String[] parts = line.split(","); //TODO: this will have to be removed when we use Strength and ScoredValue Questions while (parts.length > 9) { try { Date testDate = new Date(new Long(parts[7].trim())); break; } catch (Exception e) { logger.log(Level.INFO, "Removing comma because 7th pos doesn't pass got string: " + parts[7]+"instead of date"); } log.log(Level.SEVERE, "Has too many commas: " + line); int startIndex = 0; int iCount = 0; while((startIndex=line.indexOf(",", startIndex+1))!=-1){ if(iCount==4){ String firstPart = line.substring(0, startIndex); String secondPart = line.substring(startIndex+1, line.length()); line = firstPart + secondPart; break; } iCount++; } parts = line.split(","); } QuestionAnswerStore qas = new QuestionAnswerStore(); Date collDate = collectionDate; try { collDate = new Date(new Long(parts[7].trim())); } catch (Exception e) { logger.log(Level.WARNING, "Could not construct collection date", e); deviceFile .addProcessingMessage("Could not construct collection date from: " + parts[7]); hasErrors = true; } if (si.getSurveyId() == null) { try { si.setCollectionDate(collDate); si.setSurveyId(Long.parseLong(parts[0].trim())); si = save(si); } catch (NumberFormatException e) { logger.log(Level.SEVERE, "Could not parse survey id: " + parts[0], e); deviceFile .addProcessingMessage("Could not parse survey id: " + parts[0] + e.getMessage()); hasErrors = true; } } qas.setSurveyId(si.getSurveyId()); qas.setSurveyInstanceId(si.getKey().getId()); qas.setArbitratyNumber(new Long(parts[1].trim())); qas.setQuestionID(parts[2].trim()); qas.setType(parts[3].trim()); qas.setCollectionDate(collDate); if (parts.length > 4) { qas.setValue(parts[4].trim()); } if (parts.length >= 5) { if (si.getSubmitterName() == null) { si.setSubmitterName(parts[5].trim()); } } if (parts.length >= 9) { if (si.getDeviceIdentifier() == null) { si.setDeviceIdentifier(parts[8].trim()); } } if (parts.length >= 10) { qas.setScoredValue(parts[9].trim()); } if (parts.length >= 11) { qas.setStrength(parts[10].trim()); } qasList.add(qas); } save(qasList); deviceFile.setSurveyInstanceId(si.getKey().getId()); if (!hasErrors) { si.getDeviceFile().setProcessedStatus( StatusCode.PROCESSED_NO_ERRORS); } else { si.getDeviceFile().setProcessedStatus( StatusCode.PROCESSED_WITH_ERRORS); } si.setQuestionAnswersStore(qasList); return si; }
diff --git a/src/test/java/org/bioinfo/infrared/core/dbsql/KaryotypeDBManagerTest.java b/src/test/java/org/bioinfo/infrared/core/dbsql/KaryotypeDBManagerTest.java index 4bce009..4f9ce00 100644 --- a/src/test/java/org/bioinfo/infrared/core/dbsql/KaryotypeDBManagerTest.java +++ b/src/test/java/org/bioinfo/infrared/core/dbsql/KaryotypeDBManagerTest.java @@ -1,49 +1,49 @@ package org.bioinfo.infrared.core.dbsql; import static org.junit.Assert.fail; import java.io.File; import java.util.List; import org.bioinfo.infrared.common.dbsql.DBConnector; import org.bioinfo.infrared.core.Chromosome; import org.junit.After; import org.junit.Before; import org.junit.Test; public class KaryotypeDBManagerTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testGetAllDBNames() { System.out.println("Test - 1"); try { - DBConnector man = new DBConnector("hsa"); + DBConnector man = new DBConnector(); KaryotypeDBManager dbMan = new KaryotypeDBManager(man); System.out.println("db connector = " + man); List<Chromosome> chromosomes = dbMan.getAllChromosomes(); for(int i=0;i<chromosomes.size(); i++) { System.out.println(" ---> " + chromosomes.get(i).toString()); } System.out.println(" -> " + chromosomes.size() + " chromosomes"); Chromosome chromosome = dbMan.getChromosomeById("9"); System.out.println(" -> " + chromosome); } catch (Exception e) { e.printStackTrace(); fail("Not yet implemented"); } } }
true
true
public void testGetAllDBNames() { System.out.println("Test - 1"); try { DBConnector man = new DBConnector("hsa"); KaryotypeDBManager dbMan = new KaryotypeDBManager(man); System.out.println("db connector = " + man); List<Chromosome> chromosomes = dbMan.getAllChromosomes(); for(int i=0;i<chromosomes.size(); i++) { System.out.println(" ---> " + chromosomes.get(i).toString()); } System.out.println(" -> " + chromosomes.size() + " chromosomes"); Chromosome chromosome = dbMan.getChromosomeById("9"); System.out.println(" -> " + chromosome); } catch (Exception e) { e.printStackTrace(); fail("Not yet implemented"); } }
public void testGetAllDBNames() { System.out.println("Test - 1"); try { DBConnector man = new DBConnector(); KaryotypeDBManager dbMan = new KaryotypeDBManager(man); System.out.println("db connector = " + man); List<Chromosome> chromosomes = dbMan.getAllChromosomes(); for(int i=0;i<chromosomes.size(); i++) { System.out.println(" ---> " + chromosomes.get(i).toString()); } System.out.println(" -> " + chromosomes.size() + " chromosomes"); Chromosome chromosome = dbMan.getChromosomeById("9"); System.out.println(" -> " + chromosome); } catch (Exception e) { e.printStackTrace(); fail("Not yet implemented"); } }
diff --git a/src/com/dj/antispam/MainActivity.java b/src/com/dj/antispam/MainActivity.java index a4b66a6..91865ae 100644 --- a/src/com/dj/antispam/MainActivity.java +++ b/src/com/dj/antispam/MainActivity.java @@ -1,317 +1,313 @@ package com.dj.antispam; import android.content.*; import android.database.Cursor; import android.graphics.Rect; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.*; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.TextView; import com.dj.antispam.actionbarcompat.ActionBarActivity; import com.dj.antispam.dao.DbHelper; import com.dj.antispam.dao.SmsDao; import java.text.DateFormat; import java.util.Date; public class MainActivity extends ActionBarActivity { private static final String TAG = MainActivity.class.getSimpleName(); private SmsDao dao; private Preferences prefs; private BroadcastReceiver updater; private Cursor cursor; private long lastViewed; @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_import: openImportActivity(); return true; } return false; } /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); dao = new SmsDao(this); prefs = new Preferences(this); lastViewed = prefs.getLastViewedTime(); setContentView(R.layout.main); final ListView list = (ListView)findViewById(R.id.listView); cursor = dao.getSpamCursor(); startManagingCursor(cursor); final CursorAdapter adapter = new CursorAdapter(getApplicationContext(), cursor, true) { @Override public View newView(Context context, Cursor cursor, ViewGroup viewGroup) { return getLayoutInflater().inflate(R.layout.sms_item, null, false); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView from = (TextView) view.findViewById(R.id.from); int colFrom = cursor.getColumnIndex(DbHelper.MESSAGES_FROM); String strFrom = cursor.getString(colFrom); from.setText(strFrom); TextView body = (TextView) view.findViewById(R.id.body); body.setText(cursor.getString(cursor.getColumnIndex(DbHelper.MESSAGES_BODY))); ((TextView)view.findViewById(R.id.date)).setText(formatTime(cursor.getLong(cursor.getColumnIndex(DbHelper.MESSAGES_DATETIME)))); if (cursor.getLong(cursor.getColumnIndex(DbHelper.MESSAGES_DATETIME)) < lastViewed) { body.setTextColor(getResources().getColor(R.color.read_body)); } else { body.setTextColor(getResources().getColor(R.color.unread_body)); } } private String formatTime(Long time) { return DateFormat.getDateTimeInstance().format(new Date(time)); } }; list.setAdapter(adapter); list.setOnTouchListener(new View.OnTouchListener() { private float downX; private int downPosition; private VelocityTracker velocityTracker; private final int slop; private final int minFlingVelocity; private final int maxFlingVelocity; private final int animationTime; private boolean swiping; private View swipingView = null; { ViewConfiguration vc = ViewConfiguration.get(list.getContext()); slop = vc.getScaledTouchSlop(); minFlingVelocity = vc.getScaledMinimumFlingVelocity(); maxFlingVelocity = vc.getScaledMaximumFlingVelocity(); animationTime = list.getContext().getResources().getInteger(android.R.integer.config_shortAnimTime); } @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: int[] coords = new int[2]; list.getLocationOnScreen(coords); swipingView = hitTest((int) (event.getRawX() - coords[0]), (int) (event.getRawY() - coords[1])); if (swipingView != null) { downX = event.getRawX(); downPosition = list.getPositionForView(swipingView); velocityTracker = VelocityTracker.obtain(); velocityTracker.addMovement(event); } break; case MotionEvent.ACTION_UP: if (velocityTracker == null) break; if (swipingView == null) break; float deltaX = event.getRawX() - downX; velocityTracker.addMovement(event); velocityTracker.computeCurrentVelocity(1000); float velocityX = Math.abs(velocityTracker.getXVelocity()); float velocityY = Math.abs(velocityTracker.getYVelocity()); boolean dismiss = false; boolean dismissRight = false; if (Math.abs(deltaX) > list.getWidth() / 2 && minFlingVelocity <= velocityX && velocityX <= maxFlingVelocity && velocityY < velocityX) { dismiss = true; dismissRight = deltaX > 0; } if (dismiss) { // dismiss final boolean fDismissRight = dismissRight; /* downView.animate() .translationX(dismissRight ? mViewWidth : -mViewWidth) .alpha(0) .setDuration(mAnimationTime) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { performDismiss(downView, downPosition); } }); */ TranslateAnimation ta = new TranslateAnimation(swipingView.getLeft(), fDismissRight ? swipingView.getLeft() + swipingView.getWidth() : swipingView.getLeft() - swipingView.getWidth(), 0, 0); ta.setDuration(animationTime); ta.setFillAfter(true); ta.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { new Thread(new Runnable() { @Override public void run() { if (fDismissRight) { onDeleteMessage(downPosition); } else { onRestoreMessage(downPosition); } updater.onReceive(getApplicationContext(), new Intent(getResources().getString(R.string.update_action))); } }).start(); } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }); swipingView.startAnimation(ta); } break; case MotionEvent.ACTION_MOVE: if (velocityTracker == null) { break; } velocityTracker.addMovement(event); float dX = event.getRawX() - downX; if (Math.abs(dX) > slop) { swiping = true; list.requestDisallowInterceptTouchEvent(true); // Cancel ListView's touch (un-highlighting the item) MotionEvent cancelEvent = MotionEvent.obtain(event); cancelEvent.setAction(MotionEvent.ACTION_CANCEL); list.onTouchEvent(cancelEvent); } break; default: return false; } return false; } private View hitTest(int x, int y) { View child; Rect rect = new Rect(); for (int i = 0; i < list.getChildCount(); i++) { child = list.getChildAt(i); child.getHitRect(rect); if (rect.contains(x, y)) { return child; } } return null; } private void onRestoreMessage(int nItem) { int id = getMessageId(nItem); restoreMessage(id); } private int getMessageId(int nItem) { Cursor cur = (Cursor)list.getAdapter().getItem(nItem); - try { - int col = cur.getColumnIndex("_id"); - return cur.getInt(col); - } finally { - cur.close(); - } + int col = cur.getColumnIndex("_id"); + return cur.getInt(col); } private void onDeleteMessage(int nItem) { int id = getMessageId(nItem); SmsModel message = dao.getMessage(id); dao.deleteMessage(id); dao.markSender(message.from, true); } }); updater = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "Update spam list intent has been received"); // Wait for record updated is complete or you'll get empty record stopManagingCursor(cursor); cursor = dao.getSpamCursor(); startManagingCursor(cursor); adapter.changeCursor(cursor); list.postInvalidate(); } }; importFromExistingMessages(); } private void importFromExistingMessages() { if (prefs.showImportActivity()) { openImportActivity(); prefs.setShowImportActivity(false); } } private void openImportActivity() { startActivityForResult(new Intent(this, ImportActivity.class), ImportActivity.FIRST_IMPORT); } @Override protected void onResume() { super.onResume(); registerReceiver(updater, new IntentFilter(getResources().getString(R.string.update_action))); } @Override protected void onPause() { super.onPause(); unregisterReceiver(updater); prefs.updateLastViewedTime(); } @Override protected void finalize() throws Throwable { super.finalize(); if (dao != null) { dao.close(); } } @Override protected void onActivityResult(int code, int result, Intent intent) { Log.d(TAG, "Activity has closed"); } private void restoreMessage(int messageId) { SmsModel message = dao.getMessage(messageId); ContentValues values = new ContentValues(); values.put(Utils.MESSAGE_ADDRESS, message.from); values.put(Utils.MESSAGE_BODY, message.body); values.put(Utils.MESSAGE_READ, true); values.put(Utils.MESSAGE_TYPE, Utils.MESSAGE_TYPE_SMS); values.put(Utils.MESSAGE_DATE, message.sentAt); getContentResolver().insert(Uri.parse(Utils.URI_INBOX), values); getContentResolver().delete(Uri.parse(Utils.URI_THREADS + "-1"), null, null); dao.deleteMessage(messageId); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); dao = new SmsDao(this); prefs = new Preferences(this); lastViewed = prefs.getLastViewedTime(); setContentView(R.layout.main); final ListView list = (ListView)findViewById(R.id.listView); cursor = dao.getSpamCursor(); startManagingCursor(cursor); final CursorAdapter adapter = new CursorAdapter(getApplicationContext(), cursor, true) { @Override public View newView(Context context, Cursor cursor, ViewGroup viewGroup) { return getLayoutInflater().inflate(R.layout.sms_item, null, false); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView from = (TextView) view.findViewById(R.id.from); int colFrom = cursor.getColumnIndex(DbHelper.MESSAGES_FROM); String strFrom = cursor.getString(colFrom); from.setText(strFrom); TextView body = (TextView) view.findViewById(R.id.body); body.setText(cursor.getString(cursor.getColumnIndex(DbHelper.MESSAGES_BODY))); ((TextView)view.findViewById(R.id.date)).setText(formatTime(cursor.getLong(cursor.getColumnIndex(DbHelper.MESSAGES_DATETIME)))); if (cursor.getLong(cursor.getColumnIndex(DbHelper.MESSAGES_DATETIME)) < lastViewed) { body.setTextColor(getResources().getColor(R.color.read_body)); } else { body.setTextColor(getResources().getColor(R.color.unread_body)); } } private String formatTime(Long time) { return DateFormat.getDateTimeInstance().format(new Date(time)); } }; list.setAdapter(adapter); list.setOnTouchListener(new View.OnTouchListener() { private float downX; private int downPosition; private VelocityTracker velocityTracker; private final int slop; private final int minFlingVelocity; private final int maxFlingVelocity; private final int animationTime; private boolean swiping; private View swipingView = null; { ViewConfiguration vc = ViewConfiguration.get(list.getContext()); slop = vc.getScaledTouchSlop(); minFlingVelocity = vc.getScaledMinimumFlingVelocity(); maxFlingVelocity = vc.getScaledMaximumFlingVelocity(); animationTime = list.getContext().getResources().getInteger(android.R.integer.config_shortAnimTime); } @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: int[] coords = new int[2]; list.getLocationOnScreen(coords); swipingView = hitTest((int) (event.getRawX() - coords[0]), (int) (event.getRawY() - coords[1])); if (swipingView != null) { downX = event.getRawX(); downPosition = list.getPositionForView(swipingView); velocityTracker = VelocityTracker.obtain(); velocityTracker.addMovement(event); } break; case MotionEvent.ACTION_UP: if (velocityTracker == null) break; if (swipingView == null) break; float deltaX = event.getRawX() - downX; velocityTracker.addMovement(event); velocityTracker.computeCurrentVelocity(1000); float velocityX = Math.abs(velocityTracker.getXVelocity()); float velocityY = Math.abs(velocityTracker.getYVelocity()); boolean dismiss = false; boolean dismissRight = false; if (Math.abs(deltaX) > list.getWidth() / 2 && minFlingVelocity <= velocityX && velocityX <= maxFlingVelocity && velocityY < velocityX) { dismiss = true; dismissRight = deltaX > 0; } if (dismiss) { // dismiss final boolean fDismissRight = dismissRight; /* downView.animate() .translationX(dismissRight ? mViewWidth : -mViewWidth) .alpha(0) .setDuration(mAnimationTime) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { performDismiss(downView, downPosition); } }); */ TranslateAnimation ta = new TranslateAnimation(swipingView.getLeft(), fDismissRight ? swipingView.getLeft() + swipingView.getWidth() : swipingView.getLeft() - swipingView.getWidth(), 0, 0); ta.setDuration(animationTime); ta.setFillAfter(true); ta.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { new Thread(new Runnable() { @Override public void run() { if (fDismissRight) { onDeleteMessage(downPosition); } else { onRestoreMessage(downPosition); } updater.onReceive(getApplicationContext(), new Intent(getResources().getString(R.string.update_action))); } }).start(); } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }); swipingView.startAnimation(ta); } break; case MotionEvent.ACTION_MOVE: if (velocityTracker == null) { break; } velocityTracker.addMovement(event); float dX = event.getRawX() - downX; if (Math.abs(dX) > slop) { swiping = true; list.requestDisallowInterceptTouchEvent(true); // Cancel ListView's touch (un-highlighting the item) MotionEvent cancelEvent = MotionEvent.obtain(event); cancelEvent.setAction(MotionEvent.ACTION_CANCEL); list.onTouchEvent(cancelEvent); } break; default: return false; } return false; } private View hitTest(int x, int y) { View child; Rect rect = new Rect(); for (int i = 0; i < list.getChildCount(); i++) { child = list.getChildAt(i); child.getHitRect(rect); if (rect.contains(x, y)) { return child; } } return null; } private void onRestoreMessage(int nItem) { int id = getMessageId(nItem); restoreMessage(id); } private int getMessageId(int nItem) { Cursor cur = (Cursor)list.getAdapter().getItem(nItem); try { int col = cur.getColumnIndex("_id"); return cur.getInt(col); } finally { cur.close(); } } private void onDeleteMessage(int nItem) { int id = getMessageId(nItem); SmsModel message = dao.getMessage(id); dao.deleteMessage(id); dao.markSender(message.from, true); } }); updater = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "Update spam list intent has been received"); // Wait for record updated is complete or you'll get empty record stopManagingCursor(cursor); cursor = dao.getSpamCursor(); startManagingCursor(cursor); adapter.changeCursor(cursor); list.postInvalidate(); } }; importFromExistingMessages(); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); dao = new SmsDao(this); prefs = new Preferences(this); lastViewed = prefs.getLastViewedTime(); setContentView(R.layout.main); final ListView list = (ListView)findViewById(R.id.listView); cursor = dao.getSpamCursor(); startManagingCursor(cursor); final CursorAdapter adapter = new CursorAdapter(getApplicationContext(), cursor, true) { @Override public View newView(Context context, Cursor cursor, ViewGroup viewGroup) { return getLayoutInflater().inflate(R.layout.sms_item, null, false); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView from = (TextView) view.findViewById(R.id.from); int colFrom = cursor.getColumnIndex(DbHelper.MESSAGES_FROM); String strFrom = cursor.getString(colFrom); from.setText(strFrom); TextView body = (TextView) view.findViewById(R.id.body); body.setText(cursor.getString(cursor.getColumnIndex(DbHelper.MESSAGES_BODY))); ((TextView)view.findViewById(R.id.date)).setText(formatTime(cursor.getLong(cursor.getColumnIndex(DbHelper.MESSAGES_DATETIME)))); if (cursor.getLong(cursor.getColumnIndex(DbHelper.MESSAGES_DATETIME)) < lastViewed) { body.setTextColor(getResources().getColor(R.color.read_body)); } else { body.setTextColor(getResources().getColor(R.color.unread_body)); } } private String formatTime(Long time) { return DateFormat.getDateTimeInstance().format(new Date(time)); } }; list.setAdapter(adapter); list.setOnTouchListener(new View.OnTouchListener() { private float downX; private int downPosition; private VelocityTracker velocityTracker; private final int slop; private final int minFlingVelocity; private final int maxFlingVelocity; private final int animationTime; private boolean swiping; private View swipingView = null; { ViewConfiguration vc = ViewConfiguration.get(list.getContext()); slop = vc.getScaledTouchSlop(); minFlingVelocity = vc.getScaledMinimumFlingVelocity(); maxFlingVelocity = vc.getScaledMaximumFlingVelocity(); animationTime = list.getContext().getResources().getInteger(android.R.integer.config_shortAnimTime); } @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: int[] coords = new int[2]; list.getLocationOnScreen(coords); swipingView = hitTest((int) (event.getRawX() - coords[0]), (int) (event.getRawY() - coords[1])); if (swipingView != null) { downX = event.getRawX(); downPosition = list.getPositionForView(swipingView); velocityTracker = VelocityTracker.obtain(); velocityTracker.addMovement(event); } break; case MotionEvent.ACTION_UP: if (velocityTracker == null) break; if (swipingView == null) break; float deltaX = event.getRawX() - downX; velocityTracker.addMovement(event); velocityTracker.computeCurrentVelocity(1000); float velocityX = Math.abs(velocityTracker.getXVelocity()); float velocityY = Math.abs(velocityTracker.getYVelocity()); boolean dismiss = false; boolean dismissRight = false; if (Math.abs(deltaX) > list.getWidth() / 2 && minFlingVelocity <= velocityX && velocityX <= maxFlingVelocity && velocityY < velocityX) { dismiss = true; dismissRight = deltaX > 0; } if (dismiss) { // dismiss final boolean fDismissRight = dismissRight; /* downView.animate() .translationX(dismissRight ? mViewWidth : -mViewWidth) .alpha(0) .setDuration(mAnimationTime) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { performDismiss(downView, downPosition); } }); */ TranslateAnimation ta = new TranslateAnimation(swipingView.getLeft(), fDismissRight ? swipingView.getLeft() + swipingView.getWidth() : swipingView.getLeft() - swipingView.getWidth(), 0, 0); ta.setDuration(animationTime); ta.setFillAfter(true); ta.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { new Thread(new Runnable() { @Override public void run() { if (fDismissRight) { onDeleteMessage(downPosition); } else { onRestoreMessage(downPosition); } updater.onReceive(getApplicationContext(), new Intent(getResources().getString(R.string.update_action))); } }).start(); } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }); swipingView.startAnimation(ta); } break; case MotionEvent.ACTION_MOVE: if (velocityTracker == null) { break; } velocityTracker.addMovement(event); float dX = event.getRawX() - downX; if (Math.abs(dX) > slop) { swiping = true; list.requestDisallowInterceptTouchEvent(true); // Cancel ListView's touch (un-highlighting the item) MotionEvent cancelEvent = MotionEvent.obtain(event); cancelEvent.setAction(MotionEvent.ACTION_CANCEL); list.onTouchEvent(cancelEvent); } break; default: return false; } return false; } private View hitTest(int x, int y) { View child; Rect rect = new Rect(); for (int i = 0; i < list.getChildCount(); i++) { child = list.getChildAt(i); child.getHitRect(rect); if (rect.contains(x, y)) { return child; } } return null; } private void onRestoreMessage(int nItem) { int id = getMessageId(nItem); restoreMessage(id); } private int getMessageId(int nItem) { Cursor cur = (Cursor)list.getAdapter().getItem(nItem); int col = cur.getColumnIndex("_id"); return cur.getInt(col); } private void onDeleteMessage(int nItem) { int id = getMessageId(nItem); SmsModel message = dao.getMessage(id); dao.deleteMessage(id); dao.markSender(message.from, true); } }); updater = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "Update spam list intent has been received"); // Wait for record updated is complete or you'll get empty record stopManagingCursor(cursor); cursor = dao.getSpamCursor(); startManagingCursor(cursor); adapter.changeCursor(cursor); list.postInvalidate(); } }; importFromExistingMessages(); }
diff --git a/src/gui/src/main/java/cz/filmtit/client/SubgestPopupStructure.java b/src/gui/src/main/java/cz/filmtit/client/SubgestPopupStructure.java index 1f77cdc3..fb12350c 100644 --- a/src/gui/src/main/java/cz/filmtit/client/SubgestPopupStructure.java +++ b/src/gui/src/main/java/cz/filmtit/client/SubgestPopupStructure.java @@ -1,44 +1,45 @@ package cz.filmtit.client; import com.github.gwtbootstrap.client.ui.Paragraph; import com.google.gwt.core.client.GWT; import com.google.gwt.i18n.client.NumberFormat; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; import cz.filmtit.share.TranslationPair; public class SubgestPopupStructure extends Composite { private static SubgestPopupStructureUiBinder uiBinder = GWT.create(SubgestPopupStructureUiBinder.class); interface SubgestPopupStructureUiBinder extends UiBinder<Widget, SubgestPopupStructure> { } public SubgestPopupStructure(TranslationPair value) { initWidget(uiBinder.createAndBindUi(this)); suggestionItemText.setText(value.getStringL2()); suggestionItemMatch.setText(value.getStringL1()); if (value.getScore() != null) { - suggestionItemScore.setText( "(" + NumberFormat.getPercentFormat().format(value.getScore()) + "%)" ); + suggestionItemScore.setStyleName("score_" + Math.round(value.getScore() * 10)); + suggestionItemScore.setText( "(" + NumberFormat.getPercentFormat().format(value.getScore()) + ")" ); } else { suggestionItemScore.setText("(score unknown)"); } suggestionItemSource.setText( "(source: " + value.getSource().getDescription() + ")"); } @UiField Paragraph suggestionItemText; @UiField Paragraph suggestionItemMatch; @UiField Paragraph suggestionItemScore; @UiField Paragraph suggestionItemSource; }
true
true
public SubgestPopupStructure(TranslationPair value) { initWidget(uiBinder.createAndBindUi(this)); suggestionItemText.setText(value.getStringL2()); suggestionItemMatch.setText(value.getStringL1()); if (value.getScore() != null) { suggestionItemScore.setText( "(" + NumberFormat.getPercentFormat().format(value.getScore()) + "%)" ); } else { suggestionItemScore.setText("(score unknown)"); } suggestionItemSource.setText( "(source: " + value.getSource().getDescription() + ")"); }
public SubgestPopupStructure(TranslationPair value) { initWidget(uiBinder.createAndBindUi(this)); suggestionItemText.setText(value.getStringL2()); suggestionItemMatch.setText(value.getStringL1()); if (value.getScore() != null) { suggestionItemScore.setStyleName("score_" + Math.round(value.getScore() * 10)); suggestionItemScore.setText( "(" + NumberFormat.getPercentFormat().format(value.getScore()) + ")" ); } else { suggestionItemScore.setText("(score unknown)"); } suggestionItemSource.setText( "(source: " + value.getSource().getDescription() + ")"); }
diff --git a/modules/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource1TestCase.java b/modules/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource1TestCase.java index 31acb471a..79e66dea6 100644 --- a/modules/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource1TestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource1TestCase.java @@ -1,144 +1,145 @@ /** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or 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 Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * 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.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.test.resource; import java.io.IOException; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.engine.Engine; import org.restlet.ext.jackson.JacksonConverter; import org.restlet.representation.StringRepresentation; import org.restlet.resource.ClientResource; import org.restlet.resource.Finder; import org.restlet.resource.ResourceException; import org.restlet.test.RestletTestCase; /** * Test the annotated resources, client and server sides. * * @author Jerome Louvel */ public class AnnotatedResource1TestCase extends RestletTestCase { private ClientResource clientResource; private MyResource1 myResource; protected void setUp() throws Exception { super.setUp(); Engine.getInstance().getRegisteredConverters().clear(); Engine.getInstance().getRegisteredConverters() .add(new JacksonConverter()); Engine.getInstance().registerDefaultConverters(); Finder finder = new Finder(); finder.setTargetClass(MyServerResource1.class); this.clientResource = new ClientResource("http://local"); this.clientResource.setNext(finder); this.myResource = clientResource.wrap(MyResource1.class); } @Override protected void tearDown() throws Exception { clientResource = null; myResource = null; super.tearDown(); } public void testDelete() { assertEquals("Done", myResource.remove()); } public void testGet() throws IOException, ResourceException { MyBean myBean = myResource.represent(); assertNotNull(myBean); assertEquals("myName", myBean.getName()); assertEquals("myDescription", myBean.getDescription()); String result = clientResource.get(MediaType.TEXT_XML).getText(); assertEquals( "<MyBean><description>myDescription</description><name>myName</name></MyBean>", result); result = clientResource.get(MediaType.APPLICATION_XML).getText(); assertEquals( "<MyBean><description>myDescription</description><name>myName</name></MyBean>", result); result = clientResource.get(MediaType.APPLICATION_ALL_XML).getText(); assertEquals( "<MyBean><description>myDescription</description><name>myName</name></MyBean>", result); result = clientResource.get(MediaType.APPLICATION_JSON).getText(); assertEquals("{\"description\":\"myDescription\",\"name\":\"myName\"}", result); result = clientResource.get(MediaType.APPLICATION_JAVA_OBJECT_XML) .getText(); assertTrue(result - .startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n<java version=\"")); + .startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") + && result.contains("<java version=\"")); } public void testOptions() { assertEquals("MyDescription", myResource.describe()); } public void testPost() { MyBean myBean = new MyBean("myName", "myDescription"); assertTrue(myResource.accept(myBean)); } public void testPut() throws ResourceException { // Get current representation MyBean myBean = myResource.represent(); assertNotNull(myBean); // Put new representation MyBean newBean = new MyBean("newName", "newDescription"); String result = myResource.store(newBean); assertEquals("Done", result); // Attempt to send an unknown entity try { clientResource.put(new StringRepresentation("wxyz", MediaType.APPLICATION_GNU_ZIP)); } catch (ResourceException re) { assertEquals(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE, re.getStatus()); } } }
true
true
public void testGet() throws IOException, ResourceException { MyBean myBean = myResource.represent(); assertNotNull(myBean); assertEquals("myName", myBean.getName()); assertEquals("myDescription", myBean.getDescription()); String result = clientResource.get(MediaType.TEXT_XML).getText(); assertEquals( "<MyBean><description>myDescription</description><name>myName</name></MyBean>", result); result = clientResource.get(MediaType.APPLICATION_XML).getText(); assertEquals( "<MyBean><description>myDescription</description><name>myName</name></MyBean>", result); result = clientResource.get(MediaType.APPLICATION_ALL_XML).getText(); assertEquals( "<MyBean><description>myDescription</description><name>myName</name></MyBean>", result); result = clientResource.get(MediaType.APPLICATION_JSON).getText(); assertEquals("{\"description\":\"myDescription\",\"name\":\"myName\"}", result); result = clientResource.get(MediaType.APPLICATION_JAVA_OBJECT_XML) .getText(); assertTrue(result .startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n<java version=\"")); }
public void testGet() throws IOException, ResourceException { MyBean myBean = myResource.represent(); assertNotNull(myBean); assertEquals("myName", myBean.getName()); assertEquals("myDescription", myBean.getDescription()); String result = clientResource.get(MediaType.TEXT_XML).getText(); assertEquals( "<MyBean><description>myDescription</description><name>myName</name></MyBean>", result); result = clientResource.get(MediaType.APPLICATION_XML).getText(); assertEquals( "<MyBean><description>myDescription</description><name>myName</name></MyBean>", result); result = clientResource.get(MediaType.APPLICATION_ALL_XML).getText(); assertEquals( "<MyBean><description>myDescription</description><name>myName</name></MyBean>", result); result = clientResource.get(MediaType.APPLICATION_JSON).getText(); assertEquals("{\"description\":\"myDescription\",\"name\":\"myName\"}", result); result = clientResource.get(MediaType.APPLICATION_JAVA_OBJECT_XML) .getText(); assertTrue(result .startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") && result.contains("<java version=\"")); }
diff --git a/ui/plugins/eu.esdihumboldt.hale.ui.views.properties/src/eu/esdihumboldt/hale/ui/views/properties/UriLink.java b/ui/plugins/eu.esdihumboldt.hale.ui.views.properties/src/eu/esdihumboldt/hale/ui/views/properties/UriLink.java index bab176b82..282a13ef6 100644 --- a/ui/plugins/eu.esdihumboldt.hale.ui.views.properties/src/eu/esdihumboldt/hale/ui/views/properties/UriLink.java +++ b/ui/plugins/eu.esdihumboldt.hale.ui.views.properties/src/eu/esdihumboldt/hale/ui/views/properties/UriLink.java @@ -1,127 +1,127 @@ /* * HUMBOLDT: A Framework for Data Harmonisation and Service Integration. * EU Integrated Project #030962 01.10.2006 - 30.09.2010 * * For more information on the project, please refer to the this web site: * http://www.esdi-humboldt.eu * * LICENSE: For information on the license under which this program is * available, please refer to http:/www.esdi-humboldt.eu/license.html#core * (c) the HUMBOLDT Consortium, 2007 to 2011. */ package eu.esdihumboldt.hale.ui.views.properties; import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Link; /** * Link class based on URIs * @author Patrick Lieb */ public class UriLink{ private SelectionAdapter adapter; private Link link; /** * Creates a {@link Link} based on an URI * @param parent a composite control which will be the parent of the new instance (cannot be null) * @param style the style of control to construct * @param uri the URI of the file * @param text the text which should be displayed */ public UriLink(Composite parent, int style, final URI uri, String text){ adapter = createDefaultSelectionAdapter(uri); link = new Link(parent, style); link.addSelectionListener(adapter); link.setText(text); } /** * Refresh the UriLink with the given URI * @param uri the URI of the of the file */ public void refresh(URI uri){ link.removeSelectionListener(adapter); if(uri == null) return; adapter = createDefaultSelectionAdapter(uri); link.addSelectionListener(adapter); } /** * @return the instance of a link */ public Link getLink(){ return link; } // create the the SelectionAdapter for the UriLink private SelectionAdapter createDefaultSelectionAdapter(final URI uri){ return new SelectionAdapter(){ private URI removeFragment(URI uri) throws URISyntaxException{ String uristring = uri.toString(); uristring = uristring.substring(0, uristring.indexOf("#")); return new URI(uristring); } // the URI has to be an existing file on the local drive or on a server @Override public void widgetSelected(SelectionEvent e) { URI newuri = uri; try { if(uri.getScheme().equals("http")){ try { Desktop.getDesktop().browse(uri); } catch (IOException e1) { - MessageDialog.openWarning(Display.getCurrent().getActiveShell(), "Opening Error", "No standard application is set!"); + MessageDialog.openWarning(Display.getCurrent().getActiveShell(), "Opening Error", "No default application set!"); } return; } if(uri.toString().contains("#")){ newuri = removeFragment(uri); } File file = new File(newuri); if(file.exists()){ try { Desktop.getDesktop().open(file); } catch (IOException e2) { try { Desktop.getDesktop().browse(newuri); } catch (IOException e1) { - MessageDialog.openWarning(Display.getCurrent().getActiveShell(), "Opening Error", "No standard application is set!"); + MessageDialog.openWarning(Display.getCurrent().getActiveShell(), "Opening Error", "No default application set!"); } } } else { try { Desktop.getDesktop().browse(newuri); } catch (IOException e1) { - MessageDialog.openWarning(Display.getCurrent().getActiveShell(), "Opening Error", "No standard application is set!"); + MessageDialog.openWarning(Display.getCurrent().getActiveShell(), "Opening Error", "No default application set!"); } } } catch (URISyntaxException e1) { // do nothing } } }; } /** * @param text the text to set */ public void setText(String text) { link.setText(text); } }
false
true
private SelectionAdapter createDefaultSelectionAdapter(final URI uri){ return new SelectionAdapter(){ private URI removeFragment(URI uri) throws URISyntaxException{ String uristring = uri.toString(); uristring = uristring.substring(0, uristring.indexOf("#")); return new URI(uristring); } // the URI has to be an existing file on the local drive or on a server @Override public void widgetSelected(SelectionEvent e) { URI newuri = uri; try { if(uri.getScheme().equals("http")){ try { Desktop.getDesktop().browse(uri); } catch (IOException e1) { MessageDialog.openWarning(Display.getCurrent().getActiveShell(), "Opening Error", "No standard application is set!"); } return; } if(uri.toString().contains("#")){ newuri = removeFragment(uri); } File file = new File(newuri); if(file.exists()){ try { Desktop.getDesktop().open(file); } catch (IOException e2) { try { Desktop.getDesktop().browse(newuri); } catch (IOException e1) { MessageDialog.openWarning(Display.getCurrent().getActiveShell(), "Opening Error", "No standard application is set!"); } } } else { try { Desktop.getDesktop().browse(newuri); } catch (IOException e1) { MessageDialog.openWarning(Display.getCurrent().getActiveShell(), "Opening Error", "No standard application is set!"); } } } catch (URISyntaxException e1) { // do nothing } } }; }
private SelectionAdapter createDefaultSelectionAdapter(final URI uri){ return new SelectionAdapter(){ private URI removeFragment(URI uri) throws URISyntaxException{ String uristring = uri.toString(); uristring = uristring.substring(0, uristring.indexOf("#")); return new URI(uristring); } // the URI has to be an existing file on the local drive or on a server @Override public void widgetSelected(SelectionEvent e) { URI newuri = uri; try { if(uri.getScheme().equals("http")){ try { Desktop.getDesktop().browse(uri); } catch (IOException e1) { MessageDialog.openWarning(Display.getCurrent().getActiveShell(), "Opening Error", "No default application set!"); } return; } if(uri.toString().contains("#")){ newuri = removeFragment(uri); } File file = new File(newuri); if(file.exists()){ try { Desktop.getDesktop().open(file); } catch (IOException e2) { try { Desktop.getDesktop().browse(newuri); } catch (IOException e1) { MessageDialog.openWarning(Display.getCurrent().getActiveShell(), "Opening Error", "No default application set!"); } } } else { try { Desktop.getDesktop().browse(newuri); } catch (IOException e1) { MessageDialog.openWarning(Display.getCurrent().getActiveShell(), "Opening Error", "No default application set!"); } } } catch (URISyntaxException e1) { // do nothing } } }; }
diff --git a/code/mlmq/src/ch/ethz/mlmq/scenario/impl/SimpleSendClient.java b/code/mlmq/src/ch/ethz/mlmq/scenario/impl/SimpleSendClient.java index 3b9c746..8d44426 100644 --- a/code/mlmq/src/ch/ethz/mlmq/scenario/impl/SimpleSendClient.java +++ b/code/mlmq/src/ch/ethz/mlmq/scenario/impl/SimpleSendClient.java @@ -1,61 +1,68 @@ package ch.ethz.mlmq.scenario.impl; import java.io.IOException; import java.util.logging.Logger; import ch.ethz.mlmq.client.ClientConfiguration; import ch.ethz.mlmq.dto.QueueDto; import ch.ethz.mlmq.logging.LoggerUtil; import ch.ethz.mlmq.scenario.ClientScenario; public class SimpleSendClient extends ClientScenario { private static final Logger logger = Logger.getLogger(SimpleSendClient.class.getSimpleName()); private static final String NUMMESSAGE_KEY = "scenario.SimpleSendClient.numMessages"; private static final String WAITBETWEENMESSAGES_KEY = "scenario.SimpleSendClient.waitTimeBetweenMessages"; private final int numMessages; private long waitTimeBetweenMessages; public SimpleSendClient(ClientConfiguration config) { super(config); numMessages = config.getIntConfig(NUMMESSAGE_KEY); waitTimeBetweenMessages = config.getLongConfig(WAITBETWEENMESSAGES_KEY); } @Override public void run() throws IOException { client.register(); String queueName = "QueueOf" + config.getName(); QueueDto queue = getOrCreateQueue(queueName); + // time when we started to send messages + long startTime = System.currentTimeMillis(); for (int i = 0; i < numMessages; i++) { byte[] content = ("Some Random Text and message Nr " + i).getBytes(); try { client.sendMessage(queue.getId(), content, i % 10); - Thread.sleep(waitTimeBetweenMessages); + long dt = System.currentTimeMillis() - startTime; + if (dt / waitTimeBetweenMessages <= i) { + long timeToSleep = waitTimeBetweenMessages - (dt % waitTimeBetweenMessages); + Thread.sleep(timeToSleep); + // else { We are behind in sending messages - don't sleep } + } } catch (IOException e) { logger.severe("IOEception while sending message - shutdown " + e + " " + LoggerUtil.getStackTraceString(e)); // stop sending messages in case of ioexception i = numMessages; } catch (Exception e) { logger.warning("Error while sending message " + e + " " + LoggerUtil.getStackTraceString(e)); } } } private QueueDto getOrCreateQueue(String queueName) throws IOException { try { return client.createQueue(queueName); } catch (Exception e) { logger.info("Queue " + queueName + " already exists try to lookup queue"); return client.lookupClientQueue(queueName); } } }
false
true
public void run() throws IOException { client.register(); String queueName = "QueueOf" + config.getName(); QueueDto queue = getOrCreateQueue(queueName); for (int i = 0; i < numMessages; i++) { byte[] content = ("Some Random Text and message Nr " + i).getBytes(); try { client.sendMessage(queue.getId(), content, i % 10); Thread.sleep(waitTimeBetweenMessages); } catch (IOException e) { logger.severe("IOEception while sending message - shutdown " + e + " " + LoggerUtil.getStackTraceString(e)); // stop sending messages in case of ioexception i = numMessages; } catch (Exception e) { logger.warning("Error while sending message " + e + " " + LoggerUtil.getStackTraceString(e)); } } }
public void run() throws IOException { client.register(); String queueName = "QueueOf" + config.getName(); QueueDto queue = getOrCreateQueue(queueName); // time when we started to send messages long startTime = System.currentTimeMillis(); for (int i = 0; i < numMessages; i++) { byte[] content = ("Some Random Text and message Nr " + i).getBytes(); try { client.sendMessage(queue.getId(), content, i % 10); long dt = System.currentTimeMillis() - startTime; if (dt / waitTimeBetweenMessages <= i) { long timeToSleep = waitTimeBetweenMessages - (dt % waitTimeBetweenMessages); Thread.sleep(timeToSleep); // else { We are behind in sending messages - don't sleep } } } catch (IOException e) { logger.severe("IOEception while sending message - shutdown " + e + " " + LoggerUtil.getStackTraceString(e)); // stop sending messages in case of ioexception i = numMessages; } catch (Exception e) { logger.warning("Error while sending message " + e + " " + LoggerUtil.getStackTraceString(e)); } } }
diff --git a/src/main/java/net/alpha01/jwtest/pages/requirement/RequirementPage.java b/src/main/java/net/alpha01/jwtest/pages/requirement/RequirementPage.java index 6693345..4e2ac8c 100644 --- a/src/main/java/net/alpha01/jwtest/pages/requirement/RequirementPage.java +++ b/src/main/java/net/alpha01/jwtest/pages/requirement/RequirementPage.java @@ -1,318 +1,320 @@ package net.alpha01.jwtest.pages.requirement; import java.math.BigDecimal; import java.math.BigInteger; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import net.alpha01.jwtest.JWTestSession; import net.alpha01.jwtest.beans.Project; import net.alpha01.jwtest.beans.Requirement; import net.alpha01.jwtest.beans.TestCase; import net.alpha01.jwtest.component.BookmarkablePageLinkSecure; import net.alpha01.jwtest.component.HtmlLabel; import net.alpha01.jwtest.dao.ProjectMapper; import net.alpha01.jwtest.dao.RequirementMapper; import net.alpha01.jwtest.dao.RequirementMapper.RequirementSelectSort; import net.alpha01.jwtest.dao.SqlConnection; import net.alpha01.jwtest.dao.SqlSessionMapper; import net.alpha01.jwtest.dao.TestCaseMapper; import net.alpha01.jwtest.dao.TestCaseMapper.TestCaseSelectSort; import net.alpha01.jwtest.jfreechart.BarChartImageResource; import net.alpha01.jwtest.pages.LayoutPage; import net.alpha01.jwtest.pages.dot.TestCaseDotPage; import net.alpha01.jwtest.pages.testcase.AddTestCasePage; import net.alpha01.jwtest.panels.ChartPanel; import net.alpha01.jwtest.panels.CloseablePanel; import net.alpha01.jwtest.panels.attachment.AttachmentPanel; import net.alpha01.jwtest.panels.testcase.TestCasesTablePanel; import net.alpha01.jwtest.util.JWTestUtil; import net.alpha01.jwtest.util.RequirementUtil; import net.alpha01.jwtest.util.TestCaseUtil; import org.apache.ibatis.exceptions.PersistenceException; import org.apache.wicket.authroles.authorization.strategies.role.Roles; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Button; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.SubmitLink; import org.apache.wicket.markup.html.image.ContextImage; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.panel.EmptyPanel; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.request.resource.DynamicImageResource; public class RequirementPage extends LayoutPage { private static final long serialVersionUID = 1L; private Requirement req; private Model<Requirement> destinationReqModel = new Model<Requirement>(); private HashMap<TestCase, Model<Boolean>> selectedTests = new HashMap<TestCase, Model<Boolean>>(); private Model<Project> destCopyMovePrjModel=new Model<Project>(); public RequirementPage(PageParameters params) { super(params); SqlSessionMapper<RequirementMapper> sesReqMapper = SqlConnection.getSessionMapper(RequirementMapper.class); req = sesReqMapper.getMapper().get(BigInteger.valueOf(params.get("idReq").toLong())); // LABELS add(new Label("requirementName", new PropertyModel<String>(req, "name"))); add(new HtmlLabel("requirementDescription", new PropertyModel<String>(req, "description"))); // LINK PageParameters reqParams = new PageParameters(); reqParams.add("idReq", req.getId().toString()); add(new BookmarkablePageLinkSecure<String>("addTestLnk", AddTestCasePage.class, reqParams,Roles.ADMIN,"PROJECT_ADMIN","MANAGER").add(new ContextImage("addTestImg", "images/add_test.png"))); add(new BookmarkablePageLinkSecure<String>("delRequirementLnk", DeleteRequirementPage.class, reqParams,Roles.ADMIN,"PROJECT_ADMIN","MANAGER").add(new ContextImage("deleteRequirementImg", "images/delete_requirement.png"))); add(new BookmarkablePageLinkSecure<String>("updRequirementLnk", UpdateRequirementPage.class, reqParams,Roles.ADMIN,"PROJECT_ADMIN","MANAGER").add(new ContextImage("updateRequirementImg", "images/update_requirement.png"))); //Copy/Move Form Form<Void> copyFrm=new Form<Void>("copyFrm"); //Retrieve all projects less current List<Project> allPrj = sesReqMapper.getSqlSession().getMapper(ProjectMapper.class).getAll(); allPrj.remove(JWTestSession.getProject()); DropDownChoice<Project> prjList = new DropDownChoice<Project>("prjList",destCopyMovePrjModel,allPrj); copyFrm.add(prjList); copyFrm.add(new SubmitLink("copyBtn"){ private static final long serialVersionUID = 1L; @Override public void onSubmit() { + BigInteger curReqID = req.getId(); SqlSessionMapper<RequirementMapper> sesMapper = SqlConnection.getSessionMapper(RequirementMapper.class); if (RequirementUtil.copyRequirement(req, destCopyMovePrjModel.getObject(), sesMapper)){ sesMapper.commit(); + setResponsePage(RequirementPage.class,new PageParameters().add("idReq", curReqID)); }else{ error("SQL Error"); sesMapper.rollback(); } } }); add(copyFrm); // GRAPHS HashMap<String, BigDecimal> dataValues = new HashMap<String, BigDecimal>(); TestCaseMapper testMapper = sesReqMapper.getSqlSession().getMapper(TestCaseMapper.class); Iterator<TestCase> itc = testMapper.getAllStat(new TestCaseSelectSort(req.getId(), "name", true)).iterator(); while (itc.hasNext()) { TestCase testC = itc.next(); if (testC.getNresults().intValue() > 0) { dataValues.put(testC.getName(), testC.getPercSuccess()); } } if (dataValues.size() > 0) { final DynamicImageResource resource = new BarChartImageResource("", dataValues, "TestCases", "Success", 600, 300); add (new CloseablePanel("chartPanel","Graph", false){ private static final long serialVersionUID = 1L; @Override public Panel getContentPanel(String id) { return new ChartPanel(id, resource); } }); } else { add(new EmptyPanel("chartPanel")); } final Model<Boolean> isAuthorized = JWTestUtil.isAuthorized(Roles.ADMIN, "PROJECT_ADMIN", "MANAGER"); //ATTACHMENTS TABLE final Model<AttachmentPanel> attachPanelModel=new Model<AttachmentPanel>(); CloseablePanel attachmentsPanel; add(attachmentsPanel = new CloseablePanel("attachmentsPanel",JWTestUtil.translate("attachments",this),false){ private static final long serialVersionUID = 1L; @Override public Panel getContentPanel(String id) { attachPanelModel.setObject(new AttachmentPanel(id, req, false, isAuthorized.getObject(), isAuthorized.getObject())); return attachPanelModel.getObject(); } }); if (attachPanelModel.getObject().getSize()==0){ attachmentsPanel.setVisible(false); } // TEST TABLE TestCasesTablePanel testsTable; if (isAuthorized.getObject()) { testsTable = new TestCasesTablePanel("testTable", req, 15, new Model<HashMap<TestCase, Model<Boolean>>>(selectedTests)); } else { testsTable = new TestCasesTablePanel("testTable", req, 15); } // SELECTION FORM Form<String> testsForm = new Form<String>("testsForm"); testsForm.add(testsTable); // DELETE BUTTON testsForm.add(new Button("deleteBtn") { private static final long serialVersionUID = -1664877195014185574L; @Override public boolean isVisible() { return isAuthorized.getObject(); } @Override public boolean isEnabled() { return isAuthorized.getObject(); } @Override public void onSubmit() { SqlSessionMapper<TestCaseMapper> sesTestMapper = SqlConnection.getSessionMapper(TestCaseMapper.class); Iterator<Entry<TestCase, Model<Boolean>>> itT = selectedTests.entrySet().iterator(); boolean sqlError = false; try { int nSelTest =0; while (itT.hasNext() && !sqlError) { Entry<TestCase, Model<Boolean>> testBool = itT.next(); if (testBool.getValue().getObject().booleanValue()) { nSelTest++; // delete test if (sesTestMapper.getMapper().delete(testBool.getKey()).equals(1)) { info("TestCase " + testBool.getKey().getName() + " deleted"); } else { // ERROR error("SQL ERROR in " + testBool.getKey().getName()); sqlError = true; } } } if (nSelTest==0){ warn(JWTestUtil.translate("testcase.not.selected",this)); } if (sqlError) { sesTestMapper.rollback(); } else { sesTestMapper.commit(); } } catch (PersistenceException e) { sesTestMapper.rollback(); } selectedTests.clear(); } }); // MOVE BUTTON List<Requirement> reqs = sesReqMapper.getMapper().getAll(new RequirementSelectSort(getSession().getCurrentProject().getId(), "name", true)); sesReqMapper.close(); testsForm.add(new Button("moveBtn") { private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return isAuthorized.getObject(); } @Override public boolean isEnabled() { return isAuthorized.getObject(); } @Override public void onSubmit() { if (destinationReqModel.getObject() == null) { error("Destination Requirement not selected"); return; } SqlSessionMapper<TestCaseMapper> sesTestMapper = SqlConnection.getSessionMapper(TestCaseMapper.class); Iterator<Entry<TestCase, Model<Boolean>>> itT = selectedTests.entrySet().iterator(); boolean sqlOk = true; try { while (itT.hasNext() && sqlOk) { Entry<TestCase, Model<Boolean>> testBool = itT.next(); if (testBool.getValue().getObject().booleanValue()) { // move test sqlOk&=TestCaseUtil.moveTestCase(testBool.getKey(), destinationReqModel.getObject(), sesTestMapper); } } if (!sqlOk) { error("SQL Error"); sesTestMapper.rollback(); } else { sesTestMapper.commit(); } } catch (PersistenceException e) { sesTestMapper.rollback(); } selectedTests.clear(); } }); //COPY BUTTON testsForm.add(new Button("copyBtn") { private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return isAuthorized.getObject(); } @Override public boolean isEnabled() { return isAuthorized.getObject(); } @Override public void onSubmit() { if (destinationReqModel.getObject() == null) { error("Destination Requirement not selected"); return; } SqlSessionMapper<TestCaseMapper> sesTestMapper = SqlConnection.getSessionMapper(TestCaseMapper.class); Iterator<Entry<TestCase, Model<Boolean>>> itT = selectedTests.entrySet().iterator(); boolean sqlOk = true; try { while (itT.hasNext() && sqlOk) { Entry<TestCase, Model<Boolean>> testBool = itT.next(); if (testBool.getValue().getObject().booleanValue()) { // copy test sqlOk&=TestCaseUtil.copyTestCase(testBool.getKey(), destinationReqModel.getObject(), sesTestMapper); } } if (!sqlOk) { sesTestMapper.rollback(); } else { sesTestMapper.commit(); } } catch (PersistenceException e) { sesTestMapper.rollback(); } selectedTests.clear(); } }); reqs.remove(req); DropDownChoice<Requirement> requirementsMoveList = new DropDownChoice<Requirement>("requirementsMoveList", destinationReqModel, reqs){ private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return isAuthorized.getObject(); } @Override public boolean isEnabled() { return isAuthorized.getObject(); } }; testsForm.add(requirementsMoveList); //DOT LINK testsForm.add(new BookmarkablePageLink<String>("dotGraphLnk",TestCaseDotPage.class,new PageParameters().add("idReq",req.getId()))); add(testsForm); } }
false
true
public RequirementPage(PageParameters params) { super(params); SqlSessionMapper<RequirementMapper> sesReqMapper = SqlConnection.getSessionMapper(RequirementMapper.class); req = sesReqMapper.getMapper().get(BigInteger.valueOf(params.get("idReq").toLong())); // LABELS add(new Label("requirementName", new PropertyModel<String>(req, "name"))); add(new HtmlLabel("requirementDescription", new PropertyModel<String>(req, "description"))); // LINK PageParameters reqParams = new PageParameters(); reqParams.add("idReq", req.getId().toString()); add(new BookmarkablePageLinkSecure<String>("addTestLnk", AddTestCasePage.class, reqParams,Roles.ADMIN,"PROJECT_ADMIN","MANAGER").add(new ContextImage("addTestImg", "images/add_test.png"))); add(new BookmarkablePageLinkSecure<String>("delRequirementLnk", DeleteRequirementPage.class, reqParams,Roles.ADMIN,"PROJECT_ADMIN","MANAGER").add(new ContextImage("deleteRequirementImg", "images/delete_requirement.png"))); add(new BookmarkablePageLinkSecure<String>("updRequirementLnk", UpdateRequirementPage.class, reqParams,Roles.ADMIN,"PROJECT_ADMIN","MANAGER").add(new ContextImage("updateRequirementImg", "images/update_requirement.png"))); //Copy/Move Form Form<Void> copyFrm=new Form<Void>("copyFrm"); //Retrieve all projects less current List<Project> allPrj = sesReqMapper.getSqlSession().getMapper(ProjectMapper.class).getAll(); allPrj.remove(JWTestSession.getProject()); DropDownChoice<Project> prjList = new DropDownChoice<Project>("prjList",destCopyMovePrjModel,allPrj); copyFrm.add(prjList); copyFrm.add(new SubmitLink("copyBtn"){ private static final long serialVersionUID = 1L; @Override public void onSubmit() { SqlSessionMapper<RequirementMapper> sesMapper = SqlConnection.getSessionMapper(RequirementMapper.class); if (RequirementUtil.copyRequirement(req, destCopyMovePrjModel.getObject(), sesMapper)){ sesMapper.commit(); }else{ error("SQL Error"); sesMapper.rollback(); } } }); add(copyFrm); // GRAPHS HashMap<String, BigDecimal> dataValues = new HashMap<String, BigDecimal>(); TestCaseMapper testMapper = sesReqMapper.getSqlSession().getMapper(TestCaseMapper.class); Iterator<TestCase> itc = testMapper.getAllStat(new TestCaseSelectSort(req.getId(), "name", true)).iterator(); while (itc.hasNext()) { TestCase testC = itc.next(); if (testC.getNresults().intValue() > 0) { dataValues.put(testC.getName(), testC.getPercSuccess()); } } if (dataValues.size() > 0) { final DynamicImageResource resource = new BarChartImageResource("", dataValues, "TestCases", "Success", 600, 300); add (new CloseablePanel("chartPanel","Graph", false){ private static final long serialVersionUID = 1L; @Override public Panel getContentPanel(String id) { return new ChartPanel(id, resource); } }); } else { add(new EmptyPanel("chartPanel")); } final Model<Boolean> isAuthorized = JWTestUtil.isAuthorized(Roles.ADMIN, "PROJECT_ADMIN", "MANAGER"); //ATTACHMENTS TABLE final Model<AttachmentPanel> attachPanelModel=new Model<AttachmentPanel>(); CloseablePanel attachmentsPanel; add(attachmentsPanel = new CloseablePanel("attachmentsPanel",JWTestUtil.translate("attachments",this),false){ private static final long serialVersionUID = 1L; @Override public Panel getContentPanel(String id) { attachPanelModel.setObject(new AttachmentPanel(id, req, false, isAuthorized.getObject(), isAuthorized.getObject())); return attachPanelModel.getObject(); } }); if (attachPanelModel.getObject().getSize()==0){ attachmentsPanel.setVisible(false); } // TEST TABLE TestCasesTablePanel testsTable; if (isAuthorized.getObject()) { testsTable = new TestCasesTablePanel("testTable", req, 15, new Model<HashMap<TestCase, Model<Boolean>>>(selectedTests)); } else { testsTable = new TestCasesTablePanel("testTable", req, 15); } // SELECTION FORM Form<String> testsForm = new Form<String>("testsForm"); testsForm.add(testsTable); // DELETE BUTTON testsForm.add(new Button("deleteBtn") { private static final long serialVersionUID = -1664877195014185574L; @Override public boolean isVisible() { return isAuthorized.getObject(); } @Override public boolean isEnabled() { return isAuthorized.getObject(); } @Override public void onSubmit() { SqlSessionMapper<TestCaseMapper> sesTestMapper = SqlConnection.getSessionMapper(TestCaseMapper.class); Iterator<Entry<TestCase, Model<Boolean>>> itT = selectedTests.entrySet().iterator(); boolean sqlError = false; try { int nSelTest =0; while (itT.hasNext() && !sqlError) { Entry<TestCase, Model<Boolean>> testBool = itT.next(); if (testBool.getValue().getObject().booleanValue()) { nSelTest++; // delete test if (sesTestMapper.getMapper().delete(testBool.getKey()).equals(1)) { info("TestCase " + testBool.getKey().getName() + " deleted"); } else { // ERROR error("SQL ERROR in " + testBool.getKey().getName()); sqlError = true; } } } if (nSelTest==0){ warn(JWTestUtil.translate("testcase.not.selected",this)); } if (sqlError) { sesTestMapper.rollback(); } else { sesTestMapper.commit(); } } catch (PersistenceException e) { sesTestMapper.rollback(); } selectedTests.clear(); } }); // MOVE BUTTON List<Requirement> reqs = sesReqMapper.getMapper().getAll(new RequirementSelectSort(getSession().getCurrentProject().getId(), "name", true)); sesReqMapper.close(); testsForm.add(new Button("moveBtn") { private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return isAuthorized.getObject(); } @Override public boolean isEnabled() { return isAuthorized.getObject(); } @Override public void onSubmit() { if (destinationReqModel.getObject() == null) { error("Destination Requirement not selected"); return; } SqlSessionMapper<TestCaseMapper> sesTestMapper = SqlConnection.getSessionMapper(TestCaseMapper.class); Iterator<Entry<TestCase, Model<Boolean>>> itT = selectedTests.entrySet().iterator(); boolean sqlOk = true; try { while (itT.hasNext() && sqlOk) { Entry<TestCase, Model<Boolean>> testBool = itT.next(); if (testBool.getValue().getObject().booleanValue()) { // move test sqlOk&=TestCaseUtil.moveTestCase(testBool.getKey(), destinationReqModel.getObject(), sesTestMapper); } } if (!sqlOk) { error("SQL Error"); sesTestMapper.rollback(); } else { sesTestMapper.commit(); } } catch (PersistenceException e) { sesTestMapper.rollback(); } selectedTests.clear(); } }); //COPY BUTTON testsForm.add(new Button("copyBtn") { private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return isAuthorized.getObject(); } @Override public boolean isEnabled() { return isAuthorized.getObject(); } @Override public void onSubmit() { if (destinationReqModel.getObject() == null) { error("Destination Requirement not selected"); return; } SqlSessionMapper<TestCaseMapper> sesTestMapper = SqlConnection.getSessionMapper(TestCaseMapper.class); Iterator<Entry<TestCase, Model<Boolean>>> itT = selectedTests.entrySet().iterator(); boolean sqlOk = true; try { while (itT.hasNext() && sqlOk) { Entry<TestCase, Model<Boolean>> testBool = itT.next(); if (testBool.getValue().getObject().booleanValue()) { // copy test sqlOk&=TestCaseUtil.copyTestCase(testBool.getKey(), destinationReqModel.getObject(), sesTestMapper); } } if (!sqlOk) { sesTestMapper.rollback(); } else { sesTestMapper.commit(); } } catch (PersistenceException e) { sesTestMapper.rollback(); } selectedTests.clear(); } }); reqs.remove(req); DropDownChoice<Requirement> requirementsMoveList = new DropDownChoice<Requirement>("requirementsMoveList", destinationReqModel, reqs){ private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return isAuthorized.getObject(); } @Override public boolean isEnabled() { return isAuthorized.getObject(); } }; testsForm.add(requirementsMoveList); //DOT LINK testsForm.add(new BookmarkablePageLink<String>("dotGraphLnk",TestCaseDotPage.class,new PageParameters().add("idReq",req.getId()))); add(testsForm); }
public RequirementPage(PageParameters params) { super(params); SqlSessionMapper<RequirementMapper> sesReqMapper = SqlConnection.getSessionMapper(RequirementMapper.class); req = sesReqMapper.getMapper().get(BigInteger.valueOf(params.get("idReq").toLong())); // LABELS add(new Label("requirementName", new PropertyModel<String>(req, "name"))); add(new HtmlLabel("requirementDescription", new PropertyModel<String>(req, "description"))); // LINK PageParameters reqParams = new PageParameters(); reqParams.add("idReq", req.getId().toString()); add(new BookmarkablePageLinkSecure<String>("addTestLnk", AddTestCasePage.class, reqParams,Roles.ADMIN,"PROJECT_ADMIN","MANAGER").add(new ContextImage("addTestImg", "images/add_test.png"))); add(new BookmarkablePageLinkSecure<String>("delRequirementLnk", DeleteRequirementPage.class, reqParams,Roles.ADMIN,"PROJECT_ADMIN","MANAGER").add(new ContextImage("deleteRequirementImg", "images/delete_requirement.png"))); add(new BookmarkablePageLinkSecure<String>("updRequirementLnk", UpdateRequirementPage.class, reqParams,Roles.ADMIN,"PROJECT_ADMIN","MANAGER").add(new ContextImage("updateRequirementImg", "images/update_requirement.png"))); //Copy/Move Form Form<Void> copyFrm=new Form<Void>("copyFrm"); //Retrieve all projects less current List<Project> allPrj = sesReqMapper.getSqlSession().getMapper(ProjectMapper.class).getAll(); allPrj.remove(JWTestSession.getProject()); DropDownChoice<Project> prjList = new DropDownChoice<Project>("prjList",destCopyMovePrjModel,allPrj); copyFrm.add(prjList); copyFrm.add(new SubmitLink("copyBtn"){ private static final long serialVersionUID = 1L; @Override public void onSubmit() { BigInteger curReqID = req.getId(); SqlSessionMapper<RequirementMapper> sesMapper = SqlConnection.getSessionMapper(RequirementMapper.class); if (RequirementUtil.copyRequirement(req, destCopyMovePrjModel.getObject(), sesMapper)){ sesMapper.commit(); setResponsePage(RequirementPage.class,new PageParameters().add("idReq", curReqID)); }else{ error("SQL Error"); sesMapper.rollback(); } } }); add(copyFrm); // GRAPHS HashMap<String, BigDecimal> dataValues = new HashMap<String, BigDecimal>(); TestCaseMapper testMapper = sesReqMapper.getSqlSession().getMapper(TestCaseMapper.class); Iterator<TestCase> itc = testMapper.getAllStat(new TestCaseSelectSort(req.getId(), "name", true)).iterator(); while (itc.hasNext()) { TestCase testC = itc.next(); if (testC.getNresults().intValue() > 0) { dataValues.put(testC.getName(), testC.getPercSuccess()); } } if (dataValues.size() > 0) { final DynamicImageResource resource = new BarChartImageResource("", dataValues, "TestCases", "Success", 600, 300); add (new CloseablePanel("chartPanel","Graph", false){ private static final long serialVersionUID = 1L; @Override public Panel getContentPanel(String id) { return new ChartPanel(id, resource); } }); } else { add(new EmptyPanel("chartPanel")); } final Model<Boolean> isAuthorized = JWTestUtil.isAuthorized(Roles.ADMIN, "PROJECT_ADMIN", "MANAGER"); //ATTACHMENTS TABLE final Model<AttachmentPanel> attachPanelModel=new Model<AttachmentPanel>(); CloseablePanel attachmentsPanel; add(attachmentsPanel = new CloseablePanel("attachmentsPanel",JWTestUtil.translate("attachments",this),false){ private static final long serialVersionUID = 1L; @Override public Panel getContentPanel(String id) { attachPanelModel.setObject(new AttachmentPanel(id, req, false, isAuthorized.getObject(), isAuthorized.getObject())); return attachPanelModel.getObject(); } }); if (attachPanelModel.getObject().getSize()==0){ attachmentsPanel.setVisible(false); } // TEST TABLE TestCasesTablePanel testsTable; if (isAuthorized.getObject()) { testsTable = new TestCasesTablePanel("testTable", req, 15, new Model<HashMap<TestCase, Model<Boolean>>>(selectedTests)); } else { testsTable = new TestCasesTablePanel("testTable", req, 15); } // SELECTION FORM Form<String> testsForm = new Form<String>("testsForm"); testsForm.add(testsTable); // DELETE BUTTON testsForm.add(new Button("deleteBtn") { private static final long serialVersionUID = -1664877195014185574L; @Override public boolean isVisible() { return isAuthorized.getObject(); } @Override public boolean isEnabled() { return isAuthorized.getObject(); } @Override public void onSubmit() { SqlSessionMapper<TestCaseMapper> sesTestMapper = SqlConnection.getSessionMapper(TestCaseMapper.class); Iterator<Entry<TestCase, Model<Boolean>>> itT = selectedTests.entrySet().iterator(); boolean sqlError = false; try { int nSelTest =0; while (itT.hasNext() && !sqlError) { Entry<TestCase, Model<Boolean>> testBool = itT.next(); if (testBool.getValue().getObject().booleanValue()) { nSelTest++; // delete test if (sesTestMapper.getMapper().delete(testBool.getKey()).equals(1)) { info("TestCase " + testBool.getKey().getName() + " deleted"); } else { // ERROR error("SQL ERROR in " + testBool.getKey().getName()); sqlError = true; } } } if (nSelTest==0){ warn(JWTestUtil.translate("testcase.not.selected",this)); } if (sqlError) { sesTestMapper.rollback(); } else { sesTestMapper.commit(); } } catch (PersistenceException e) { sesTestMapper.rollback(); } selectedTests.clear(); } }); // MOVE BUTTON List<Requirement> reqs = sesReqMapper.getMapper().getAll(new RequirementSelectSort(getSession().getCurrentProject().getId(), "name", true)); sesReqMapper.close(); testsForm.add(new Button("moveBtn") { private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return isAuthorized.getObject(); } @Override public boolean isEnabled() { return isAuthorized.getObject(); } @Override public void onSubmit() { if (destinationReqModel.getObject() == null) { error("Destination Requirement not selected"); return; } SqlSessionMapper<TestCaseMapper> sesTestMapper = SqlConnection.getSessionMapper(TestCaseMapper.class); Iterator<Entry<TestCase, Model<Boolean>>> itT = selectedTests.entrySet().iterator(); boolean sqlOk = true; try { while (itT.hasNext() && sqlOk) { Entry<TestCase, Model<Boolean>> testBool = itT.next(); if (testBool.getValue().getObject().booleanValue()) { // move test sqlOk&=TestCaseUtil.moveTestCase(testBool.getKey(), destinationReqModel.getObject(), sesTestMapper); } } if (!sqlOk) { error("SQL Error"); sesTestMapper.rollback(); } else { sesTestMapper.commit(); } } catch (PersistenceException e) { sesTestMapper.rollback(); } selectedTests.clear(); } }); //COPY BUTTON testsForm.add(new Button("copyBtn") { private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return isAuthorized.getObject(); } @Override public boolean isEnabled() { return isAuthorized.getObject(); } @Override public void onSubmit() { if (destinationReqModel.getObject() == null) { error("Destination Requirement not selected"); return; } SqlSessionMapper<TestCaseMapper> sesTestMapper = SqlConnection.getSessionMapper(TestCaseMapper.class); Iterator<Entry<TestCase, Model<Boolean>>> itT = selectedTests.entrySet().iterator(); boolean sqlOk = true; try { while (itT.hasNext() && sqlOk) { Entry<TestCase, Model<Boolean>> testBool = itT.next(); if (testBool.getValue().getObject().booleanValue()) { // copy test sqlOk&=TestCaseUtil.copyTestCase(testBool.getKey(), destinationReqModel.getObject(), sesTestMapper); } } if (!sqlOk) { sesTestMapper.rollback(); } else { sesTestMapper.commit(); } } catch (PersistenceException e) { sesTestMapper.rollback(); } selectedTests.clear(); } }); reqs.remove(req); DropDownChoice<Requirement> requirementsMoveList = new DropDownChoice<Requirement>("requirementsMoveList", destinationReqModel, reqs){ private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return isAuthorized.getObject(); } @Override public boolean isEnabled() { return isAuthorized.getObject(); } }; testsForm.add(requirementsMoveList); //DOT LINK testsForm.add(new BookmarkablePageLink<String>("dotGraphLnk",TestCaseDotPage.class,new PageParameters().add("idReq",req.getId()))); add(testsForm); }
diff --git a/src/net/sourceforge/schemaspy/Main.java b/src/net/sourceforge/schemaspy/Main.java index 0ad0dd2..b1e3002 100755 --- a/src/net/sourceforge/schemaspy/Main.java +++ b/src/net/sourceforge/schemaspy/Main.java @@ -1,738 +1,734 @@ package net.sourceforge.schemaspy; import java.io.*; import java.net.*; import java.sql.*; import java.util.*; import java.util.jar.*; //import javax.xml.parsers.*; //import org.w3c.dom.*; import net.sourceforge.schemaspy.model.*; import net.sourceforge.schemaspy.util.*; import net.sourceforge.schemaspy.view.*; public class Main { public static void main(String[] argv) { try { List args = new ArrayList(Arrays.asList(argv)); // can't mod the original if (args.size() == 0 || args.remove("-h") || args.remove("-?") || args.remove("?") || args.remove("/?")) { dumpUsage(null, false, false); System.exit(1); } if (args.remove("-help")) { dumpUsage(null, true, false); System.exit(1); } if (args.remove("-dbhelp")) { dumpUsage(null, true, true); System.exit(1); } long start = System.currentTimeMillis(); long startGraphingDetails = start; long startSummarizing = start; // allow '=' in param specs args = fixupArgs(args); final boolean generateHtml = !args.remove("-nohtml"); final boolean includeImpliedConstraints = !args.remove("-noimplied"); String outputDirName = getParam(args, "-o", true, false); // quoting command-line arguments sometimes leaves the trailing " if (outputDirName.endsWith("\"")) outputDirName = outputDirName.substring(0, outputDirName.length() - 1); File outputDir = new File(outputDirName).getCanonicalFile(); if (!outputDir.isDirectory()) { if (!outputDir.mkdir()) { System.err.println("Failed to create directory '" + outputDir + "'"); System.exit(2); } } if (generateHtml) { new File(outputDir, "tables").mkdir(); new File(outputDir, "graphs/summary").mkdirs(); } String dbType = getParam(args, "-t", false, false); if (dbType == null) dbType = "ora"; StringBuffer propertiesLoadedFrom = new StringBuffer(); Properties properties = getDbProperties(dbType, propertiesLoadedFrom); String user = getParam(args, "-u", true, false); String password = getParam(args, "-p", false, false); String schema = null; try { schema = getParam(args, "-s", false, true); } catch (Exception schemaNotSpecified) { } String classpath = getParam(args, "-cp", false, false); String css = getParam(args, "-css", false, false); if (css == null) css = "schemaSpy.css"; int maxDbThreads = getMaxDbThreads(args, properties); if (!args.remove("-nologo")) { // nasty hack, but passing this info everywhere churns my stomach System.setProperty("sourceforgelogo", "true"); } ConnectionURLBuilder urlBuilder = null; try { urlBuilder = new ConnectionURLBuilder(dbType, args, properties); } catch (IllegalArgumentException badParam) { System.err.println(badParam.getMessage()); System.exit(1); } String dbName = urlBuilder.getDbName(); if (args.size() != 0) { System.out.print("Warning: Unrecognized option(s):"); for (Iterator iter = args.iterator(); iter.hasNext(); ) { System.out.print(" " + iter.next()); } System.out.println(); } if (generateHtml) StyleSheet.init(new BufferedReader(getStyleSheet(css))); String driverClass = properties.getProperty("driver"); String driverPath = properties.getProperty("driverPath"); if (classpath != null) driverPath = classpath + File.pathSeparator + driverPath; Connection connection = getConnection(user, password, urlBuilder.getConnectionURL(), driverClass, driverPath, propertiesLoadedFrom.toString()); DatabaseMetaData meta = connection.getMetaData(); if (schema == null && meta.supportsSchemasInTableDefinitions()) { schema = user; } if (generateHtml) { System.out.println("Connected to " + meta.getDatabaseProductName() + " - " + meta.getDatabaseProductVersion()); System.out.println(); System.out.print("Gathering schema details"); } // // create the spy // SchemaSpy spy = new SchemaSpy(connection, meta, dbName, schema, properties, maxDbThreads); Database db = spy.getDatabase(); LineWriter out; Collection tables = new ArrayList(db.getTables()); tables.addAll(db.getViews()); if (tables.isEmpty()) { dumpNoTablesMessage(schema, user, meta); System.exit(2); } // DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // DocumentBuilder builder = factory.newDocumentBuilder(); // Document document = builder.newDocument(); // Element schemaNode = document.createElement("schema"); // document.appendChild(schemaNode); // if (schema != null) // DOMUtil.appendAttribute(schemaNode, "name", schema); // DOMUtil.appendAttribute(schemaNode, "databaseType", db.getDatabaseProduct()); if (generateHtml) { startSummarizing = System.currentTimeMillis(); System.out.println("(" + (startSummarizing - start) / 1000 + "sec)"); System.out.print("Writing/graphing summary"); System.out.print("."); File graphsDir = new File(outputDir, "graphs/summary"); String dotBaseFilespec = "relationships"; out = new LineWriter(new FileWriter(new File(graphsDir, dotBaseFilespec + ".real.compact.dot"))); WriteStats stats = DotFormatter.getInstance().writeRealRelationships(tables, true, out); boolean hasRelationships = stats.getNumTablesWritten() > 0 || stats.getNumViewsWritten() > 0; out.close(); if (hasRelationships) { System.out.print("."); out = new LineWriter(new FileWriter(new File(graphsDir, dotBaseFilespec + ".real.large.dot"))); DotFormatter.getInstance().writeRealRelationships(tables, false, out); out.close(); } // getting implied constraints has a side-effect of associating the parent/child tables, so don't do it // here unless they want that behavior List impliedConstraints = null; if (includeImpliedConstraints) impliedConstraints = DBAnalyzer.getImpliedConstraints(tables); else impliedConstraints = new ArrayList(); List orphans = DBAnalyzer.getOrphans(tables); boolean hasOrphans = !orphans.isEmpty() && Dot.getInstance().isValid(); if (hasRelationships) { System.out.print("."); File impliedDotFile = new File(graphsDir, dotBaseFilespec + ".implied.compact.dot"); out = new LineWriter(new FileWriter(impliedDotFile)); boolean hasImplied = DotFormatter.getInstance().writeAllRelationships(tables, true, out).wroteImplied(); out.close(); if (hasImplied) { impliedDotFile = new File(graphsDir, dotBaseFilespec + ".implied.large.dot"); out = new LineWriter(new FileWriter(impliedDotFile)); DotFormatter.getInstance().writeAllRelationships(tables, false, out); out.close(); } else { impliedDotFile.delete(); } out = new LineWriter(new FileWriter(new File(outputDir, dotBaseFilespec + ".html"))); hasRelationships = HtmlGraphFormatter.getInstance().write(db, graphsDir, dotBaseFilespec, hasOrphans, hasImplied, out); out.close(); } System.out.print("."); dotBaseFilespec = "utilities"; out = new LineWriter(new FileWriter(new File(outputDir, dotBaseFilespec + ".html"))); HtmlGraphFormatter.getInstance().writeOrphans(db, orphans, hasRelationships, graphsDir, out); out.close(); System.out.print("."); out = new LineWriter(new FileWriter(new File(outputDir, "index.html")), 64 * 1024); HtmlMainIndexFormatter.getInstance().write(db, tables, hasRelationships, hasOrphans, out); out.close(); System.out.print("."); List constraints = DBAnalyzer.getForeignKeyConstraints(tables); out = new LineWriter(new FileWriter(new File(outputDir, "constraints.html")), 256 * 1024); HtmlConstraintIndexFormatter constraintIndexFormatter = HtmlConstraintIndexFormatter.getInstance(); constraintIndexFormatter.write(db, constraints, tables, hasRelationships, hasOrphans, out); out.close(); System.out.print("."); out = new LineWriter(new FileWriter(new File(outputDir, "anomalies.html")), 16 * 1024); HtmlAnomaliesFormatter.getInstance().write(db, tables, impliedConstraints, hasRelationships, hasOrphans, out); out.close(); System.out.print("."); out = new LineWriter(new FileWriter(new File(outputDir, "columns.html")), 16 * 1024); HtmlColumnsFormatter.getInstance().write(db, tables, hasRelationships, hasOrphans, out); out.close(); startGraphingDetails = System.currentTimeMillis(); System.out.println("(" + (startGraphingDetails - startSummarizing) / 1000 + "sec)"); System.out.print("Writing/graphing results"); HtmlTableFormatter tableFormatter = HtmlTableFormatter.getInstance(); for (Iterator iter = tables.iterator(); iter.hasNext(); ) { System.out.print('.'); Table table = (Table)iter.next(); out = new LineWriter(new FileWriter(new File(outputDir, "tables/" + table.getName() + ".html")), 24 * 1024); tableFormatter.write(db, table, hasRelationships, hasOrphans, outputDir, out); out.close(); // XmlTableFormatter.getInstance().appendTable(schemaNode, table, outputDir); } out = new LineWriter(new FileWriter(new File(outputDir, "schemaSpy.css"))); StyleSheet.getInstance().write(out); out.close(); out = new LineWriter(new FileWriter(new File(outputDir, "schemaSpy.js"))); JavaScriptFormatter.getInstance().write(out); out.close(); } // out = new LineWriter(new FileWriter(new File(outputDir, "schemaSpy.xml")), 24 * 1024); // document.getDocumentElement().normalize(); // DOMUtil.printDOM(document, out); // out.close(); List recursiveConstraints = new ArrayList(); // side effect is that the RI relationships get trashed // also populates the recursiveConstraints collection List orderedTables = spy.sortTablesByRI(recursiveConstraints); out = new LineWriter(new FileWriter(new File(outputDir, "insertionOrder.txt")), 16 * 1024); TextFormatter.getInstance().write(db, orderedTables, false, out); out.close(); out = new LineWriter(new FileWriter(new File(outputDir, "deletionOrder.txt")), 16 * 1024); Collections.reverse(orderedTables); TextFormatter.getInstance().write(db, orderedTables, false, out); out.close(); /* we'll eventually want to put this functionality back in with a * database independent implementation File constraintsFile = new File(outputDir, "removeRecursiveConstraints.sql"); constraintsFile.delete(); if (!recursiveConstraints.isEmpty()) { out = new LineWriter(new FileWriter(constraintsFile), 4 * 1024); writeRemoveRecursiveConstraintsSql(recursiveConstraints, schema, out); out.close(); } constraintsFile = new File(outputDir, "restoreRecursiveConstraints.sql"); constraintsFile.delete(); if (!recursiveConstraints.isEmpty()) { out = new LineWriter(new FileWriter(constraintsFile), 4 * 1024); writeRestoreRecursiveConstraintsSql(recursiveConstraints, schema, out); out.close(); } */ if (generateHtml) { long end = System.currentTimeMillis(); System.out.println("(" + (end - startGraphingDetails) / 1000 + "sec)"); System.out.println("Wrote relationship details of " + tables.size() + " tables/views to directory '" + new File(outputDirName) + "' in " + (end - start) / 1000 + " seconds."); System.out.println("Start with " + new File(outputDirName, "index.html")); } - } catch (IllegalArgumentException badParam) { - System.err.println(); - badParam.printStackTrace(); - dumpUsage(badParam.getMessage(), false, false); } catch (Exception exc) { System.err.println(); exc.printStackTrace(); } } /** * getMaxDbThreads * * @param args List * @param properties Properties * @return int */ private static int getMaxDbThreads(List args, Properties properties) { int maxThreads = Integer.MAX_VALUE; String threads = properties.getProperty("dbThreads"); if (threads == null) threads = properties.getProperty("dbthreads"); if (threads != null) maxThreads = Integer.parseInt(threads); threads = getParam(args, "-dbThreads", false, false); if (threads == null) threads = getParam(args, "-dbthreads", false, false); if (threads != null) maxThreads = Integer.parseInt(threads); if (maxThreads < 0) maxThreads = Integer.MAX_VALUE; else if (maxThreads == 0) maxThreads = 1; return maxThreads; } /** * dumpNoDataMessage * * @param schema String * @param user String * @param meta DatabaseMetaData */ private static void dumpNoTablesMessage(String schema, String user, DatabaseMetaData meta) throws SQLException { System.out.println(); System.out.println(); System.out.println("No tables or views were found in schema " + schema + "."); List schemas = DBAnalyzer.getSchemas(meta); if (schemas.contains(schema)) { System.out.println("The schema exists in the database, but the user you specified '" + user + "'"); System.out.println(" might not have rights to read its contents."); } else { System.out.println("The schema does not exist in the database."); System.out.println("Make sure you specify a valid schema with the -s option and that the user"); System.out.println(" specified '" + user + "' can read from the schema."); System.out.println("Note that schema names are usually case sensitive."); } System.out.println(); System.out.println(schemas.size() + " schemas exist in this database."); System.out.println("Some of these \"schemas\" may be users or system schemas."); System.out.println(); Iterator iter = schemas.iterator(); while (iter.hasNext()) { System.out.print(iter.next() + " "); } System.out.println(); System.out.println(); System.out.println("These schemas contain tables/views that user '" + user + "' can see:"); System.out.println(); iter = DBAnalyzer.getPopulatedSchemas(meta).iterator(); while (iter.hasNext()) { System.out.print(iter.next() + " "); } } private static Connection getConnection(String user, String password, String connectionURL, String driverClass, String driverPath, String propertiesLoadedFrom) throws SQLException, MalformedURLException { System.out.println("Using database properties:"); System.out.println(" " + propertiesLoadedFrom); List classpath = new ArrayList(); StringTokenizer tokenizer = new StringTokenizer(driverPath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { File pathElement = new File(tokenizer.nextToken()); if (pathElement.exists()) classpath.add(pathElement.toURL()); } URLClassLoader loader = new URLClassLoader((URL[])classpath.toArray(new URL[0])); Driver driver = null; try { driver = (Driver)Class.forName(driverClass, true, loader).newInstance(); // have to use deprecated method or we won't see messages generated by older drivers //java.sql.DriverManager.setLogStream(System.err); } catch (Exception exc) { System.err.println(); System.err.println("Failed to load driver [" + driverClass + "] from classpath " + classpath); System.err.println(); System.err.println("Use -t [databaseType] to specify what drivers to use"); System.err.println("or modify one of the .properties from the jar, put it on your file"); System.err.println("system and point to it with -t [databasePropertiesFile]."); System.err.println(); System.err.println("For many people it's easiest to use the -cp option to directly specify"); System.err.println("where the database drivers exist (usually in a .jar or .zip/.Z)."); System.err.println(); exc.printStackTrace(); System.exit(1); } Properties connectionProperties = new Properties(); connectionProperties.put("user", user); if (password != null) connectionProperties.put("password", password); Connection connection = null; try { connection = driver.connect(connectionURL, connectionProperties); if (connection == null) { System.err.println(); System.err.println("Cannot connect to this database URL:"); System.err.println(" " + connectionURL); System.err.println("with this driver:"); System.err.println(" " + driverClass); System.err.println(); System.err.println("Additional connection information may be available in "); System.err.println(" " + propertiesLoadedFrom); System.exit(1); } } catch (UnsatisfiedLinkError badPath) { System.err.println(); System.err.println("Failed to load driver [" + driverClass + "] from classpath " + classpath); System.err.println(); System.err.println("Make sure the reported library (.dll/.lib/.so) from the following line can be"); System.err.println("found by your PATH (or LIB*PATH) environment variable"); System.err.println(); badPath.printStackTrace(); System.exit(1); } catch (Exception exc) { System.err.println(); System.err.println("Failed to connect to database URL [" + connectionURL + "]"); System.err.println(); exc.printStackTrace(); System.exit(1); } return connection; } /** * Currently very DB2-specific * @param recursiveConstraints List * @param schema String * @param out LineWriter * @throws IOException */ /* we'll eventually want to put this functionality back in with a * database independent implementation private static void writeRemoveRecursiveConstraintsSql(List recursiveConstraints, String schema, LineWriter out) throws IOException { for (Iterator iter = recursiveConstraints.iterator(); iter.hasNext(); ) { ForeignKeyConstraint constraint = (ForeignKeyConstraint)iter.next(); out.writeln("ALTER TABLE " + schema + "." + constraint.getChildTable() + " DROP CONSTRAINT " + constraint.getName() + ";"); } } */ /** * Currently very DB2-specific * @param recursiveConstraints List * @param schema String * @param out LineWriter * @throws IOException */ /* we'll eventually want to put this functionality back in with a * database independent implementation private static void writeRestoreRecursiveConstraintsSql(List recursiveConstraints, String schema, LineWriter out) throws IOException { Map ruleTextMapping = new HashMap(); ruleTextMapping.put(new Character('C'), "CASCADE"); ruleTextMapping.put(new Character('A'), "NO ACTION"); ruleTextMapping.put(new Character('N'), "NO ACTION"); // Oracle ruleTextMapping.put(new Character('R'), "RESTRICT"); ruleTextMapping.put(new Character('S'), "SET NULL"); // Oracle for (Iterator iter = recursiveConstraints.iterator(); iter.hasNext(); ) { ForeignKeyConstraint constraint = (ForeignKeyConstraint)iter.next(); out.write("ALTER TABLE \"" + schema + "\".\"" + constraint.getChildTable() + "\" ADD CONSTRAINT \"" + constraint.getName() + "\""); StringBuffer buf = new StringBuffer(); for (Iterator columnIter = constraint.getChildColumns().iterator(); columnIter.hasNext(); ) { buf.append("\""); buf.append(columnIter.next()); buf.append("\""); if (columnIter.hasNext()) buf.append(","); } out.write(" FOREIGN KEY (" + buf.toString() + ")"); out.write(" REFERENCES \"" + schema + "\".\"" + constraint.getParentTable() + "\""); buf = new StringBuffer(); for (Iterator columnIter = constraint.getParentColumns().iterator(); columnIter.hasNext(); ) { buf.append("\""); buf.append(columnIter.next()); buf.append("\""); if (columnIter.hasNext()) buf.append(","); } out.write(" (" + buf.toString() + ")"); out.write(" ON DELETE "); out.write(ruleTextMapping.get(new Character(constraint.getDeleteRule())).toString()); out.write(" ON UPDATE "); out.write(ruleTextMapping.get(new Character(constraint.getUpdateRule())).toString()); out.writeln(";"); } } */ private static void dumpUsage(String errorMessage, boolean detailed, boolean detailedDb) { if (errorMessage != null) { System.err.println("*** " + errorMessage + " ***"); } if (detailed) { System.out.println("SchemaSpy generates an HTML representation of a database's relationships."); System.out.println(); } if (!detailedDb) { System.out.println("Usage:"); System.out.println(" java -jar " + getLoadedFromJar() + " [options]"); System.out.println(" -t databaseType type of database - defaults to ora"); System.out.println(" use -dbhelp for a list of built-in types"); System.out.println(" -u user connect to the database with this user id"); System.out.println(" -s schema defaults to the specified user"); System.out.println(" -p password defaults to no password"); System.out.println(" -o outputDirectory directory to place the generated output in"); System.out.println(" -css styleSheet.css defaults to schemaSpy.css"); System.out.println(" -cp pathToDrivers optional - looks for drivers here before looking"); System.out.println(" in driverPath in [databaseType].properties"); System.out.println(" -dbthreads max concurrent threads when accessing metadata"); System.out.println(" defaults to -1 (no limit)"); System.out.println(" use 1 if you get 'already closed' type errors"); System.out.println(" -nohtml defaults to generate html"); System.out.println(" -noimplied defaults to generate implied relationships"); System.out.println(" -nologo don't put SourceForge logo on generated pages"); System.out.println(" (please don't disable unless absolutely necessary)"); System.out.println(" -help detailed help"); System.out.println(" -dbhelp display databaseType-specific help"); System.out.println(); System.out.println("Go to http://schemaspy.sourceforge.net for more details or the latest version."); System.out.println(); } if (!detailed) { System.out.println(" java -jar " + getLoadedFromJar() + " -help to display more detailed help"); System.out.println(); } if (detailedDb) { System.out.println("Built-in database types and their required connection parameters:"); Set datatypes = getBuiltInDatabaseTypes(getLoadedFromJar()); class DbPropLoader { Properties load(String dbType) { ResourceBundle bundle = ResourceBundle.getBundle(dbType); Properties properties; try { String baseDbType = bundle.getString("extends"); int lastSlash = dbType.lastIndexOf('/'); if (lastSlash != -1) baseDbType = dbType.substring(0, dbType.lastIndexOf("/") + 1) + baseDbType; properties = load(baseDbType); } catch (MissingResourceException doesntExtend) { properties = new Properties(); } return add(properties, bundle); } } for (Iterator iter = datatypes.iterator(); iter.hasNext(); ) { String dbType = iter.next().toString(); new ConnectionURLBuilder(dbType, null, new DbPropLoader().load(dbType)).dumpUsage(); } System.out.println(); } if (detailed || detailedDb) { System.out.println("You can use your own database types by specifying the filespec of a .properties file with -t."); System.out.println("Grab one out of " + getLoadedFromJar() + " and modify it to suit your needs."); System.out.println(); } if (detailed) { System.out.println("Sample usage using the default database type (implied -t ora):"); System.out.println(" java -jar schemaSpy.jar -db epdb -s sonedba -u devuser -p devuser -o output"); System.out.println(); } } public static String getLoadedFromJar() { String classpath = System.getProperty("java.class.path"); return new StringTokenizer(classpath, File.pathSeparator).nextToken(); } private static String getParam(List args, String paramId, boolean required, boolean dbTypeSpecific) { int paramIndex = args.indexOf(paramId); if (paramIndex < 0) { if (required) { dumpUsage("Parameter '" + paramId + "' missing." + (dbTypeSpecific ? " It is required for this database type." : ""), !dbTypeSpecific, dbTypeSpecific); System.exit(1); } else { return null; } } args.remove(paramIndex); String param = args.get(paramIndex).toString(); args.remove(paramIndex); return param; } /** * Allow an equal sign in args...like "-db=dbName" * * @param args List * @return List */ private static List fixupArgs(List args) { List expandedArgs = new ArrayList(); Iterator iter = args.iterator(); while (iter.hasNext()) { String arg = iter.next().toString(); int indexOfEquals = arg.indexOf('='); if (indexOfEquals != -1) { expandedArgs.add(arg.substring(0, indexOfEquals)); expandedArgs.add(arg.substring(indexOfEquals + 1)); } else { expandedArgs.add(arg); } } return expandedArgs; } private static Properties getDbProperties(String dbType, StringBuffer loadedFrom) throws IOException { ResourceBundle bundle = null; try { File propertiesFile = new File(dbType); bundle = new PropertyResourceBundle(new FileInputStream(propertiesFile)); loadedFrom.append(propertiesFile.getAbsolutePath()); } catch (FileNotFoundException notFoundOnFilesystemWithoutExtension) { try { File propertiesFile = new File(dbType + ".properties"); bundle = new PropertyResourceBundle(new FileInputStream(propertiesFile)); loadedFrom.append(propertiesFile.getAbsolutePath()); } catch (FileNotFoundException notFoundOnFilesystemWithExtensionTackedOn) { try { bundle = ResourceBundle.getBundle(dbType); loadedFrom.append("[" + getLoadedFromJar() + "]" + File.separator + dbType + ".properties"); } catch (Exception notInJarWithoutPath) { try { String path = SchemaSpy.class.getPackage().getName() + ".dbTypes." + dbType; path = path.replace('.', '/'); bundle = ResourceBundle.getBundle(path); loadedFrom.append("[" + getLoadedFromJar() + "]/" + path + ".properties"); } catch (Exception notInJar) { notInJar.printStackTrace(); notFoundOnFilesystemWithExtensionTackedOn.printStackTrace(); throw notFoundOnFilesystemWithoutExtension; } } } } Properties properties; try { String baseDbType = bundle.getString("extends"); properties = getDbProperties(baseDbType, new StringBuffer()); } catch (MissingResourceException doesntExtend) { properties = new Properties(); } return add(properties, bundle); } /** * Add the contents of <code>bundle</code> to the specified <code>properties</code>. * * @param properties Properties * @param bundle ResourceBundle * @return Properties */ private static Properties add(Properties properties, ResourceBundle bundle) { Enumeration iter = bundle.getKeys(); while (iter.hasMoreElements()) { Object key = iter.nextElement(); properties.put(key, bundle.getObject(key.toString())); } return properties; } public static Set getBuiltInDatabaseTypes(String loadedFromJar) { Set databaseTypes = new TreeSet(); JarInputStream jar = null; try { jar = new JarInputStream(new FileInputStream(loadedFromJar)); JarEntry entry; while ((entry = jar.getNextJarEntry()) != null) { String entryName = entry.getName(); int dotPropsIndex = entryName.indexOf(".properties"); if (dotPropsIndex != -1) databaseTypes.add(entryName.substring(0, dotPropsIndex)); } } catch (IOException exc) { } finally { try { jar.close(); } catch (Exception ignore) {} } return databaseTypes; } private static Reader getStyleSheet(String cssName) throws IOException { File cssFile = new File(cssName); if (cssFile.exists()) return new FileReader(cssFile); cssFile = new File(System.getProperty("user.dir"), cssName); if (cssFile.exists()) return new FileReader(cssFile); Reader css = new InputStreamReader(StyleSheet.class.getClassLoader().getResourceAsStream(cssName)); if (css == null) throw new IllegalStateException("Unable to find requested style sheet: " + cssName); return css; } }
true
true
public static void main(String[] argv) { try { List args = new ArrayList(Arrays.asList(argv)); // can't mod the original if (args.size() == 0 || args.remove("-h") || args.remove("-?") || args.remove("?") || args.remove("/?")) { dumpUsage(null, false, false); System.exit(1); } if (args.remove("-help")) { dumpUsage(null, true, false); System.exit(1); } if (args.remove("-dbhelp")) { dumpUsage(null, true, true); System.exit(1); } long start = System.currentTimeMillis(); long startGraphingDetails = start; long startSummarizing = start; // allow '=' in param specs args = fixupArgs(args); final boolean generateHtml = !args.remove("-nohtml"); final boolean includeImpliedConstraints = !args.remove("-noimplied"); String outputDirName = getParam(args, "-o", true, false); // quoting command-line arguments sometimes leaves the trailing " if (outputDirName.endsWith("\"")) outputDirName = outputDirName.substring(0, outputDirName.length() - 1); File outputDir = new File(outputDirName).getCanonicalFile(); if (!outputDir.isDirectory()) { if (!outputDir.mkdir()) { System.err.println("Failed to create directory '" + outputDir + "'"); System.exit(2); } } if (generateHtml) { new File(outputDir, "tables").mkdir(); new File(outputDir, "graphs/summary").mkdirs(); } String dbType = getParam(args, "-t", false, false); if (dbType == null) dbType = "ora"; StringBuffer propertiesLoadedFrom = new StringBuffer(); Properties properties = getDbProperties(dbType, propertiesLoadedFrom); String user = getParam(args, "-u", true, false); String password = getParam(args, "-p", false, false); String schema = null; try { schema = getParam(args, "-s", false, true); } catch (Exception schemaNotSpecified) { } String classpath = getParam(args, "-cp", false, false); String css = getParam(args, "-css", false, false); if (css == null) css = "schemaSpy.css"; int maxDbThreads = getMaxDbThreads(args, properties); if (!args.remove("-nologo")) { // nasty hack, but passing this info everywhere churns my stomach System.setProperty("sourceforgelogo", "true"); } ConnectionURLBuilder urlBuilder = null; try { urlBuilder = new ConnectionURLBuilder(dbType, args, properties); } catch (IllegalArgumentException badParam) { System.err.println(badParam.getMessage()); System.exit(1); } String dbName = urlBuilder.getDbName(); if (args.size() != 0) { System.out.print("Warning: Unrecognized option(s):"); for (Iterator iter = args.iterator(); iter.hasNext(); ) { System.out.print(" " + iter.next()); } System.out.println(); } if (generateHtml) StyleSheet.init(new BufferedReader(getStyleSheet(css))); String driverClass = properties.getProperty("driver"); String driverPath = properties.getProperty("driverPath"); if (classpath != null) driverPath = classpath + File.pathSeparator + driverPath; Connection connection = getConnection(user, password, urlBuilder.getConnectionURL(), driverClass, driverPath, propertiesLoadedFrom.toString()); DatabaseMetaData meta = connection.getMetaData(); if (schema == null && meta.supportsSchemasInTableDefinitions()) { schema = user; } if (generateHtml) { System.out.println("Connected to " + meta.getDatabaseProductName() + " - " + meta.getDatabaseProductVersion()); System.out.println(); System.out.print("Gathering schema details"); } // // create the spy // SchemaSpy spy = new SchemaSpy(connection, meta, dbName, schema, properties, maxDbThreads); Database db = spy.getDatabase(); LineWriter out; Collection tables = new ArrayList(db.getTables()); tables.addAll(db.getViews()); if (tables.isEmpty()) { dumpNoTablesMessage(schema, user, meta); System.exit(2); } // DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // DocumentBuilder builder = factory.newDocumentBuilder(); // Document document = builder.newDocument(); // Element schemaNode = document.createElement("schema"); // document.appendChild(schemaNode); // if (schema != null) // DOMUtil.appendAttribute(schemaNode, "name", schema); // DOMUtil.appendAttribute(schemaNode, "databaseType", db.getDatabaseProduct()); if (generateHtml) { startSummarizing = System.currentTimeMillis(); System.out.println("(" + (startSummarizing - start) / 1000 + "sec)"); System.out.print("Writing/graphing summary"); System.out.print("."); File graphsDir = new File(outputDir, "graphs/summary"); String dotBaseFilespec = "relationships"; out = new LineWriter(new FileWriter(new File(graphsDir, dotBaseFilespec + ".real.compact.dot"))); WriteStats stats = DotFormatter.getInstance().writeRealRelationships(tables, true, out); boolean hasRelationships = stats.getNumTablesWritten() > 0 || stats.getNumViewsWritten() > 0; out.close(); if (hasRelationships) { System.out.print("."); out = new LineWriter(new FileWriter(new File(graphsDir, dotBaseFilespec + ".real.large.dot"))); DotFormatter.getInstance().writeRealRelationships(tables, false, out); out.close(); } // getting implied constraints has a side-effect of associating the parent/child tables, so don't do it // here unless they want that behavior List impliedConstraints = null; if (includeImpliedConstraints) impliedConstraints = DBAnalyzer.getImpliedConstraints(tables); else impliedConstraints = new ArrayList(); List orphans = DBAnalyzer.getOrphans(tables); boolean hasOrphans = !orphans.isEmpty() && Dot.getInstance().isValid(); if (hasRelationships) { System.out.print("."); File impliedDotFile = new File(graphsDir, dotBaseFilespec + ".implied.compact.dot"); out = new LineWriter(new FileWriter(impliedDotFile)); boolean hasImplied = DotFormatter.getInstance().writeAllRelationships(tables, true, out).wroteImplied(); out.close(); if (hasImplied) { impliedDotFile = new File(graphsDir, dotBaseFilespec + ".implied.large.dot"); out = new LineWriter(new FileWriter(impliedDotFile)); DotFormatter.getInstance().writeAllRelationships(tables, false, out); out.close(); } else { impliedDotFile.delete(); } out = new LineWriter(new FileWriter(new File(outputDir, dotBaseFilespec + ".html"))); hasRelationships = HtmlGraphFormatter.getInstance().write(db, graphsDir, dotBaseFilespec, hasOrphans, hasImplied, out); out.close(); } System.out.print("."); dotBaseFilespec = "utilities"; out = new LineWriter(new FileWriter(new File(outputDir, dotBaseFilespec + ".html"))); HtmlGraphFormatter.getInstance().writeOrphans(db, orphans, hasRelationships, graphsDir, out); out.close(); System.out.print("."); out = new LineWriter(new FileWriter(new File(outputDir, "index.html")), 64 * 1024); HtmlMainIndexFormatter.getInstance().write(db, tables, hasRelationships, hasOrphans, out); out.close(); System.out.print("."); List constraints = DBAnalyzer.getForeignKeyConstraints(tables); out = new LineWriter(new FileWriter(new File(outputDir, "constraints.html")), 256 * 1024); HtmlConstraintIndexFormatter constraintIndexFormatter = HtmlConstraintIndexFormatter.getInstance(); constraintIndexFormatter.write(db, constraints, tables, hasRelationships, hasOrphans, out); out.close(); System.out.print("."); out = new LineWriter(new FileWriter(new File(outputDir, "anomalies.html")), 16 * 1024); HtmlAnomaliesFormatter.getInstance().write(db, tables, impliedConstraints, hasRelationships, hasOrphans, out); out.close(); System.out.print("."); out = new LineWriter(new FileWriter(new File(outputDir, "columns.html")), 16 * 1024); HtmlColumnsFormatter.getInstance().write(db, tables, hasRelationships, hasOrphans, out); out.close(); startGraphingDetails = System.currentTimeMillis(); System.out.println("(" + (startGraphingDetails - startSummarizing) / 1000 + "sec)"); System.out.print("Writing/graphing results"); HtmlTableFormatter tableFormatter = HtmlTableFormatter.getInstance(); for (Iterator iter = tables.iterator(); iter.hasNext(); ) { System.out.print('.'); Table table = (Table)iter.next(); out = new LineWriter(new FileWriter(new File(outputDir, "tables/" + table.getName() + ".html")), 24 * 1024); tableFormatter.write(db, table, hasRelationships, hasOrphans, outputDir, out); out.close(); // XmlTableFormatter.getInstance().appendTable(schemaNode, table, outputDir); } out = new LineWriter(new FileWriter(new File(outputDir, "schemaSpy.css"))); StyleSheet.getInstance().write(out); out.close(); out = new LineWriter(new FileWriter(new File(outputDir, "schemaSpy.js"))); JavaScriptFormatter.getInstance().write(out); out.close(); } // out = new LineWriter(new FileWriter(new File(outputDir, "schemaSpy.xml")), 24 * 1024); // document.getDocumentElement().normalize(); // DOMUtil.printDOM(document, out); // out.close(); List recursiveConstraints = new ArrayList(); // side effect is that the RI relationships get trashed // also populates the recursiveConstraints collection List orderedTables = spy.sortTablesByRI(recursiveConstraints); out = new LineWriter(new FileWriter(new File(outputDir, "insertionOrder.txt")), 16 * 1024); TextFormatter.getInstance().write(db, orderedTables, false, out); out.close(); out = new LineWriter(new FileWriter(new File(outputDir, "deletionOrder.txt")), 16 * 1024); Collections.reverse(orderedTables); TextFormatter.getInstance().write(db, orderedTables, false, out); out.close(); /* we'll eventually want to put this functionality back in with a * database independent implementation File constraintsFile = new File(outputDir, "removeRecursiveConstraints.sql"); constraintsFile.delete(); if (!recursiveConstraints.isEmpty()) { out = new LineWriter(new FileWriter(constraintsFile), 4 * 1024); writeRemoveRecursiveConstraintsSql(recursiveConstraints, schema, out); out.close(); } constraintsFile = new File(outputDir, "restoreRecursiveConstraints.sql"); constraintsFile.delete(); if (!recursiveConstraints.isEmpty()) { out = new LineWriter(new FileWriter(constraintsFile), 4 * 1024); writeRestoreRecursiveConstraintsSql(recursiveConstraints, schema, out); out.close(); } */ if (generateHtml) { long end = System.currentTimeMillis(); System.out.println("(" + (end - startGraphingDetails) / 1000 + "sec)"); System.out.println("Wrote relationship details of " + tables.size() + " tables/views to directory '" + new File(outputDirName) + "' in " + (end - start) / 1000 + " seconds."); System.out.println("Start with " + new File(outputDirName, "index.html")); } } catch (IllegalArgumentException badParam) { System.err.println(); badParam.printStackTrace(); dumpUsage(badParam.getMessage(), false, false); } catch (Exception exc) { System.err.println(); exc.printStackTrace(); } }
public static void main(String[] argv) { try { List args = new ArrayList(Arrays.asList(argv)); // can't mod the original if (args.size() == 0 || args.remove("-h") || args.remove("-?") || args.remove("?") || args.remove("/?")) { dumpUsage(null, false, false); System.exit(1); } if (args.remove("-help")) { dumpUsage(null, true, false); System.exit(1); } if (args.remove("-dbhelp")) { dumpUsage(null, true, true); System.exit(1); } long start = System.currentTimeMillis(); long startGraphingDetails = start; long startSummarizing = start; // allow '=' in param specs args = fixupArgs(args); final boolean generateHtml = !args.remove("-nohtml"); final boolean includeImpliedConstraints = !args.remove("-noimplied"); String outputDirName = getParam(args, "-o", true, false); // quoting command-line arguments sometimes leaves the trailing " if (outputDirName.endsWith("\"")) outputDirName = outputDirName.substring(0, outputDirName.length() - 1); File outputDir = new File(outputDirName).getCanonicalFile(); if (!outputDir.isDirectory()) { if (!outputDir.mkdir()) { System.err.println("Failed to create directory '" + outputDir + "'"); System.exit(2); } } if (generateHtml) { new File(outputDir, "tables").mkdir(); new File(outputDir, "graphs/summary").mkdirs(); } String dbType = getParam(args, "-t", false, false); if (dbType == null) dbType = "ora"; StringBuffer propertiesLoadedFrom = new StringBuffer(); Properties properties = getDbProperties(dbType, propertiesLoadedFrom); String user = getParam(args, "-u", true, false); String password = getParam(args, "-p", false, false); String schema = null; try { schema = getParam(args, "-s", false, true); } catch (Exception schemaNotSpecified) { } String classpath = getParam(args, "-cp", false, false); String css = getParam(args, "-css", false, false); if (css == null) css = "schemaSpy.css"; int maxDbThreads = getMaxDbThreads(args, properties); if (!args.remove("-nologo")) { // nasty hack, but passing this info everywhere churns my stomach System.setProperty("sourceforgelogo", "true"); } ConnectionURLBuilder urlBuilder = null; try { urlBuilder = new ConnectionURLBuilder(dbType, args, properties); } catch (IllegalArgumentException badParam) { System.err.println(badParam.getMessage()); System.exit(1); } String dbName = urlBuilder.getDbName(); if (args.size() != 0) { System.out.print("Warning: Unrecognized option(s):"); for (Iterator iter = args.iterator(); iter.hasNext(); ) { System.out.print(" " + iter.next()); } System.out.println(); } if (generateHtml) StyleSheet.init(new BufferedReader(getStyleSheet(css))); String driverClass = properties.getProperty("driver"); String driverPath = properties.getProperty("driverPath"); if (classpath != null) driverPath = classpath + File.pathSeparator + driverPath; Connection connection = getConnection(user, password, urlBuilder.getConnectionURL(), driverClass, driverPath, propertiesLoadedFrom.toString()); DatabaseMetaData meta = connection.getMetaData(); if (schema == null && meta.supportsSchemasInTableDefinitions()) { schema = user; } if (generateHtml) { System.out.println("Connected to " + meta.getDatabaseProductName() + " - " + meta.getDatabaseProductVersion()); System.out.println(); System.out.print("Gathering schema details"); } // // create the spy // SchemaSpy spy = new SchemaSpy(connection, meta, dbName, schema, properties, maxDbThreads); Database db = spy.getDatabase(); LineWriter out; Collection tables = new ArrayList(db.getTables()); tables.addAll(db.getViews()); if (tables.isEmpty()) { dumpNoTablesMessage(schema, user, meta); System.exit(2); } // DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // DocumentBuilder builder = factory.newDocumentBuilder(); // Document document = builder.newDocument(); // Element schemaNode = document.createElement("schema"); // document.appendChild(schemaNode); // if (schema != null) // DOMUtil.appendAttribute(schemaNode, "name", schema); // DOMUtil.appendAttribute(schemaNode, "databaseType", db.getDatabaseProduct()); if (generateHtml) { startSummarizing = System.currentTimeMillis(); System.out.println("(" + (startSummarizing - start) / 1000 + "sec)"); System.out.print("Writing/graphing summary"); System.out.print("."); File graphsDir = new File(outputDir, "graphs/summary"); String dotBaseFilespec = "relationships"; out = new LineWriter(new FileWriter(new File(graphsDir, dotBaseFilespec + ".real.compact.dot"))); WriteStats stats = DotFormatter.getInstance().writeRealRelationships(tables, true, out); boolean hasRelationships = stats.getNumTablesWritten() > 0 || stats.getNumViewsWritten() > 0; out.close(); if (hasRelationships) { System.out.print("."); out = new LineWriter(new FileWriter(new File(graphsDir, dotBaseFilespec + ".real.large.dot"))); DotFormatter.getInstance().writeRealRelationships(tables, false, out); out.close(); } // getting implied constraints has a side-effect of associating the parent/child tables, so don't do it // here unless they want that behavior List impliedConstraints = null; if (includeImpliedConstraints) impliedConstraints = DBAnalyzer.getImpliedConstraints(tables); else impliedConstraints = new ArrayList(); List orphans = DBAnalyzer.getOrphans(tables); boolean hasOrphans = !orphans.isEmpty() && Dot.getInstance().isValid(); if (hasRelationships) { System.out.print("."); File impliedDotFile = new File(graphsDir, dotBaseFilespec + ".implied.compact.dot"); out = new LineWriter(new FileWriter(impliedDotFile)); boolean hasImplied = DotFormatter.getInstance().writeAllRelationships(tables, true, out).wroteImplied(); out.close(); if (hasImplied) { impliedDotFile = new File(graphsDir, dotBaseFilespec + ".implied.large.dot"); out = new LineWriter(new FileWriter(impliedDotFile)); DotFormatter.getInstance().writeAllRelationships(tables, false, out); out.close(); } else { impliedDotFile.delete(); } out = new LineWriter(new FileWriter(new File(outputDir, dotBaseFilespec + ".html"))); hasRelationships = HtmlGraphFormatter.getInstance().write(db, graphsDir, dotBaseFilespec, hasOrphans, hasImplied, out); out.close(); } System.out.print("."); dotBaseFilespec = "utilities"; out = new LineWriter(new FileWriter(new File(outputDir, dotBaseFilespec + ".html"))); HtmlGraphFormatter.getInstance().writeOrphans(db, orphans, hasRelationships, graphsDir, out); out.close(); System.out.print("."); out = new LineWriter(new FileWriter(new File(outputDir, "index.html")), 64 * 1024); HtmlMainIndexFormatter.getInstance().write(db, tables, hasRelationships, hasOrphans, out); out.close(); System.out.print("."); List constraints = DBAnalyzer.getForeignKeyConstraints(tables); out = new LineWriter(new FileWriter(new File(outputDir, "constraints.html")), 256 * 1024); HtmlConstraintIndexFormatter constraintIndexFormatter = HtmlConstraintIndexFormatter.getInstance(); constraintIndexFormatter.write(db, constraints, tables, hasRelationships, hasOrphans, out); out.close(); System.out.print("."); out = new LineWriter(new FileWriter(new File(outputDir, "anomalies.html")), 16 * 1024); HtmlAnomaliesFormatter.getInstance().write(db, tables, impliedConstraints, hasRelationships, hasOrphans, out); out.close(); System.out.print("."); out = new LineWriter(new FileWriter(new File(outputDir, "columns.html")), 16 * 1024); HtmlColumnsFormatter.getInstance().write(db, tables, hasRelationships, hasOrphans, out); out.close(); startGraphingDetails = System.currentTimeMillis(); System.out.println("(" + (startGraphingDetails - startSummarizing) / 1000 + "sec)"); System.out.print("Writing/graphing results"); HtmlTableFormatter tableFormatter = HtmlTableFormatter.getInstance(); for (Iterator iter = tables.iterator(); iter.hasNext(); ) { System.out.print('.'); Table table = (Table)iter.next(); out = new LineWriter(new FileWriter(new File(outputDir, "tables/" + table.getName() + ".html")), 24 * 1024); tableFormatter.write(db, table, hasRelationships, hasOrphans, outputDir, out); out.close(); // XmlTableFormatter.getInstance().appendTable(schemaNode, table, outputDir); } out = new LineWriter(new FileWriter(new File(outputDir, "schemaSpy.css"))); StyleSheet.getInstance().write(out); out.close(); out = new LineWriter(new FileWriter(new File(outputDir, "schemaSpy.js"))); JavaScriptFormatter.getInstance().write(out); out.close(); } // out = new LineWriter(new FileWriter(new File(outputDir, "schemaSpy.xml")), 24 * 1024); // document.getDocumentElement().normalize(); // DOMUtil.printDOM(document, out); // out.close(); List recursiveConstraints = new ArrayList(); // side effect is that the RI relationships get trashed // also populates the recursiveConstraints collection List orderedTables = spy.sortTablesByRI(recursiveConstraints); out = new LineWriter(new FileWriter(new File(outputDir, "insertionOrder.txt")), 16 * 1024); TextFormatter.getInstance().write(db, orderedTables, false, out); out.close(); out = new LineWriter(new FileWriter(new File(outputDir, "deletionOrder.txt")), 16 * 1024); Collections.reverse(orderedTables); TextFormatter.getInstance().write(db, orderedTables, false, out); out.close(); /* we'll eventually want to put this functionality back in with a * database independent implementation File constraintsFile = new File(outputDir, "removeRecursiveConstraints.sql"); constraintsFile.delete(); if (!recursiveConstraints.isEmpty()) { out = new LineWriter(new FileWriter(constraintsFile), 4 * 1024); writeRemoveRecursiveConstraintsSql(recursiveConstraints, schema, out); out.close(); } constraintsFile = new File(outputDir, "restoreRecursiveConstraints.sql"); constraintsFile.delete(); if (!recursiveConstraints.isEmpty()) { out = new LineWriter(new FileWriter(constraintsFile), 4 * 1024); writeRestoreRecursiveConstraintsSql(recursiveConstraints, schema, out); out.close(); } */ if (generateHtml) { long end = System.currentTimeMillis(); System.out.println("(" + (end - startGraphingDetails) / 1000 + "sec)"); System.out.println("Wrote relationship details of " + tables.size() + " tables/views to directory '" + new File(outputDirName) + "' in " + (end - start) / 1000 + " seconds."); System.out.println("Start with " + new File(outputDirName, "index.html")); } } catch (Exception exc) { System.err.println(); exc.printStackTrace(); } }
diff --git a/src/com/Cayviel/RotatePiston/InteractListener.java b/src/com/Cayviel/RotatePiston/InteractListener.java index 5975847..6b0df29 100644 --- a/src/com/Cayviel/RotatePiston/InteractListener.java +++ b/src/com/Cayviel/RotatePiston/InteractListener.java @@ -1,106 +1,106 @@ package com.Cayviel.RotatePiston; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.event.player.PlayerListener; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.block.Action; public class InteractListener extends PlayerListener { byte clickeddirc(byte clickeddir){ switch (clickeddir){ case 0: return 1; case 1: return 0; case 2: return 3; case 3: return 2; case 4: return 5; case 5: return 4; default: return 1; } } public void onPlayerInteract(PlayerInteractEvent PlayerWithPiston){ if (RotatePiston.permissionHandler == null) { if (RotatePiston.useop&&(!PlayerWithPiston.getPlayer().isOp())){ return; } }else{ if (!RotatePiston.permissionHandler.has(PlayerWithPiston.getPlayer(),"rotatepiston")){ return; } } if (PlayerWithPiston.getAction().equals(Action.RIGHT_CLICK_BLOCK)){ Material Blocktype = PlayerWithPiston.getClickedBlock().getType(); if ((Blocktype == Material.PISTON_BASE)||(Blocktype == Material.PISTON_STICKY_BASE)){ boolean sticky = false; if (Blocktype == Material.PISTON_STICKY_BASE){sticky = true;} BlockFace clickedface = PlayerWithPiston.getBlockFace(); Block piston = PlayerWithPiston.getClickedBlock(); byte dir = (byte) (piston.getData() % 8); byte clickeddir; byte dirsetto; if (clickedface == BlockFace.valueOf("NORTH")){clickeddir=4;}else{ if (clickedface == BlockFace.valueOf("EAST")){clickeddir=2;}else{ if (clickedface == BlockFace.valueOf("SOUTH")){clickeddir=5;}else{ if (clickedface == BlockFace.valueOf("WEST")){clickeddir=3;}else{ if (clickedface == BlockFace.valueOf("UP")){clickeddir=1;}else{ if (clickedface == BlockFace.valueOf("DOWN")){clickeddir=0;}else{ clickeddir=1; } } } } } } piston.setTypeId(0); if (sticky==false){ piston.setType(Material.PISTON_BASE); }else{ piston.setType(Material.PISTON_STICKY_BASE); } if (!PlayerWithPiston.getPlayer().isSneaking()){ if (clickeddir == dir){ dirsetto=clickeddirc(clickeddir); }else{ dirsetto=clickeddir; } }else{ while(((byte)((dir+1) % 6)==clickeddir)||((byte)((dir+1) % 6)==clickeddirc(clickeddir))){dir = (byte)((dir+1) % 6);} //don't try sides already accessible dirsetto=(byte)((dir+1) % 6); } piston.setData(dirsetto); - if (piston.isBlockPowered()){ + if (piston.isBlockPowered()||piston.isBlockIndirectlyPowered()){ if (piston.getRelative(convertdirtoface(dirsetto)).getType()==Material.AIR){ piston.setData((byte) (piston.getData()+8)); piston.getRelative(convertdirtoface(dirsetto)).setType(Material.PISTON_EXTENSION); if (sticky == false){ piston.getRelative(convertdirtoface(dirsetto)).setData(dirsetto); }else{ piston.getRelative(convertdirtoface(dirsetto)).setData((byte) (dirsetto+8)); } } } } } } private BlockFace convertdirtoface (byte dir){ switch (dir){ case 0: return BlockFace.DOWN; case 1: return BlockFace.UP; case 2: return BlockFace.EAST; case 3: return BlockFace.WEST; case 4: return BlockFace.NORTH; case 5: return BlockFace.SOUTH; default: return BlockFace.DOWN; } } }
true
true
public void onPlayerInteract(PlayerInteractEvent PlayerWithPiston){ if (RotatePiston.permissionHandler == null) { if (RotatePiston.useop&&(!PlayerWithPiston.getPlayer().isOp())){ return; } }else{ if (!RotatePiston.permissionHandler.has(PlayerWithPiston.getPlayer(),"rotatepiston")){ return; } } if (PlayerWithPiston.getAction().equals(Action.RIGHT_CLICK_BLOCK)){ Material Blocktype = PlayerWithPiston.getClickedBlock().getType(); if ((Blocktype == Material.PISTON_BASE)||(Blocktype == Material.PISTON_STICKY_BASE)){ boolean sticky = false; if (Blocktype == Material.PISTON_STICKY_BASE){sticky = true;} BlockFace clickedface = PlayerWithPiston.getBlockFace(); Block piston = PlayerWithPiston.getClickedBlock(); byte dir = (byte) (piston.getData() % 8); byte clickeddir; byte dirsetto; if (clickedface == BlockFace.valueOf("NORTH")){clickeddir=4;}else{ if (clickedface == BlockFace.valueOf("EAST")){clickeddir=2;}else{ if (clickedface == BlockFace.valueOf("SOUTH")){clickeddir=5;}else{ if (clickedface == BlockFace.valueOf("WEST")){clickeddir=3;}else{ if (clickedface == BlockFace.valueOf("UP")){clickeddir=1;}else{ if (clickedface == BlockFace.valueOf("DOWN")){clickeddir=0;}else{ clickeddir=1; } } } } } } piston.setTypeId(0); if (sticky==false){ piston.setType(Material.PISTON_BASE); }else{ piston.setType(Material.PISTON_STICKY_BASE); } if (!PlayerWithPiston.getPlayer().isSneaking()){ if (clickeddir == dir){ dirsetto=clickeddirc(clickeddir); }else{ dirsetto=clickeddir; } }else{ while(((byte)((dir+1) % 6)==clickeddir)||((byte)((dir+1) % 6)==clickeddirc(clickeddir))){dir = (byte)((dir+1) % 6);} //don't try sides already accessible dirsetto=(byte)((dir+1) % 6); } piston.setData(dirsetto); if (piston.isBlockPowered()){ if (piston.getRelative(convertdirtoface(dirsetto)).getType()==Material.AIR){ piston.setData((byte) (piston.getData()+8)); piston.getRelative(convertdirtoface(dirsetto)).setType(Material.PISTON_EXTENSION); if (sticky == false){ piston.getRelative(convertdirtoface(dirsetto)).setData(dirsetto); }else{ piston.getRelative(convertdirtoface(dirsetto)).setData((byte) (dirsetto+8)); } } } } } }
public void onPlayerInteract(PlayerInteractEvent PlayerWithPiston){ if (RotatePiston.permissionHandler == null) { if (RotatePiston.useop&&(!PlayerWithPiston.getPlayer().isOp())){ return; } }else{ if (!RotatePiston.permissionHandler.has(PlayerWithPiston.getPlayer(),"rotatepiston")){ return; } } if (PlayerWithPiston.getAction().equals(Action.RIGHT_CLICK_BLOCK)){ Material Blocktype = PlayerWithPiston.getClickedBlock().getType(); if ((Blocktype == Material.PISTON_BASE)||(Blocktype == Material.PISTON_STICKY_BASE)){ boolean sticky = false; if (Blocktype == Material.PISTON_STICKY_BASE){sticky = true;} BlockFace clickedface = PlayerWithPiston.getBlockFace(); Block piston = PlayerWithPiston.getClickedBlock(); byte dir = (byte) (piston.getData() % 8); byte clickeddir; byte dirsetto; if (clickedface == BlockFace.valueOf("NORTH")){clickeddir=4;}else{ if (clickedface == BlockFace.valueOf("EAST")){clickeddir=2;}else{ if (clickedface == BlockFace.valueOf("SOUTH")){clickeddir=5;}else{ if (clickedface == BlockFace.valueOf("WEST")){clickeddir=3;}else{ if (clickedface == BlockFace.valueOf("UP")){clickeddir=1;}else{ if (clickedface == BlockFace.valueOf("DOWN")){clickeddir=0;}else{ clickeddir=1; } } } } } } piston.setTypeId(0); if (sticky==false){ piston.setType(Material.PISTON_BASE); }else{ piston.setType(Material.PISTON_STICKY_BASE); } if (!PlayerWithPiston.getPlayer().isSneaking()){ if (clickeddir == dir){ dirsetto=clickeddirc(clickeddir); }else{ dirsetto=clickeddir; } }else{ while(((byte)((dir+1) % 6)==clickeddir)||((byte)((dir+1) % 6)==clickeddirc(clickeddir))){dir = (byte)((dir+1) % 6);} //don't try sides already accessible dirsetto=(byte)((dir+1) % 6); } piston.setData(dirsetto); if (piston.isBlockPowered()||piston.isBlockIndirectlyPowered()){ if (piston.getRelative(convertdirtoface(dirsetto)).getType()==Material.AIR){ piston.setData((byte) (piston.getData()+8)); piston.getRelative(convertdirtoface(dirsetto)).setType(Material.PISTON_EXTENSION); if (sticky == false){ piston.getRelative(convertdirtoface(dirsetto)).setData(dirsetto); }else{ piston.getRelative(convertdirtoface(dirsetto)).setData((byte) (dirsetto+8)); } } } } } }
diff --git a/orbisgis-ui/src/main/java/org/orbisgis/core/ui/plugins/views/sqlConsole/actions/ExecuteScriptProcess.java b/orbisgis-ui/src/main/java/org/orbisgis/core/ui/plugins/views/sqlConsole/actions/ExecuteScriptProcess.java index 3227e116f..edc77b27e 100644 --- a/orbisgis-ui/src/main/java/org/orbisgis/core/ui/plugins/views/sqlConsole/actions/ExecuteScriptProcess.java +++ b/orbisgis-ui/src/main/java/org/orbisgis/core/ui/plugins/views/sqlConsole/actions/ExecuteScriptProcess.java @@ -1,198 +1,200 @@ /* * OrbisGIS is a GIS application dedicated to scientific spatial simulation. * This cross-platform GIS is developed at French IRSTV institute and is able to * manipulate and create vector and raster spatial information. OrbisGIS is * distributed under GPL 3 license. It is produced by the "Atelier SIG" team of * the IRSTV Institute <http://www.irstv.cnrs.fr/> CNRS FR 2488. * * * Team leader Erwan BOCHER, scientific researcher, * * User support leader : Gwendall Petit, geomatic engineer. * * * Copyright (C) 2007 Erwan BOCHER, Fernando GONZALEZ CORTES, Thomas LEDUC * * Copyright (C) 2010 Erwan BOCHER, Pierre-Yves FADET, Alexis GUEGANNO, Maxence LAURENT * * This file is part of OrbisGIS. * * OrbisGIS 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. * * OrbisGIS 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 * OrbisGIS. If not, see <http://www.gnu.org/licenses/>. * * For more information, please consult: <http://www.orbisgis.org/> * * or contact directly: * erwan.bocher _at_ ec-nantes.fr * gwendall.petit _at_ ec-nantes.fr */ package org.orbisgis.core.ui.plugins.views.sqlConsole.actions; import org.apache.log4j.Logger; import org.gdms.data.DataSource; import org.gdms.data.DataSourceCreationException; import org.gdms.data.DataSourceFactory; import org.gdms.data.SQLDataSourceFactory; import org.gdms.data.schema.Metadata; import org.gdms.data.schema.MetadataUtilities; import org.gdms.driver.DriverException; import org.gdms.sql.engine.SQLEngine; import org.gdms.sql.engine.SqlStatement; import org.gdms.sql.engine.ParseException; import org.orbisgis.core.DataManager; import org.orbisgis.core.Services; import org.orbisgis.core.background.BackgroundJob; import org.orbisgis.core.layerModel.ILayer; import org.orbisgis.core.layerModel.LayerException; import org.orbisgis.core.layerModel.MapContext; import org.orbisgis.core.ui.editors.map.MapContextManager; import org.orbisgis.core.ui.plugins.views.output.OutputManager; import org.orbisgis.core.ui.plugins.views.sqlConsole.ui.SQLConsolePanel; import org.orbisgis.progress.ProgressMonitor; public class ExecuteScriptProcess implements BackgroundJob { private String script; private static final Logger logger = Logger.getLogger(ExecuteScriptProcess.class); private SQLConsolePanel panel; public ExecuteScriptProcess(String script) { this.script = script; } public ExecuteScriptProcess(String script, SQLConsolePanel panel) { this.script = script; this.panel = panel; } public String getTaskName() { return "Executing script"; } public void run(ProgressMonitor pm) { DataManager dataManager = (DataManager) Services.getService(DataManager.class); SQLDataSourceFactory dsf = dataManager.getDataSourceFactory(); SQLEngine engine = new SQLEngine(dsf); SqlStatement[] statements = null; long t1 = System.currentTimeMillis(); try { logger.debug("Preparing script: " + script); try { statements = engine.parse(script); } catch (ParseException e) { Services.getErrorManager().error("Cannot parse script", e); if (panel != null) { panel.setStatusMessage("Failed to parse the script."); } return; } MapContext vc = ((MapContextManager) Services.getService(MapContextManager.class)).getActiveMapContext(); for (int i = 0; i < statements.length; i++) { SqlStatement st = statements[i]; logger.debug("Preparing instruction: " + st.getSQL()); - st.prepare(dsf); boolean spatial = false; try { + st.prepare(dsf); Metadata metadata = st.getResultMetadata(); + st.cleanUp(); if (metadata != null) { spatial = MetadataUtilities.isSpatial(metadata); DataSource ds = dsf.getDataSource(st, DataSourceFactory.DEFAULT, pm); if (pm.isCancelled()) { break; } if (spatial && vc != null) { try { final ILayer layer = dataManager.createLayer(ds); vc.getLayerModel().insertLayer(layer, 0); } catch (LayerException e) { Services.getErrorManager().error( "Impossible to create the layer:" + ds.getName(), e); break; } } else { OutputManager om = Services.getService(OutputManager.class); ds.open(); StringBuilder aux = new StringBuilder(); int fc = ds.getMetadata().getFieldCount(); int rc = (int) ds.getRowCount(); for (int j = 0; j < fc; j++) { om.print(ds.getFieldName(j)); om.print("\t"); } om.println(""); for (int row = 0; row < rc; row++) { for (int j = 0; j < fc; j++) { om.print(ds.getFieldValue(row, j).toString()); om.print("\t"); } om.println(""); if (row > 100) { om.println("and more... total " + rc + " rows"); break; } } ds.close(); om.println(aux.toString()); } } else { + st.prepare(dsf); st.execute(); if (pm.isCancelled()) { break; } } } catch (DataSourceCreationException e) { Services.getErrorManager().error( "Cannot create the DataSource:" + st.getSQL(), e); break; } finally { if (!spatial) { st.cleanUp(); } } pm.progressTo(100 * i / statements.length); } } catch (DriverException e) { Services.getErrorManager().error("Data access error:", e); } long t2 = System.currentTimeMillis(); double lastExecTime = ((t2 - t1) / 1000.0); logger.debug("Execution time: " + lastExecTime); if (panel != null) { panel.setStatusMessage("Execution time: " + lastExecTime); } } }
false
true
public void run(ProgressMonitor pm) { DataManager dataManager = (DataManager) Services.getService(DataManager.class); SQLDataSourceFactory dsf = dataManager.getDataSourceFactory(); SQLEngine engine = new SQLEngine(dsf); SqlStatement[] statements = null; long t1 = System.currentTimeMillis(); try { logger.debug("Preparing script: " + script); try { statements = engine.parse(script); } catch (ParseException e) { Services.getErrorManager().error("Cannot parse script", e); if (panel != null) { panel.setStatusMessage("Failed to parse the script."); } return; } MapContext vc = ((MapContextManager) Services.getService(MapContextManager.class)).getActiveMapContext(); for (int i = 0; i < statements.length; i++) { SqlStatement st = statements[i]; logger.debug("Preparing instruction: " + st.getSQL()); st.prepare(dsf); boolean spatial = false; try { Metadata metadata = st.getResultMetadata(); if (metadata != null) { spatial = MetadataUtilities.isSpatial(metadata); DataSource ds = dsf.getDataSource(st, DataSourceFactory.DEFAULT, pm); if (pm.isCancelled()) { break; } if (spatial && vc != null) { try { final ILayer layer = dataManager.createLayer(ds); vc.getLayerModel().insertLayer(layer, 0); } catch (LayerException e) { Services.getErrorManager().error( "Impossible to create the layer:" + ds.getName(), e); break; } } else { OutputManager om = Services.getService(OutputManager.class); ds.open(); StringBuilder aux = new StringBuilder(); int fc = ds.getMetadata().getFieldCount(); int rc = (int) ds.getRowCount(); for (int j = 0; j < fc; j++) { om.print(ds.getFieldName(j)); om.print("\t"); } om.println(""); for (int row = 0; row < rc; row++) { for (int j = 0; j < fc; j++) { om.print(ds.getFieldValue(row, j).toString()); om.print("\t"); } om.println(""); if (row > 100) { om.println("and more... total " + rc + " rows"); break; } } ds.close(); om.println(aux.toString()); } } else { st.execute(); if (pm.isCancelled()) { break; } } } catch (DataSourceCreationException e) { Services.getErrorManager().error( "Cannot create the DataSource:" + st.getSQL(), e); break; } finally { if (!spatial) { st.cleanUp(); } } pm.progressTo(100 * i / statements.length); } } catch (DriverException e) { Services.getErrorManager().error("Data access error:", e); } long t2 = System.currentTimeMillis(); double lastExecTime = ((t2 - t1) / 1000.0); logger.debug("Execution time: " + lastExecTime); if (panel != null) { panel.setStatusMessage("Execution time: " + lastExecTime); } }
public void run(ProgressMonitor pm) { DataManager dataManager = (DataManager) Services.getService(DataManager.class); SQLDataSourceFactory dsf = dataManager.getDataSourceFactory(); SQLEngine engine = new SQLEngine(dsf); SqlStatement[] statements = null; long t1 = System.currentTimeMillis(); try { logger.debug("Preparing script: " + script); try { statements = engine.parse(script); } catch (ParseException e) { Services.getErrorManager().error("Cannot parse script", e); if (panel != null) { panel.setStatusMessage("Failed to parse the script."); } return; } MapContext vc = ((MapContextManager) Services.getService(MapContextManager.class)).getActiveMapContext(); for (int i = 0; i < statements.length; i++) { SqlStatement st = statements[i]; logger.debug("Preparing instruction: " + st.getSQL()); boolean spatial = false; try { st.prepare(dsf); Metadata metadata = st.getResultMetadata(); st.cleanUp(); if (metadata != null) { spatial = MetadataUtilities.isSpatial(metadata); DataSource ds = dsf.getDataSource(st, DataSourceFactory.DEFAULT, pm); if (pm.isCancelled()) { break; } if (spatial && vc != null) { try { final ILayer layer = dataManager.createLayer(ds); vc.getLayerModel().insertLayer(layer, 0); } catch (LayerException e) { Services.getErrorManager().error( "Impossible to create the layer:" + ds.getName(), e); break; } } else { OutputManager om = Services.getService(OutputManager.class); ds.open(); StringBuilder aux = new StringBuilder(); int fc = ds.getMetadata().getFieldCount(); int rc = (int) ds.getRowCount(); for (int j = 0; j < fc; j++) { om.print(ds.getFieldName(j)); om.print("\t"); } om.println(""); for (int row = 0; row < rc; row++) { for (int j = 0; j < fc; j++) { om.print(ds.getFieldValue(row, j).toString()); om.print("\t"); } om.println(""); if (row > 100) { om.println("and more... total " + rc + " rows"); break; } } ds.close(); om.println(aux.toString()); } } else { st.prepare(dsf); st.execute(); if (pm.isCancelled()) { break; } } } catch (DataSourceCreationException e) { Services.getErrorManager().error( "Cannot create the DataSource:" + st.getSQL(), e); break; } finally { if (!spatial) { st.cleanUp(); } } pm.progressTo(100 * i / statements.length); } } catch (DriverException e) { Services.getErrorManager().error("Data access error:", e); } long t2 = System.currentTimeMillis(); double lastExecTime = ((t2 - t1) / 1000.0); logger.debug("Execution time: " + lastExecTime); if (panel != null) { panel.setStatusMessage("Execution time: " + lastExecTime); } }
diff --git a/waterken/persistence/src/org/waterken/jos/JODB.java b/waterken/persistence/src/org/waterken/jos/JODB.java index 6d63904a..64fc2a8b 100644 --- a/waterken/persistence/src/org/waterken/jos/JODB.java +++ b/waterken/persistence/src/org/waterken/jos/JODB.java @@ -1,792 +1,793 @@ // Copyright 2002-2008 Waterken Inc. under the terms of the MIT X license // found at http://www.opensource.org/licenses/mit-license.html package org.waterken.jos; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InvalidClassException; import java.io.ObjectInputStream; import java.io.ObjectStreamConstants; import java.io.OutputStream; import java.io.Serializable; import java.io.StreamCorruptedException; import java.lang.ref.ReferenceQueue; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Locale; import java.util.Map; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.joe_e.Immutable; import org.joe_e.JoeE; import org.joe_e.Struct; import org.joe_e.Token; import org.joe_e.inert; import org.joe_e.array.ByteArray; import org.joe_e.array.PowerlessArray; import org.joe_e.charset.URLEncoding; import org.joe_e.file.InvalidFilenameException; import org.joe_e.reflect.Reflection; import org.joe_e.var.Milestone; import org.ref_send.log.Event; import org.ref_send.promise.Eventual; import org.ref_send.promise.Log; import org.ref_send.promise.Promise; import org.ref_send.promise.Receiver; import org.waterken.base32.Base32; import org.waterken.cache.CacheReference; import org.waterken.db.Creator; import org.waterken.db.CyclicGraph; import org.waterken.db.Database; import org.waterken.db.Effect; import org.waterken.db.ProhibitedCreation; import org.waterken.db.ProhibitedModification; import org.waterken.db.Root; import org.waterken.db.Service; import org.waterken.db.Transaction; import org.waterken.db.TransactionMonitor; import org.waterken.project.Project; import org.waterken.store.Store; import org.waterken.store.Update; import org.waterken.trace.EventSender; import org.waterken.trace.Tracer; import org.waterken.trace.TurnCounter; import org.waterken.trace.application.ApplicationTracer; /** * An object graph stored as a set of Java Object Serialization files. */ /* package */ final class JODB<S> extends Database<S> { /** * Canonicalizes a {@link Root} name. * <p> * All lower-case names are used to hide differences in how different file * systems handle case-sensitivity. * </p> * @param name chosen name * @return canonical name */ static protected String canonicalize(final String name) { return name.toLowerCase(Locale.ENGLISH); } /** * file extension for a serialized Java object tree */ static protected final String ext = ".jos"; static private final int keyChars = 70 / 5; // 70 bits > 10^21 keys static protected final int keyBytes = keyChars * 5 / 8 + 1; /** * Turns an object identifier into a filename. * @param id object identifier * @return corresponding filename */ static protected String filename(final byte[] id) {return Base32.encode(id).substring(0, keyChars);} private final Receiver<Event> stderr; // log event output private final Store store; // byte storage protected JODB(final S session, final Receiver<Service> service, final Receiver<Event> stderr, final Store store) { super(session, service); this.stderr = stderr; this.store = store; } static private <S> Receiver<Object> makeDestructor(final Receiver<Effect<S>> effect) { class Destruct extends Struct implements Receiver<Object>, Serializable{ static private final long serialVersionUID = 1L; public void run(final Object ignored) { effect.run(new Effect<S>() { public void run(final Database<S> origin) throws InterruptedException { while (true) { try { ((JODB<?>)origin).store.clean(); break; } catch (final Exception e) { Thread.sleep(1000); } } } }); } } return new Destruct(); } // org.waterken.db.Database interface /** * Has the {@link #wake wake} task been run? */ private final Milestone<Boolean> awake = Milestone.plan(); private ClassLoader code = JODB.class.getClassLoader(); private SecureRandom prng; private HashMap<String,Bucket> f2b; // object cache private ReferenceQueue<Object> wiped; // dead cache entries private Processor tx; // currently active transaction processor static private final class Wake implements Transaction<Immutable> { public Immutable run(final Root root) throws Exception { final Receiver<?> wake = root.fetch(null, Database.wake); if (null != wake) { wake.run(null); } return new Token(); } } public <R extends Immutable> Promise<R> enter(final boolean isQuery, final Transaction<R> body) throws Exception { synchronized (store) { if (!awake.is() && !(body instanceof Wake)) { enter(Transaction.query, new Wake()).call(); awake.mark(true); } Promise<R> r; final Processor m = tx = new Processor(isQuery, store.update()); boolean done = false; try { initialize(m); try { // execute the transaction body if (!m.isQuery) { final Receiver<?> flip = root.fetch(null, JODB.flip); if (null != flip) { flip.run(null); } } r = Eventual.ref(body.run(root)); } catch (final Exception e) { r = Eventual.reject(e); } persist(m); m.update.commit(); done = true; } catch (final Error e) { // allow the caller to recover from an aborted transaction if (e instanceof OutOfMemoryError) { System.gc(); } final Throwable cause = e.getCause(); if (cause instanceof Exception) { throw (Exception)cause; } throw new Exception(e); } finally { if (!done) { f2b = null; wiped = null; } tx = null; m.update.close(); } // output the log events for the committed transaction if (null != stderr) { while (!m.events.isEmpty()) { stderr.run(m.events.removeFirst()); } } // schedule any services if (null != service) { while (!m.services.isEmpty()) { service.run(m.services.removeFirst()); } } return r; } } // org.waterken.jos.JODB interface /** * An object store entry. */ static private final class Bucket extends Struct { final CacheReference<String,Object> value; final boolean created; // Is this a newly created bucket? final ByteArray version; // secure hash of value, or // <code>null</code> if not known final boolean managed; // Does value contain only managed state? final PowerlessArray<String> splices; // buckets spliced into value Bucket(final CacheReference<String,Object> value, final boolean created, final ByteArray version, final boolean managed, final PowerlessArray<String> splices) { if (null == value) { throw new AssertionError(); } if (!created && null == version) { throw new AssertionError(); } if (!created && null == splices) { throw new AssertionError(); } this.value = value; this.created = created; this.version = version; this.managed = managed; this.splices = splices; } } static private final class Processor { final boolean isQuery; final Update update; final IdentityHashMap<Object,String> o2f = // [ object => filename ] new IdentityHashMap<Object,String>(32); final IdentityHashMap<Object,String> o2wf = // [object => weak filename] new IdentityHashMap<Object,String>(32); final HashSet<String> xxx = // [ dirty filename ] new HashSet<String>(16); final LinkedList<Service> services = new LinkedList<Service>(); final LinkedList<Event> events = new LinkedList<Event>(); Processor(final boolean isQuery, final Update update) { this.isQuery = isQuery; this.update = update; } } private void create(final String f, final Object o) { if (null != f2b.put(f, new Bucket(new CacheReference<String,Object>(f, o, wiped), true, null, false, null))) {throw new AssertionError();} if (null != tx.o2f.put(o, f)) { throw new AssertionError(); } if (!tx.xxx.add(f)) { throw new AssertionError(); } } private final Root root = new Root() { private final ArrayList<String> stack = new ArrayList<String>(16); /** * Gets the corresponding value, loading from the store if needed. * @param f name of corresponding bucket * @return corresponding value * @throws FileNotFoundException no corresponding value * @throws RuntimeException syntax problem with state * @throws Error I/O problem */ private Object load(final String f) throws FileNotFoundException, RuntimeException { if ("".equals(f)) { return null; } { // check the cache final Bucket b = f2b.get(f); final Object o = null != b ? b.value.get() : null; if (null != o) { if (!b.created) { markDirty(o, b); } return o; } } // remove dead cache entries while (true) { final CacheReference<?,?> r = (CacheReference<?,?>)wiped.poll(); if (null == r) { break; } final Bucket b = f2b.remove(r.key); if (b.value != r) { /* * The entry was reloaded before the soft reference to the * previously loaded value was dequeued. Just put the entry * back in the cache. */ f2b.put(b.value.key, b); } } final int startCycle = stack.lastIndexOf(f); if (-1 != startCycle) { - PowerlessArray<String> cycle = PowerlessArray.array(); + PowerlessArray<String> cycle = + PowerlessArray.array(new String[] {}); for (final String at : stack.subList(startCycle,stack.size())) { try { cycle = cycle.with(identify(tx.update.read(at + ext))); } catch (final IOException e) { throw new Error(e); } } throw new CyclicGraph(cycle.with(cycle.get(0))); } InputStream in; try { in = tx.update.read(f + ext); } catch (final FileNotFoundException e) { throw e; } catch (final IOException e) { throw new Error(e); } stack.add(f); try { final Object o; final ByteArray version; final Milestone<Boolean> unmanaged = Milestone.plan(); final HashSet<String> splices = new HashSet<String>(8); if (canonicalize(JODB.secret).equals(f)) { // base case for loading the master secret final ObjectInputStream oin = new ObjectInputStream(in); in = oin; o = oin.readObject(); setMaster((ByteArray)((SymbolicLink)o).target); final Mac mac = allocMac(this); final Slicer out = new Slicer(false, o, this, new MacOutputStream(mac, null)); out.writeObject(o); out.flush(); out.close(); version = ByteArray.array(mac.doFinal()); freeMac(mac); } else { final Mac mac = allocMac(this); in = new MacInputStream(mac, in); final SubstitutionStream oin = new SubstitutionStream(true, code, in) { protected Object resolveObject(Object x) throws IOException { if (x instanceof File) { unmanaged.mark(true); } else if (x instanceof Splice) { splices.add(((Splice)x).name); x = load(((Splice)x).name); } return x; } }; o = oin.readObject(); while (-1 != in.read()) { in.skip(Long.MAX_VALUE); } in = oin; version = ByteArray.array(mac.doFinal()); freeMac(mac); } // may overwrite a dead cache entry f2b.put(f, new Bucket( new CacheReference<String,Object>(f, o, wiped), false, version, !unmanaged.is(), PowerlessArray.array(splices.toArray(new String[0])))); if (null != tx.o2f.put(o, f)) { throw new AssertionError(); } if (!tx.xxx.add(f)) { throw new AssertionError(); } return o; } catch (final InvalidClassException e) { throw new RuntimeException(e); } catch (final ClassNotFoundException e) { throw new RuntimeException(e); } catch (final IOException e) { throw new Error(e); } catch (final RuntimeException e) { throw e; } catch (final Exception e) { throw new RuntimeException(e); } finally { stack.remove(stack.size() - 1); try { in.close(); } catch (final Exception e) {} } } private void markDirty(final Object o, final Bucket b) { if (null == tx.o2f.put(o, b.value.key)) { if (!tx.xxx.add(b.value.key)) { throw new AssertionError(); } for (final String splice : b.splices) { final Bucket spliced = f2b.get(splice); if (null == spliced) { throw new AssertionError(); } markDirty(spliced.value.get(), spliced); } } } // org.waterken.db.Root interface /** * Updates an object store entry. * <p> * Each entry is stored as a binding in the persistent store. The * corresponding filename is of the form XYZ.jos, where the XYZ * component may be chosen by the client and the ".jos" extension is * automatically appended by the implementation. All filenames are * composed of only lower case letters. For example, * ".stuff.jos.jos" is the filename corresponding to the user chosen * name ".Stuff.JOS". The file extension chosen by the user carries * no significance in this implementation, and neither does a * filename starting with a "." character. * </p> */ public void assign(final String name, final Object value) { if (tx.isQuery) { throw new ProhibitedModification(Reflection.getName(Root.class)); } create(canonicalize(name), new SymbolicLink(value)); } public @SuppressWarnings("unchecked") <T> T fetch(final Object otherwise, final String name) { try { final Object value = load(canonicalize(name)); return (T)(value instanceof SymbolicLink ? ((SymbolicLink)value).target : value); } catch (final FileNotFoundException e) { return (T)otherwise; } } public String export(final @inert Object o, final boolean isWeak) { // check for an existing strong identity { final String f = tx.o2f.get(o); if (null != f) { return f; } } // check for an existing weak identity { final String wf = tx.o2wf.get(o); if (null != wf) { if (!isWeak) { tx.o2wf.remove(o); create(wf, o); } return wf; } } // create a new identity final String r; if (null == o || Slicer.inline(o.getClass())) { try { final Mac mac = allocMac(this); final Slicer out = new Slicer(isWeak, o, this, new MacOutputStream(mac, null)); out.writeObject(o); out.flush(); out.close(); final byte[] k = mac.doFinal(); freeMac(mac); r = filename(k); final Bucket b = f2b.get(r); if (null != b) { if(!b.created && !ByteArray.array(k).equals(b.version)){ throw new AssertionError(); } return r; // recalculated key for a stored object } } catch (final Exception e) { throw new Error(e); } } else if (tx.isQuery) { /* * to support caching of query responses, forbid export of * selfish state in a query transaction */ throw new ProhibitedCreation(Reflection.getName(o.getClass())); } else { final byte[] k = new byte[keyBytes]; prng.nextBytes(k); r = filename(k); } if (isWeak) { tx.o2wf.put(o, r); } else { create(r, o); } return r; } }; final TransactionMonitor monitor = new TransactionMonitor() { public String tag() { final Mac mac; try { mac = allocMac(root); } catch (final Exception e) { throw new Error(e); } for (final String name : tx.o2f.values()) { final Bucket b = f2b.get(name); if (!b.created) { if (!b.managed) { return null; } mac.update(b.version.toByteArray()); } } if (code instanceof Project) { // include code timestamp in the ETag final long buffer = ((Project)code).timestamp; for (int i = Long.SIZE; i != 0;) { i -= Byte.SIZE; mac.update((byte)(buffer >>> i)); } } final byte[] id = mac.doFinal(); freeMac(mac); return '\"' + Base32.encode(id).substring(0, 2*keyChars) + '\"'; } }; final Receiver<Effect<S>> effect = new Receiver<Effect<S>>() { public void run(final Effect<S> task) { tx.services.add(new Service() { public Void call() throws Exception { task.run(JODB.this); return null; } }); } }; final Creator creator = new Creator() { public <X extends Immutable> Promise<X> run(final String project, final String base, String name, final Transaction<X> setup) throws InvalidFilenameException, ProhibitedModification { if (tx.isQuery) { throw new ProhibitedModification( Reflection.getName(Creator.class)); } Store subStore; if (null != name) { name = canonicalize(name); try { subStore = tx.update.nest(name); } catch (final InvalidFilenameException e) { throw e; } catch (final Exception e) { throw new Error(e); } } else { while (true) { try { final byte[] d = new byte[4]; prng.nextBytes(d); name = Base32.encode(d).substring(0, 6); subStore = tx.update.nest(name); break; } catch (final InvalidFilenameException e) { } catch (final Exception e) { throw new Error(e); } } } try { final String here = base + URLEncoding.encode(name) + "/"; final byte[] bits = new byte[128 / Byte.SIZE]; prng.nextBytes(bits); final ByteArray secretBits = ByteArray.array(bits); final JODB<S> sub = new JODB<S>(null, null, null == stderr ? new Receiver<Event>() { public void run(final Event value) {} } : stderr, subStore); final String subProject; if (null != project) { subProject = project; sub.code = Project.connect(subProject); } else { subProject = root.fetch(null, Database.project); sub.code = code; } sub.prng = prng; sub.awake.mark(true); return sub.enter(Transaction.update, new Transaction<X>() { public X run(final Root local) throws Exception { local.assign(Database.project, subProject); local.assign(Database.here, here); local.assign(secret, secretBits); final TurnCounter turn = TurnCounter.make(here); local.assign(JODB.flip, turn.flip); final ClassLoader code = local.fetch(null, Database.code); final Tracer tracer = ApplicationTracer.make(code); final Receiver<Effect<S>> effect = local.fetch(null, Database.effect); local.assign(Database.destruct, makeDestructor(effect)); sub.create(canonicalize(Database.log), EventSender.make( sub.txerr, turn.mark, tracer)); return setup.run(local); } }); } catch (final Exception e) { throw new Error(e); } } }; final Receiver<Event> txerr = new Receiver<Event>() { public void run(final Event event) { tx.events.add(event); } }; final Log nop = new Log(); private void initialize(final Processor m) throws Exception { final boolean restockCache = null == f2b; if (restockCache) { wiped = new ReferenceQueue<Object>(); f2b = new HashMap<String,Bucket>(64); } /* * finish Vat initialization, which was delayed to avoid doing anything * intensive while holding the global "live" lock */ if (null == prng) { final String project; try { project = root.fetch(null, Database.project); } catch (final Exception e) { throw new Error(e); } code = Project.connect(project); prng = new SecureRandom(); } // setup the pseudo-persistent objects m.o2f.put(code, Database.code); m.o2f.put(creator, Database.creator); m.o2f.put(effect, Database.effect); m.o2f.put(null, Database.nothing); m.o2f.put(monitor, Database.monitor); m.o2f.put(txerr, ".txerr"); m.o2f.put(root, ".root"); if (null == stderr) { // short-circuit the log implementation m.o2f.put(nop, Database.log); } if (restockCache) { for (final Map.Entry<Object,String> x : m.o2f.entrySet()) { final String f = x.getValue(); if (!f2b.containsKey(f)) { f2b.put(f, new Bucket( new CacheReference<String,Object>(f, x.getKey(), wiped), true, null, false, null)); } } } } private void persist(final Processor m) throws Exception { while (!m.xxx.isEmpty()) { final Iterator<String> i = m.xxx.iterator(); final String f = i.next(); final Bucket b = f2b.get(f); final Object o = b.value.get(); i.remove(); final Mac mac = allocMac(root); final ByteArrayOutputStream bytes = !b.created && (m.isQuery || JoeE.isFrozen(o)) ? null : new ByteArrayOutputStream(256); final Slicer out = new Slicer(false, o, root, new MacOutputStream(mac, bytes)); out.writeObject(o); out.flush(); out.close(); final ByteArray version = ByteArray.array(mac.doFinal()); freeMac(mac); if (b.created || !version.equals(b.version)) { if (null == bytes) { throw new ProhibitedModification(Reflection.getName( null != o ? o.getClass() : Void.class)); } final OutputStream fout = m.update.write(f + ext); bytes.writeTo(fout); fout.flush(); fout.close(); if (b != f2b.put(f, new Bucket(b.value, false, version, out.isManaged(), out.getSplices()))) { throw new AssertionError(); } } } // to avoid disk searches, put dead weak keys in the cache while (!m.o2wf.isEmpty()) { final Iterator<String> i = m.o2wf.values().iterator(); final String f = i.next(); i.remove(); final Object o = new SymbolicLink(null); final Mac mac = allocMac(root); final Slicer out = new Slicer(true, o, root, new MacOutputStream(mac, null)); out.writeObject(o); out.flush(); out.close(); final ByteArray version = ByteArray.array(mac.doFinal()); freeMac(mac); if (null != f2b.put(f, new Bucket( new CacheReference<String,Object>(f,o,wiped),false,version,true, PowerlessArray.array(new String[0])))) { throw new AssertionError(); } } } static private final String flip = ".flip"; // name of loop turn flipper /* * In testing, allocation of hash objects doubled serialization time, so I'm * keeping a pool of them. Sucky code is like cancer. */ static private final String secret = ".secret"; // name of master MAC key private final ArrayList<Mac> macs = new ArrayList<Mac>(); private SecretKeySpec master; // MAC key generation secret private void setMaster(final ByteArray bits) { master = new SecretKeySpec(bits.toByteArray(), "HmacSHA256"); } private Mac allocMac(final Root local) throws Exception { if (!macs.isEmpty()) { return macs.remove(macs.size() - 1); } if (null == master) { final ByteArray bits = local.fetch(null, secret); setMaster(bits); } final Mac r = Mac.getInstance("HmacSHA256"); r.init(master); return r; } private void freeMac(final Mac h) { macs.add(h); } /** * Determine the type of object stored in a stream. */ static protected String identify(final InputStream s) throws IOException { final DataInputStream data = new DataInputStream(s); final String r; if (ObjectStreamConstants.STREAM_MAGIC != data.readShort()) { r = "! " + StreamCorruptedException.class.getName(); } else { data.readShort(); // skip version number, assume compatible switch (data.read()) { case ObjectStreamConstants.TC_OBJECT: { switch (data.read()) { case ObjectStreamConstants.TC_CLASSDESC: { r = data.readUTF(); } break; case ObjectStreamConstants.TC_PROXYCLASSDESC: { r = data.readInt() > 0 ? data.readUTF() : "proxy"; } break; default: r = "! " + StreamCorruptedException.class.getName(); } } break; case ObjectStreamConstants.TC_ARRAY: { r = "array"; } break; case ObjectStreamConstants.TC_STRING: { r = "string"; } break; case ObjectStreamConstants.TC_LONGSTRING: { r = "long string"; } break; case ObjectStreamConstants.TC_NULL: { r = "null"; } break; default: r = "! " + StreamCorruptedException.class.getName(); } } try { data.close(); } catch (final Exception e) {} return r; } }
true
true
private Object load(final String f) throws FileNotFoundException, RuntimeException { if ("".equals(f)) { return null; } { // check the cache final Bucket b = f2b.get(f); final Object o = null != b ? b.value.get() : null; if (null != o) { if (!b.created) { markDirty(o, b); } return o; } } // remove dead cache entries while (true) { final CacheReference<?,?> r = (CacheReference<?,?>)wiped.poll(); if (null == r) { break; } final Bucket b = f2b.remove(r.key); if (b.value != r) { /* * The entry was reloaded before the soft reference to the * previously loaded value was dequeued. Just put the entry * back in the cache. */ f2b.put(b.value.key, b); } } final int startCycle = stack.lastIndexOf(f); if (-1 != startCycle) { PowerlessArray<String> cycle = PowerlessArray.array(); for (final String at : stack.subList(startCycle,stack.size())) { try { cycle = cycle.with(identify(tx.update.read(at + ext))); } catch (final IOException e) { throw new Error(e); } } throw new CyclicGraph(cycle.with(cycle.get(0))); } InputStream in; try { in = tx.update.read(f + ext); } catch (final FileNotFoundException e) { throw e; } catch (final IOException e) { throw new Error(e); } stack.add(f); try { final Object o; final ByteArray version; final Milestone<Boolean> unmanaged = Milestone.plan(); final HashSet<String> splices = new HashSet<String>(8); if (canonicalize(JODB.secret).equals(f)) { // base case for loading the master secret final ObjectInputStream oin = new ObjectInputStream(in); in = oin; o = oin.readObject(); setMaster((ByteArray)((SymbolicLink)o).target); final Mac mac = allocMac(this); final Slicer out = new Slicer(false, o, this, new MacOutputStream(mac, null)); out.writeObject(o); out.flush(); out.close(); version = ByteArray.array(mac.doFinal()); freeMac(mac); } else { final Mac mac = allocMac(this); in = new MacInputStream(mac, in); final SubstitutionStream oin = new SubstitutionStream(true, code, in) { protected Object resolveObject(Object x) throws IOException { if (x instanceof File) { unmanaged.mark(true); } else if (x instanceof Splice) { splices.add(((Splice)x).name); x = load(((Splice)x).name); } return x; } }; o = oin.readObject(); while (-1 != in.read()) { in.skip(Long.MAX_VALUE); } in = oin; version = ByteArray.array(mac.doFinal()); freeMac(mac); } // may overwrite a dead cache entry f2b.put(f, new Bucket( new CacheReference<String,Object>(f, o, wiped), false, version, !unmanaged.is(), PowerlessArray.array(splices.toArray(new String[0])))); if (null != tx.o2f.put(o, f)) { throw new AssertionError(); } if (!tx.xxx.add(f)) { throw new AssertionError(); } return o; } catch (final InvalidClassException e) { throw new RuntimeException(e); } catch (final ClassNotFoundException e) { throw new RuntimeException(e); } catch (final IOException e) { throw new Error(e); } catch (final RuntimeException e) { throw e; } catch (final Exception e) { throw new RuntimeException(e); } finally { stack.remove(stack.size() - 1); try { in.close(); } catch (final Exception e) {} } }
private Object load(final String f) throws FileNotFoundException, RuntimeException { if ("".equals(f)) { return null; } { // check the cache final Bucket b = f2b.get(f); final Object o = null != b ? b.value.get() : null; if (null != o) { if (!b.created) { markDirty(o, b); } return o; } } // remove dead cache entries while (true) { final CacheReference<?,?> r = (CacheReference<?,?>)wiped.poll(); if (null == r) { break; } final Bucket b = f2b.remove(r.key); if (b.value != r) { /* * The entry was reloaded before the soft reference to the * previously loaded value was dequeued. Just put the entry * back in the cache. */ f2b.put(b.value.key, b); } } final int startCycle = stack.lastIndexOf(f); if (-1 != startCycle) { PowerlessArray<String> cycle = PowerlessArray.array(new String[] {}); for (final String at : stack.subList(startCycle,stack.size())) { try { cycle = cycle.with(identify(tx.update.read(at + ext))); } catch (final IOException e) { throw new Error(e); } } throw new CyclicGraph(cycle.with(cycle.get(0))); } InputStream in; try { in = tx.update.read(f + ext); } catch (final FileNotFoundException e) { throw e; } catch (final IOException e) { throw new Error(e); } stack.add(f); try { final Object o; final ByteArray version; final Milestone<Boolean> unmanaged = Milestone.plan(); final HashSet<String> splices = new HashSet<String>(8); if (canonicalize(JODB.secret).equals(f)) { // base case for loading the master secret final ObjectInputStream oin = new ObjectInputStream(in); in = oin; o = oin.readObject(); setMaster((ByteArray)((SymbolicLink)o).target); final Mac mac = allocMac(this); final Slicer out = new Slicer(false, o, this, new MacOutputStream(mac, null)); out.writeObject(o); out.flush(); out.close(); version = ByteArray.array(mac.doFinal()); freeMac(mac); } else { final Mac mac = allocMac(this); in = new MacInputStream(mac, in); final SubstitutionStream oin = new SubstitutionStream(true, code, in) { protected Object resolveObject(Object x) throws IOException { if (x instanceof File) { unmanaged.mark(true); } else if (x instanceof Splice) { splices.add(((Splice)x).name); x = load(((Splice)x).name); } return x; } }; o = oin.readObject(); while (-1 != in.read()) { in.skip(Long.MAX_VALUE); } in = oin; version = ByteArray.array(mac.doFinal()); freeMac(mac); } // may overwrite a dead cache entry f2b.put(f, new Bucket( new CacheReference<String,Object>(f, o, wiped), false, version, !unmanaged.is(), PowerlessArray.array(splices.toArray(new String[0])))); if (null != tx.o2f.put(o, f)) { throw new AssertionError(); } if (!tx.xxx.add(f)) { throw new AssertionError(); } return o; } catch (final InvalidClassException e) { throw new RuntimeException(e); } catch (final ClassNotFoundException e) { throw new RuntimeException(e); } catch (final IOException e) { throw new Error(e); } catch (final RuntimeException e) { throw e; } catch (final Exception e) { throw new RuntimeException(e); } finally { stack.remove(stack.size() - 1); try { in.close(); } catch (final Exception e) {} } }
diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/command/CommandExecutorTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/command/CommandExecutorTest.java index 3436117dd8..d346550ac8 100644 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/command/CommandExecutorTest.java +++ b/sonar-plugin-api/src/test/java/org/sonar/api/utils/command/CommandExecutorTest.java @@ -1,69 +1,71 @@ /* * Sonar, open source software quality management tool. * Copyright (C) 2008-2011 SonarSource * mailto:contact AT sonarsource DOT com * * Sonar is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.api.utils.command; import org.apache.commons.lang.SystemUtils; import org.junit.Test; import java.io.File; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.number.OrderingComparisons.greaterThanOrEqualTo; import static org.hamcrest.number.OrderingComparisons.lessThan; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; public class CommandExecutorTest { @Test public void shouldEchoArguments() { String executable = getScript("echo"); int exitCode = CommandExecutor.create().execute(Command.create(executable), 1000L); assertThat(exitCode, is(0)); } @Test public void shouldStopWithTimeout() { String executable = getScript("forever"); long start = System.currentTimeMillis(); try { CommandExecutor.create().execute(Command.create(executable), 300L); fail(); } catch (CommandException e) { long duration = System.currentTimeMillis()-start; - assertThat(e.getMessage(), duration, greaterThanOrEqualTo(300L)); + // should test >= 300 but it strangly fails during build on windows. + // The timeout is raised after 297ms (??) + assertThat(e.getMessage(), duration, greaterThanOrEqualTo(290L)); } } @Test(expected = CommandException.class) public void shouldFailIfScriptNotFound() { CommandExecutor.create().execute(Command.create("notfound"), 1000L); } private String getScript(String name) { String filename; if (SystemUtils.IS_OS_WINDOWS) { filename = name + ".bat"; } else { filename = name + ".sh"; } return new File("src/test/scripts/" + filename).getPath(); } }
true
true
public void shouldStopWithTimeout() { String executable = getScript("forever"); long start = System.currentTimeMillis(); try { CommandExecutor.create().execute(Command.create(executable), 300L); fail(); } catch (CommandException e) { long duration = System.currentTimeMillis()-start; assertThat(e.getMessage(), duration, greaterThanOrEqualTo(300L)); } }
public void shouldStopWithTimeout() { String executable = getScript("forever"); long start = System.currentTimeMillis(); try { CommandExecutor.create().execute(Command.create(executable), 300L); fail(); } catch (CommandException e) { long duration = System.currentTimeMillis()-start; // should test >= 300 but it strangly fails during build on windows. // The timeout is raised after 297ms (??) assertThat(e.getMessage(), duration, greaterThanOrEqualTo(290L)); } }
diff --git a/launchpad/launchpad-servlets/src/main/java/org/apache/sling/launchpad/servlets/UjaxInfoServlet.java b/launchpad/launchpad-servlets/src/main/java/org/apache/sling/launchpad/servlets/UjaxInfoServlet.java index eeee1104a5..ff1f3f6038 100644 --- a/launchpad/launchpad-servlets/src/main/java/org/apache/sling/launchpad/servlets/UjaxInfoServlet.java +++ b/launchpad/launchpad-servlets/src/main/java/org/apache/sling/launchpad/servlets/UjaxInfoServlet.java @@ -1,93 +1,95 @@ /* * 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.sling.launchpad.servlets; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import org.apache.sling.api.SlingException; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.SlingSafeMethodsServlet; import org.apache.sling.commons.json.JSONException; import org.apache.sling.commons.json.io.JSONWriter; public class UjaxInfoServlet extends SlingSafeMethodsServlet { /** Handle requests which start with this path */ public static String PATH_PREFIX = "/ujax:"; @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { Map <String, Object> data = null; if(request.getPathInfo().equals(PATH_PREFIX + "sessionInfo.json")) { try { data = getSessionInfo(request); } catch(RepositoryException re) { throw new ServletException("RepositoryException in getSessionInfo(): " + re,re); } } if (data== null) { response.sendError(HttpServletResponse.SC_NOT_FOUND,request.getPathInfo()); + return; } // render data in JSON format response.setContentType("application/json"); - final Writer out = new OutputStreamWriter(response.getOutputStream()); + response.setCharacterEncoding("UTF-8"); + final Writer out = response.getWriter(); final JSONWriter w = new JSONWriter(out); try { w.object(); for(Map.Entry<String, Object> e : data.entrySet()) { w.key(e.getKey()); w.value(e.getValue()); } w.endObject(); } catch (JSONException jse) { out.write(jse.toString()); } finally { out.flush(); } } protected Map<String, Object> getSessionInfo(SlingHttpServletRequest request) throws RepositoryException, SlingException { final Map<String, Object> result = new HashMap<String, Object>(); final Session s = (Session)request.getAttribute(Session.class.getName()); result.put("workspace",s.getWorkspace().getName()); result.put("userID",s.getUserID()); return result; } }
false
true
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { Map <String, Object> data = null; if(request.getPathInfo().equals(PATH_PREFIX + "sessionInfo.json")) { try { data = getSessionInfo(request); } catch(RepositoryException re) { throw new ServletException("RepositoryException in getSessionInfo(): " + re,re); } } if (data== null) { response.sendError(HttpServletResponse.SC_NOT_FOUND,request.getPathInfo()); } // render data in JSON format response.setContentType("application/json"); final Writer out = new OutputStreamWriter(response.getOutputStream()); final JSONWriter w = new JSONWriter(out); try { w.object(); for(Map.Entry<String, Object> e : data.entrySet()) { w.key(e.getKey()); w.value(e.getValue()); } w.endObject(); } catch (JSONException jse) { out.write(jse.toString()); } finally { out.flush(); } }
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { Map <String, Object> data = null; if(request.getPathInfo().equals(PATH_PREFIX + "sessionInfo.json")) { try { data = getSessionInfo(request); } catch(RepositoryException re) { throw new ServletException("RepositoryException in getSessionInfo(): " + re,re); } } if (data== null) { response.sendError(HttpServletResponse.SC_NOT_FOUND,request.getPathInfo()); return; } // render data in JSON format response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); final Writer out = response.getWriter(); final JSONWriter w = new JSONWriter(out); try { w.object(); for(Map.Entry<String, Object> e : data.entrySet()) { w.key(e.getKey()); w.value(e.getValue()); } w.endObject(); } catch (JSONException jse) { out.write(jse.toString()); } finally { out.flush(); } }
diff --git a/src/de/jungblut/math/dense/DenseDoubleMatrix.java b/src/de/jungblut/math/dense/DenseDoubleMatrix.java index 9eb80f9..565bf0a 100644 --- a/src/de/jungblut/math/dense/DenseDoubleMatrix.java +++ b/src/de/jungblut/math/dense/DenseDoubleMatrix.java @@ -1,580 +1,581 @@ package de.jungblut.math.dense; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Random; import org.apache.commons.math3.util.FastMath; import org.jblas.MyNativeBlasLibraryLoader; import de.jungblut.math.DoubleMatrix; import de.jungblut.math.DoubleVector; import de.jungblut.math.DoubleVector.DoubleVectorElement; /** * Dense double matrix implementation. Internally a column major ordering is * used, just like in any other scientific language like FORTRAN or MATLAB. This * is especially better for Java in terms of memory usage, as every row of the * matrix has additional array/object overhead to deal with. */ public final class DenseDoubleMatrix implements DoubleMatrix { private static final int JBLAS_COLUMN_THRESHOLD = 100; private static final int JBLAS_ROW_THRESHOLD = 100; private static final boolean JBLAS_AVAILABLE; static { JBLAS_AVAILABLE = MyNativeBlasLibraryLoader.loadLibraryAndCheckErrors(); } /** * We use a column major format to store the matrix, as two dimensional arrays * have a high waste of space. */ private final double[] matrix; private final int numRows; private final int numColumns; /** * Creates a new empty matrix from the rows and columns. * * @param rows the num of rows. * @param columns the num of columns. */ public DenseDoubleMatrix(int rows, int columns) { this.numRows = rows; this.numColumns = columns; this.matrix = new double[columns * rows]; } /** * Creates a new empty matrix from the rows and columns filled with the given * default value. * * @param rows the num of rows. * @param columns the num of columns. * @param defaultValue the default value. */ public DenseDoubleMatrix(int rows, int columns, double defaultValue) { this(rows, columns); Arrays.fill(matrix, defaultValue); } /** * Creates a new empty matrix from the rows and columns filled with the given * random values. * * @param rows the num of rows. * @param columns the num of columns. * @param rand the random instance to use. */ public DenseDoubleMatrix(int rows, int columns, Random rand) { this(rows, columns); for (int i = 0; i < matrix.length; i++) { matrix[i] = rand.nextDouble(); } } /** * Simple copy constructor, does a deep copy of the given parameter. * * @param otherMatrix the other matrix. */ public DenseDoubleMatrix(double[][] otherMatrix) { this(otherMatrix.length, otherMatrix[0].length); for (int row = 0; row < otherMatrix.length; row++) { for (int col = 0; col < otherMatrix[row].length; col++) { set(row, col, otherMatrix[row][col]); } } } /** * Generates a matrix out of a vector list. it treats the entries as rows and * the vector itself contains the values of the columns. * * @param vectorArray the list of vectors. */ public DenseDoubleMatrix(List<DoubleVector> vec) { this(vec.size(), vec.get(0).getDimension()); int row = 0; for (DoubleVector value : vec) { for (int col = 0; col < value.getDimension(); col++) { set(row, col, value.get(col)); } row++; } } /** * Generates a matrix out of a vector array. It treats the array entries as * rows and the vector itself contains the values of the columns. * * @param vectorArray the array of vectors. */ public DenseDoubleMatrix(DoubleVector[] vectorArray) { this(Arrays.asList(vectorArray)); } /** * Creates a new matrix with the given vector into the first column and the * other matrix to the other columns. This is usually used in machine learning * algorithms that add a bias on the zero-index column. * * @param first the new first column. * @param otherMatrix the other matrix to set on from the second column. */ public DenseDoubleMatrix(DenseDoubleVector first, DoubleMatrix otherMatrix) { this(otherMatrix.getRowCount(), otherMatrix.getColumnCount() + 1); // copy the first column System.arraycopy(first.toArray(), 0, matrix, 0, first.getDimension()); int offset = first.getDimension(); for (int col : otherMatrix.columnIndices()) { double[] clv = otherMatrix.getColumnVector(col).toArray(); System.arraycopy(clv, 0, matrix, offset, clv.length); offset += clv.length; } } /** * Copies the given double array v into the first row of this matrix, and * creates this with the number of given rows and columns. This is basically a * conversion case for column major storage to this class (in the past this * was backed by a two-dimensional array, thus the conversion needs). * * @param v the values to put into the first row. * @param rows the number of rows. * @param columns the number of columns. */ public DenseDoubleMatrix(double[] v, int rows, int columns) { this(v, rows, columns, true); } private DenseDoubleMatrix(double[] v, int rows, int columns, boolean copy) { this.numRows = rows; this.numColumns = columns; if (copy) { this.matrix = new double[columns * rows]; System.arraycopy(v, 0, this.matrix, 0, v.length); } else { this.matrix = v; } } /* * ------------CONSTRUCTOR END------------ */ /** * @return the internal matrix representation, no defensive copy is made. */ public double[] getColumnMajorMatrix() { return this.matrix; } @Override public double get(int row, int col) { return matrix[translate(row, col, numRows)]; } /** * Gets a whole column of the matrix as a double array. */ public double[] getColumn(int col) { double[] column = new double[numRows]; int offset = translate(0, col, numRows); for (int i = 0; i < column.length; i++) { column[i] = matrix[offset + i]; } return column; } @Override public int getColumnCount() { return numColumns; } @Override public DoubleVector getColumnVector(int col) { return new DenseDoubleVector(getColumn(col)); } @Override public double[][] toArray() { double[][] mat = new double[getRowCount()][getColumnCount()]; int index = 0; for (int col = 0; col < getColumnCount(); col++) { for (int row = 0; row < getRowCount(); row++) { mat[row][col] = matrix[index++]; } } return mat; } /** * Get a single row of the matrix as a double array. */ public double[] getRow(int row) { double[] rowArray = new double[getColumnCount()]; for (int i = 0; i < getColumnCount(); i++) { rowArray[i] = get(row, i); } return rowArray; } @Override public int getRowCount() { return numRows; } @Override public DoubleVector getRowVector(int row) { return new DenseDoubleVector(getRow(row)); } @Override public void set(int row, int col, double value) { this.matrix[translate(row, col, numRows)] = value; } /** * Sets the row to a given double array. */ public void setRow(int row, double[] value) { for (int i = 0; i < value.length; i++) { this.matrix[translate(row, i, numRows)] = value[i]; } } /** * Sets the column to a given double array. */ public void setColumn(int col, double[] values) { int offset = translate(0, col, numRows); System.arraycopy(values, 0, matrix, offset, values.length); } @Override public void setColumnVector(int col, DoubleVector column) { this.setColumn(col, column.toArray()); } @Override public void setRowVector(int rowIndex, DoubleVector row) { this.setRow(rowIndex, row.toArray()); } @Override public DenseDoubleMatrix multiply(double scalar) { double[] csjr = new double[this.numRows * this.numColumns]; for (int i = 0; i < matrix.length; i++) { csjr[i] = this.matrix[i] * scalar; } return new DenseDoubleMatrix(csjr, this.numRows, this.numColumns, false); } @Override public DoubleMatrix multiply(DoubleMatrix other) { DenseDoubleMatrix matrix = null; int m = this.numRows; int n = this.numColumns; int p = other.getColumnCount(); // only execute when we have JBLAS and our matrix is bigger than 50x50 if (JBLAS_AVAILABLE && m > JBLAS_ROW_THRESHOLD && n > JBLAS_COLUMN_THRESHOLD && !other.isSparse()) { org.jblas.DoubleMatrix jblasThis = new org.jblas.DoubleMatrix(m, n, this.matrix); - org.jblas.DoubleMatrix jblasOther = new org.jblas.DoubleMatrix(m, p, + org.jblas.DoubleMatrix jblasOther = new org.jblas.DoubleMatrix( + other.getRowCount(), other.getColumnCount(), ((DenseDoubleMatrix) other).matrix); org.jblas.DoubleMatrix jblasRes = new org.jblas.DoubleMatrix(m, p); jblasThis.mmuli(jblasOther, jblasRes); // copy the result back matrix = new DenseDoubleMatrix(jblasRes.toArray(), this.getRowCount(), other.getColumnCount(), false); } else { matrix = new DenseDoubleMatrix(m, p); for (int k = 0; k < n; k++) { for (int i = 0; i < m; i++) { for (int j = 0; j < p; j++) { matrix.set(i, j, matrix.get(i, j) + get(i, k) * other.get(k, j)); } } } } return matrix; } @Override public DoubleMatrix multiplyElementWise(DoubleMatrix other) { DenseDoubleMatrix matrix = new DenseDoubleMatrix(this.numRows, this.numColumns); for (int i = 0; i < numRows; i++) { for (int j = 0; j < numColumns; j++) { matrix.set(i, j, this.get(i, j) * (other.get(i, j))); } } return matrix; } @Override public DoubleVector multiplyVectorRow(DoubleVector v) { DoubleVector vector = new DenseDoubleVector(this.getRowCount()); for (int row = 0; row < numRows; row++) { double sum = 0.0d; if (v.isSparse()) { Iterator<DoubleVectorElement> iterateNonZero = v.iterateNonZero(); while (iterateNonZero.hasNext()) { DoubleVectorElement next = iterateNonZero.next(); sum += (matrix[translate(row, next.getIndex(), numRows)] * next .getValue()); } } else { for (int col = 0; col < numColumns; col++) { sum += (matrix[translate(row, col, numRows)] * v.get(col)); } } vector.set(row, sum); } return vector; } @Override public DoubleVector multiplyVectorColumn(DoubleVector v) { DoubleVector vector = new DenseDoubleVector(this.getColumnCount()); for (int col = 0; col < numColumns; col++) { double sum = 0.0d; for (int row = 0; row < numRows; row++) { sum += (matrix[translate(row, col, numRows)] * v.get(row)); } vector.set(col, sum); } return vector; } @Override public DenseDoubleMatrix transpose() { DenseDoubleMatrix m = new DenseDoubleMatrix(this.numColumns, this.numRows); for (int i = 0; i < numRows; i++) { for (int j = 0; j < numColumns; j++) { m.set(j, i, this.matrix[translate(i, j, numRows)]); } } return m; } @Override public DenseDoubleMatrix subtractBy(double amount) { double[] csjr = new double[this.numRows * this.numColumns]; for (int i = 0; i < matrix.length; i++) { csjr[i] = amount - this.matrix[i]; } return new DenseDoubleMatrix(csjr, this.numRows, this.numColumns, false); } @Override public DenseDoubleMatrix subtract(double amount) { double[] csjr = new double[this.numRows * this.numColumns]; for (int i = 0; i < matrix.length; i++) { csjr[i] = this.matrix[i] - amount; } return new DenseDoubleMatrix(csjr, this.numRows, this.numColumns, false); } @Override public DoubleMatrix subtract(DoubleMatrix other) { DoubleMatrix m = new DenseDoubleMatrix(this.numRows, this.numColumns); for (int i = 0; i < numRows; i++) { for (int j = 0; j < numColumns; j++) { m.set(i, j, this.matrix[translate(i, j, numRows)] - other.get(i, j)); } } return m; } @Override public DenseDoubleMatrix subtract(DoubleVector vec) { DenseDoubleMatrix cop = new DenseDoubleMatrix(this.getRowCount(), this.getColumnCount()); for (int i = 0; i < this.getColumnCount(); i++) { cop.setColumnVector(i, getColumnVector(i).subtract(vec)); } return cop; } @Override public DoubleMatrix divide(DoubleVector vec) { DoubleMatrix cop = new DenseDoubleMatrix(this.getRowCount(), this.getColumnCount()); for (int i = 0; i < this.getColumnCount(); i++) { cop.setColumnVector(i, getColumnVector(i).divide(vec)); } return cop; } @Override public DoubleMatrix divide(DoubleMatrix other) { DoubleMatrix m = new DenseDoubleMatrix(this.numRows, this.numColumns); for (int i = 0; i < numRows; i++) { for (int j = 0; j < numColumns; j++) { m.set(i, j, this.matrix[translate(i, j, numRows)] / other.get(i, j)); } } return m; } @Override public DoubleMatrix divide(double scalar) { double[] csjr = new double[this.numRows * this.numColumns]; for (int i = 0; i < matrix.length; i++) { csjr[i] = this.matrix[i] / scalar; } return new DenseDoubleMatrix(csjr, this.numRows, this.numColumns, false); } @Override public DoubleMatrix add(DoubleMatrix other) { DoubleMatrix m = new DenseDoubleMatrix(this.numRows, this.numColumns); for (int i = 0; i < numRows; i++) { for (int j = 0; j < numColumns; j++) { m.set(i, j, this.matrix[translate(i, j, numRows)] + other.get(i, j)); } } return m; } @Override public DoubleMatrix pow(double x) { double[] csjr = new double[this.numRows * this.numColumns]; for (int i = 0; i < matrix.length; i++) { if (x == 2d) { csjr[i] = this.matrix[i] * this.matrix[i]; } else { csjr[i] = FastMath.pow(this.matrix[i], x); } } return new DenseDoubleMatrix(csjr, this.numRows, this.numColumns, false); } @Override public double max(int column) { double max = Double.MIN_VALUE; int offset = translate(0, column, numRows); for (int i = 0; i < getRowCount(); i++) { double d = matrix[offset + i]; if (d > max) { max = d; } } return max; } @Override public double min(int column) { double min = Double.MAX_VALUE; int offset = translate(0, column, numRows); for (int i = 0; i < getRowCount(); i++) { double d = matrix[offset + i]; if (d < min) { min = d; } } return min; } @Override public DoubleMatrix slice(int rows, int cols) { return slice(0, rows, 0, cols); } @Override public DoubleMatrix slice(int rowOffset, int rowMax, int colOffset, int colMax) { DenseDoubleMatrix m = new DenseDoubleMatrix(rowMax - rowOffset, colMax - colOffset); for (int row = rowOffset; row < rowMax; row++) { for (int col = colOffset; col < colMax; col++) { m.set(row - rowOffset, col - colOffset, this.get(row, col)); } } return m; } @Override public boolean isSparse() { return false; } @Override public double sum() { double x = 0.0d; for (int i = 0; i < matrix.length; i++) { x += Math.abs(matrix[i]); } return x; } @Override public int[] columnIndices() { int[] x = new int[getColumnCount()]; for (int i = 0; i < getColumnCount(); i++) x[i] = i; return x; } @Override public int[] rowIndices() { int[] x = new int[getRowCount()]; for (int i = 0; i < getRowCount(); i++) x[i] = i; return x; } @Override public DoubleMatrix deepCopy() { return new DenseDoubleMatrix(toArray()); } @Override public String toString() { if (numRows * numColumns < 100) { StringBuilder sb = new StringBuilder(); double[][] array = toArray(); for (int i = 0; i < numRows; i++) { sb.append(Arrays.toString(array[i])); sb.append('\n'); } return sb.toString(); } else { return sizeToString(); } } /** * Returns the size of the matrix as string (ROWSxCOLUMNS). */ public String sizeToString() { return numRows + "x" + numColumns; } /** * Translates the 2D addressing to a single offset in the 1D matrix. * * @param row the row to get. * @param col the column to get. * @param numRows the number of rows in the matrix. * @return an offset in the 1D matrix that contains the row/col value. */ private static int translate(int row, int col, int numRows) { return row + col * numRows; } }
true
true
public DoubleMatrix multiply(DoubleMatrix other) { DenseDoubleMatrix matrix = null; int m = this.numRows; int n = this.numColumns; int p = other.getColumnCount(); // only execute when we have JBLAS and our matrix is bigger than 50x50 if (JBLAS_AVAILABLE && m > JBLAS_ROW_THRESHOLD && n > JBLAS_COLUMN_THRESHOLD && !other.isSparse()) { org.jblas.DoubleMatrix jblasThis = new org.jblas.DoubleMatrix(m, n, this.matrix); org.jblas.DoubleMatrix jblasOther = new org.jblas.DoubleMatrix(m, p, ((DenseDoubleMatrix) other).matrix); org.jblas.DoubleMatrix jblasRes = new org.jblas.DoubleMatrix(m, p); jblasThis.mmuli(jblasOther, jblasRes); // copy the result back matrix = new DenseDoubleMatrix(jblasRes.toArray(), this.getRowCount(), other.getColumnCount(), false); } else { matrix = new DenseDoubleMatrix(m, p); for (int k = 0; k < n; k++) { for (int i = 0; i < m; i++) { for (int j = 0; j < p; j++) { matrix.set(i, j, matrix.get(i, j) + get(i, k) * other.get(k, j)); } } } } return matrix; }
public DoubleMatrix multiply(DoubleMatrix other) { DenseDoubleMatrix matrix = null; int m = this.numRows; int n = this.numColumns; int p = other.getColumnCount(); // only execute when we have JBLAS and our matrix is bigger than 50x50 if (JBLAS_AVAILABLE && m > JBLAS_ROW_THRESHOLD && n > JBLAS_COLUMN_THRESHOLD && !other.isSparse()) { org.jblas.DoubleMatrix jblasThis = new org.jblas.DoubleMatrix(m, n, this.matrix); org.jblas.DoubleMatrix jblasOther = new org.jblas.DoubleMatrix( other.getRowCount(), other.getColumnCount(), ((DenseDoubleMatrix) other).matrix); org.jblas.DoubleMatrix jblasRes = new org.jblas.DoubleMatrix(m, p); jblasThis.mmuli(jblasOther, jblasRes); // copy the result back matrix = new DenseDoubleMatrix(jblasRes.toArray(), this.getRowCount(), other.getColumnCount(), false); } else { matrix = new DenseDoubleMatrix(m, p); for (int k = 0; k < n; k++) { for (int i = 0; i < m; i++) { for (int j = 0; j < p; j++) { matrix.set(i, j, matrix.get(i, j) + get(i, k) * other.get(k, j)); } } } } return matrix; }
diff --git a/src/org/encog/persist/persistors/generic/XML2Object.java b/src/org/encog/persist/persistors/generic/XML2Object.java index 8cc785c41..55cbf46b1 100644 --- a/src/org/encog/persist/persistors/generic/XML2Object.java +++ b/src/org/encog/persist/persistors/generic/XML2Object.java @@ -1,269 +1,269 @@ /* * Encog(tm) Core v2.4 * http://www.heatonresearch.com/encog/ * http://code.google.com/p/encog-java/ * * Copyright 2008-2010 by Heaton Research Inc. * * Released under the LGPL. * * 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. * * Encog and Heaton Research are Trademarks of Heaton Research, Inc. * For information on Heaton Research trademarks, visit: * * http://www.heatonresearch.com/copyright.html */ package org.encog.persist.persistors.generic; import java.io.File; import java.lang.reflect.Field; import java.util.Collection; import org.encog.EncogError; import org.encog.parse.tags.Tag.Type; import org.encog.parse.tags.read.ReadXML; import org.encog.persist.EncogPersistedObject; import org.encog.persist.PersistError; import org.encog.util.ReflectionUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A generic class used to take an XML segment and produce an object for it. * Some of the Encog persistors make use of this class. The Encog generic * persistor makes use of this class. * * @author jheaton * */ public class XML2Object { /** * The object mapper to use to resolve references. */ private final ObjectMapper mapper = new ObjectMapper(); /** * Used to read the XML. */ private ReadXML in; /** * The logging object. */ @SuppressWarnings("unused") private final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * Load an object from XML. * * @param in * The XML reader. * @param target * The object to load. * @throws IllegalAccessException * @throws IllegalArgumentException */ public void load(final ReadXML in, final EncogPersistedObject target) { this.in = in; this.mapper.clear(); target.setName(in.getTag().getAttributeValue("name")); target.setDescription(in.getTag().getAttributeValue("description")); loadActualObject(null, target); this.mapper.resolve(); } /** * Load an object. * * @param objectField * The object's field. * @param target The object that will get the value. */ @SuppressWarnings("unchecked") private void loadActualObject(final Field objectField, final Object target) { try { // handle attributes for (final String key : this.in.getTag().getAttributes().keySet()) { if (key.equals("native")) { continue; } // see if there is an id if (key.equals(Object2XML.REFF_ID)) { final int ref = Integer.parseInt(this.in.getTag() .getAttributeValue(Object2XML.REFF_ID)); this.mapper.addObjectMapping(ref, target); continue; } final Field field = ReflectionUtil.findField(target.getClass(), key); if( field!=null ) { final String value = this.in.getTag().getAttributeValue(key); setFieldValue(field, target, value); } } // handle properties while (this.in.readToTag()) { if (this.in.getTag().getType() == Type.BEGIN) { final String tagName = this.in.getTag().getName(); final Field field = ReflectionUtil.findField(target .getClass(), tagName); if (field == null) { continue; } field.setAccessible(true); final Object currentValue = field.get(target); Class<?> type = field.getType(); if( type.isEnum() ) { final String value = this.in.readTextToTag(); setFieldValue(field, target, value); } - else if (ReflectionUtil.isPrimitive(currentValue)) { + else if( (type == String.class) || type.isPrimitive() ) { final String value = this.in.readTextToTag(); setFieldValue(field, target, value); } else if (currentValue instanceof Collection) { loadCollection((Collection<Object>) currentValue); } else if (field.getType() == File.class) { final String value = this.in.readTextToTag(); final File file = new File(value); field.set(target, file); } else { this.in.readToTag(); if( this.in.getTag().getType()!=Type.END) { final Object nextObject = loadObject(field, target); field.set(target, nextObject); } } } else if (this.in.getTag().getType() == Type.END) { if (this.in.getTag().getName().equals( target.getClass().getSimpleName())) { return; } } } } catch (final IllegalArgumentException e) { throw new EncogError(e); } catch (final IllegalAccessException e) { throw new EncogError(e); } catch (final InstantiationException e) { throw new EncogError(e); } } /** * Load a collection. * @param collection The collection to load. */ private void loadCollection(final Collection<Object> collection) { try { while (this.in.readToTag()) { if (this.in.getTag().getType() == Type.BEGIN) { final String tagName = this.in.getTag().getName(); final Class< ? > c = ReflectionUtil .resolveEncogClass(tagName); final Object target = c.newInstance(); loadActualObject(null, target); collection.add(target); } else if (this.in.getTag().getType() == Type.END) { return; } } } catch (final InstantiationException e) { throw new EncogError(e); } catch (final IllegalAccessException e) { throw new EncogError(e); } } /** * Load an object and handle reference if needed. * @param objectField The field. * @param parent The object that holds the field. * @return The loaded object. * @throws InstantiationException An error. * @throws IllegalAccessException An error. */ private Object loadObject(final Field objectField, final Object parent) throws InstantiationException, IllegalAccessException { final String ref = this.in.getTag().getAttributeValue("ref"); // handle ref if (ref != null) { final int ref2 = Integer.parseInt(this.in.getTag() .getAttributeValue("ref")); this.mapper.addFieldMapping(ref2, objectField, parent); this.in.readToTag(); return null; } else { final Class< ? > c = ReflectionUtil.resolveEncogClass(this.in .getTag().getName()); if (c == null) { throw new PersistError("Can't create class: " + this.in.getTag().getName()); } final Object obj = c.newInstance(); loadActualObject(objectField, obj); return obj; } } /** * Set a field value. * @param field The field to set. * @param target The object that contains the field. * @param value The field value. */ private void setFieldValue(final Field field, final Object target, final String value) { try { final Class< ? > type = field.getType(); if( type.isEnum() ) { field.set(target, ReflectionUtil.resolveEnum(field, value)); } else if (type == long.class) { field.setLong(target, Long.parseLong(value)); } else if (type == int.class) { field.setInt(target, Integer.parseInt(value)); } else if (type == short.class) { field.setShort(target, Short.parseShort(value)); } else if (type == double.class) { field.setDouble(target, Double.parseDouble(value)); } else if (type == float.class) { field.setDouble(target, Float.parseFloat(value)); } else if (type == String.class) { field.set(target, value); } else if (type == boolean.class) { field.setBoolean(target, value.equalsIgnoreCase("true") ? Boolean.TRUE : Boolean.FALSE); } } catch (final IllegalAccessException e) { throw new PersistError("Error parsing field:" + field.getName(),e); } catch (final NumberFormatException e) { throw new PersistError("Error on field:" + field.getName(),e); } } }
true
true
private void loadActualObject(final Field objectField, final Object target) { try { // handle attributes for (final String key : this.in.getTag().getAttributes().keySet()) { if (key.equals("native")) { continue; } // see if there is an id if (key.equals(Object2XML.REFF_ID)) { final int ref = Integer.parseInt(this.in.getTag() .getAttributeValue(Object2XML.REFF_ID)); this.mapper.addObjectMapping(ref, target); continue; } final Field field = ReflectionUtil.findField(target.getClass(), key); if( field!=null ) { final String value = this.in.getTag().getAttributeValue(key); setFieldValue(field, target, value); } } // handle properties while (this.in.readToTag()) { if (this.in.getTag().getType() == Type.BEGIN) { final String tagName = this.in.getTag().getName(); final Field field = ReflectionUtil.findField(target .getClass(), tagName); if (field == null) { continue; } field.setAccessible(true); final Object currentValue = field.get(target); Class<?> type = field.getType(); if( type.isEnum() ) { final String value = this.in.readTextToTag(); setFieldValue(field, target, value); } else if (ReflectionUtil.isPrimitive(currentValue)) { final String value = this.in.readTextToTag(); setFieldValue(field, target, value); } else if (currentValue instanceof Collection) { loadCollection((Collection<Object>) currentValue); } else if (field.getType() == File.class) { final String value = this.in.readTextToTag(); final File file = new File(value); field.set(target, file); } else { this.in.readToTag(); if( this.in.getTag().getType()!=Type.END) { final Object nextObject = loadObject(field, target); field.set(target, nextObject); } } } else if (this.in.getTag().getType() == Type.END) { if (this.in.getTag().getName().equals( target.getClass().getSimpleName())) { return; } } } } catch (final IllegalArgumentException e) { throw new EncogError(e); } catch (final IllegalAccessException e) { throw new EncogError(e); } catch (final InstantiationException e) { throw new EncogError(e); } }
private void loadActualObject(final Field objectField, final Object target) { try { // handle attributes for (final String key : this.in.getTag().getAttributes().keySet()) { if (key.equals("native")) { continue; } // see if there is an id if (key.equals(Object2XML.REFF_ID)) { final int ref = Integer.parseInt(this.in.getTag() .getAttributeValue(Object2XML.REFF_ID)); this.mapper.addObjectMapping(ref, target); continue; } final Field field = ReflectionUtil.findField(target.getClass(), key); if( field!=null ) { final String value = this.in.getTag().getAttributeValue(key); setFieldValue(field, target, value); } } // handle properties while (this.in.readToTag()) { if (this.in.getTag().getType() == Type.BEGIN) { final String tagName = this.in.getTag().getName(); final Field field = ReflectionUtil.findField(target .getClass(), tagName); if (field == null) { continue; } field.setAccessible(true); final Object currentValue = field.get(target); Class<?> type = field.getType(); if( type.isEnum() ) { final String value = this.in.readTextToTag(); setFieldValue(field, target, value); } else if( (type == String.class) || type.isPrimitive() ) { final String value = this.in.readTextToTag(); setFieldValue(field, target, value); } else if (currentValue instanceof Collection) { loadCollection((Collection<Object>) currentValue); } else if (field.getType() == File.class) { final String value = this.in.readTextToTag(); final File file = new File(value); field.set(target, file); } else { this.in.readToTag(); if( this.in.getTag().getType()!=Type.END) { final Object nextObject = loadObject(field, target); field.set(target, nextObject); } } } else if (this.in.getTag().getType() == Type.END) { if (this.in.getTag().getName().equals( target.getClass().getSimpleName())) { return; } } } } catch (final IllegalArgumentException e) { throw new EncogError(e); } catch (final IllegalAccessException e) { throw new EncogError(e); } catch (final InstantiationException e) { throw new EncogError(e); } }
diff --git a/versat/src/com/bu/TransitionDay.java b/versat/src/com/bu/TransitionDay.java index 18ebd24..eb453a4 100644 --- a/versat/src/com/bu/TransitionDay.java +++ b/versat/src/com/bu/TransitionDay.java @@ -1,382 +1,382 @@ package com.bu; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.concurrent.atomic.AtomicInteger; import com.dao.FundDao; import com.dao.FundPriceHistoryDao; import com.dao.PositionDao; import com.dao.SysuserDao; import com.dao.TransactionDao; import com.dao.TransitionDao; import com.pojo.Fund; import com.pojo.FundPriceHistory; import com.pojo.Position; import com.pojo.Sysuser; import com.pojo.Transaction; public class TransitionDay { public static final int SUCCESS = 0; public static final int FAILED = -1; public static final int RETRY = -2; public static final int NEWFUNDS = -3; // funds need vale private static TransitionDay instance = new TransitionDay(); private boolean inTransition; private AtomicInteger inProcessingTransition; private TransitionDay() { inTransition = false; inProcessingTransition = new AtomicInteger(0); } public static TransitionDay getInstance() { return instance; } public synchronized boolean getAndSetinTransition() { if (inTransition) { return false; } else { inTransition = true; return true; } } private boolean beforeTransition() { inProcessingTransition.getAndIncrement(); if (!inTransition) { return true; } else { inProcessingTransition.getAndDecrement(); return false; } } public FundPriceHistory getCurHistory(int idFund) throws Exception { return FundPriceHistoryDao.getInstance().getLatestFundHistoryById( idFund); } public ArrayList<Fund> getFundList() { try { Date d = FundPriceHistoryDao.getInstance().getLastDay(); ArrayList<Fund> funds = FundDao.getInstance().getAllList(); if (d != null) { ArrayList<FundPriceHistory> fundList = FundPriceHistoryDao .getInstance().getListByDate(d); HashMap<Integer, Double> lastprice = new HashMap<Integer, Double>(); for (FundPriceHistory f : fundList) { Fund test = f.getFund(); lastprice.put(test.getId(), f.getPrice() / 100.0); } if (funds != null) { for (Fund fund : funds) { if (lastprice.containsKey(fund.getId())) { fund.setLastDay(lastprice.get(fund.getId())); } } } } return funds; } catch (Exception e) { e.printStackTrace(); } return new ArrayList<Fund>(); } public int commitTransitionDay(ArrayList<Fund> commitFunds, Date date) { int ret = SUCCESS; ArrayList<Fund> funds = null; try { funds = FundDao.getInstance().getAllList(); } catch (Exception e) { e.printStackTrace(); return FAILED; } HashSet<Integer> fundsMask = new HashSet<Integer>(); for (Fund commitFund : commitFunds) { fundsMask.add(commitFund.getId()); } if (funds != null) { for (Fund fund : funds) { if (!fundsMask.contains(fund.getId())) { commitFunds.add(fund); ret = NEWFUNDS; } } } if (ret == NEWFUNDS) { return ret; } else { if (getAndSetinTransition()) { while (inProcessingTransition.get() != 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } Fund fundToLink = new Fund(); for (Fund commitFund : commitFunds) { try { FundPriceHistory fundPriceHistoryCur = getCurHistory(commitFund .getId()); fundPriceHistoryCur.setPriceDate(date); fundPriceHistoryCur.setPrice((long) (commitFund .getCur() * 100)); FundPriceHistoryDao.getInstance().update( fundPriceHistoryCur); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } FundPriceHistory fundPriceHistorynew = new FundPriceHistory(); fundToLink.setId(commitFund.getId()); fundPriceHistorynew.setFund(fundToLink); try { FundPriceHistoryDao.getInstance().create( fundPriceHistorynew); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } ArrayList<Transaction> trans = null; try { trans = TransactionDao.getInstance().getTransByStatus(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } inTransition = false; TransitionProcessing tp = new TransitionProcessing(date, trans); tp.start(); // NEED to add thread to handle the all transactions; return SUCCESS; } else { return RETRY; } } } public Date getLastTransitionDay() { Date date = null; try { date = FundPriceHistoryDao.getInstance().getLastDay(); } catch (Exception e) { e.printStackTrace(); } if (date == null) { return new Date(); } System.out.println(date.toString()); return date; } public int newTransaction(int idUser, int idFund, Transaction transaction) { int ret = SUCCESS; int retryTime = 3; while (retryTime > 0) { if (beforeTransition()) { try { Sysuser user = SysuserDao.getInstance().getByUserId(idUser); FundPriceHistory fph = getCurHistory(idFund); if (user == null || fph == null) { ret = FAILED; } else { transaction.setSysuser(user); transaction.setFundPriceHistory(fph); // transaction.setExecuteDate(fph.getPriceDate()); TransactionDao.getInstance().createTransaction( transaction); } } catch (Exception e) { ret = FAILED; e.printStackTrace(); } finally { retryTime = -1; inProcessingTransition.getAndDecrement(); } } retryTime--; try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } if (retryTime == 0) { return RETRY; } return ret; } public int newTransaction(int idUser, Transaction transaction) { int ret = SUCCESS; int retryTime = 3; while (retryTime > 0) { if (beforeTransition()) { try { Sysuser user = SysuserDao.getInstance().getByUserId(idUser); if (user == null) { ret = FAILED; } else { transaction.setSysuser(user); // transaction.setExecuteDate(getLastTransitionDay()); TransactionDao.getInstance().createTransaction( transaction); } } catch (Exception e) { ret = FAILED; e.printStackTrace(); } finally { retryTime = -1; inProcessingTransition.getAndDecrement(); } } retryTime--; try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } if (retryTime == 0) { return RETRY; } return ret; } public static class TransitionProcessing extends Thread { private Date date; private ArrayList<Transaction> trans; public TransitionProcessing(Date date, ArrayList<Transaction> trans) { this.date = date; this.trans = trans; } @Override public void run() { try { if (this.trans != null) { for (Transaction tran : trans) { operation(tran, this.date); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // TODO Auto-generated method stub } private static synchronized void operation(Transaction tran, Date date) throws Exception { // TODO Auto-generated method stub Sysuser user = SysuserDao.getInstance().getByUserId( tran.getSysuser().getId()); tran.setExecuteDate(date); int operation = TransitionDao.OPERATION_UPDATE; switch (tran.getTransactionType()) { case Transaction.TRANS_TYPE_BUY: if (user.getCash() >= tran.getAmount()) { long shares = 1000 * tran.getAmount() / tran.getFundPriceHistory().getPrice(); if (shares == 0) { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } else { tran.setShares(shares); tran.setAmount((long) (shares / 1000.0 * tran.getFundPriceHistory().getPrice())); user.setCash(user.getCash() - tran.getAmount()); Position p = PositionDao.getInstance() .getByCustomerIdFundId( user.getId(), tran.getFundPriceHistory().getFund() .getId()); if (p == null) { p = new Position(); p.setFund(tran.getFundPriceHistory().getFund()); p.setIduser(user.getId()); p.setShares(shares); operation = TransitionDao.OPERATION_NEW; } else { p.setShares(shares + p.getShares()); } tran.setStatus(Transaction.TRANS_STATUS_FINISH); if (!TransitionDao.getInstance().buyAndSell(p, user, tran, operation)) { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } } } else { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } break; case Transaction.TRANS_TYPE_SELL: Position p = PositionDao.getInstance().getByCustomerIdFundId( user.getId(), tran.getFundPriceHistory().getFund().getId()); if (p.getShares() >= tran.getShares()) { - long money = tran.getShares() / 1000 - * tran.getFundPriceHistory().getPrice(); + long money = (long) (tran.getShares() / 1000.0 + * tran.getFundPriceHistory().getPrice()); user.setCash(user.getCash() + money); tran.setAmount(money); if (p.getShares() == tran.getShares()) { operation = TransitionDao.OPERATION_DELETE; } else { p.setShares(p.getShares() - tran.getShares()); } tran.setStatus(Transaction.TRANS_STATUS_FINISH); if (!TransitionDao.getInstance().buyAndSell(p, user, tran, operation)) { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } } else { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } break; case Transaction.TRANS_TYPE_DEPOSIT: user.setCash(user.getCash() + tran.getAmount()); tran.setStatus(Transaction.TRANS_STATUS_FINISH); if (!TransitionDao.getInstance().withDrawAndDepsit(user, tran)) { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } break; case Transaction.TRANS_TYPE_WITHDRAW: if (user.getCash() >= tran.getAmount()) { user.setCash(user.getCash() - tran.getAmount()); tran.setStatus(Transaction.TRANS_STATUS_FINISH); if (!TransitionDao.getInstance().withDrawAndDepsit(user, tran)) { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } } else { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } break; } } } }
true
true
private static synchronized void operation(Transaction tran, Date date) throws Exception { // TODO Auto-generated method stub Sysuser user = SysuserDao.getInstance().getByUserId( tran.getSysuser().getId()); tran.setExecuteDate(date); int operation = TransitionDao.OPERATION_UPDATE; switch (tran.getTransactionType()) { case Transaction.TRANS_TYPE_BUY: if (user.getCash() >= tran.getAmount()) { long shares = 1000 * tran.getAmount() / tran.getFundPriceHistory().getPrice(); if (shares == 0) { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } else { tran.setShares(shares); tran.setAmount((long) (shares / 1000.0 * tran.getFundPriceHistory().getPrice())); user.setCash(user.getCash() - tran.getAmount()); Position p = PositionDao.getInstance() .getByCustomerIdFundId( user.getId(), tran.getFundPriceHistory().getFund() .getId()); if (p == null) { p = new Position(); p.setFund(tran.getFundPriceHistory().getFund()); p.setIduser(user.getId()); p.setShares(shares); operation = TransitionDao.OPERATION_NEW; } else { p.setShares(shares + p.getShares()); } tran.setStatus(Transaction.TRANS_STATUS_FINISH); if (!TransitionDao.getInstance().buyAndSell(p, user, tran, operation)) { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } } } else { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } break; case Transaction.TRANS_TYPE_SELL: Position p = PositionDao.getInstance().getByCustomerIdFundId( user.getId(), tran.getFundPriceHistory().getFund().getId()); if (p.getShares() >= tran.getShares()) { long money = tran.getShares() / 1000 * tran.getFundPriceHistory().getPrice(); user.setCash(user.getCash() + money); tran.setAmount(money); if (p.getShares() == tran.getShares()) { operation = TransitionDao.OPERATION_DELETE; } else { p.setShares(p.getShares() - tran.getShares()); } tran.setStatus(Transaction.TRANS_STATUS_FINISH); if (!TransitionDao.getInstance().buyAndSell(p, user, tran, operation)) { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } } else { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } break; case Transaction.TRANS_TYPE_DEPOSIT: user.setCash(user.getCash() + tran.getAmount()); tran.setStatus(Transaction.TRANS_STATUS_FINISH); if (!TransitionDao.getInstance().withDrawAndDepsit(user, tran)) { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } break; case Transaction.TRANS_TYPE_WITHDRAW: if (user.getCash() >= tran.getAmount()) { user.setCash(user.getCash() - tran.getAmount()); tran.setStatus(Transaction.TRANS_STATUS_FINISH); if (!TransitionDao.getInstance().withDrawAndDepsit(user, tran)) { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } } else { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } break; } }
private static synchronized void operation(Transaction tran, Date date) throws Exception { // TODO Auto-generated method stub Sysuser user = SysuserDao.getInstance().getByUserId( tran.getSysuser().getId()); tran.setExecuteDate(date); int operation = TransitionDao.OPERATION_UPDATE; switch (tran.getTransactionType()) { case Transaction.TRANS_TYPE_BUY: if (user.getCash() >= tran.getAmount()) { long shares = 1000 * tran.getAmount() / tran.getFundPriceHistory().getPrice(); if (shares == 0) { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } else { tran.setShares(shares); tran.setAmount((long) (shares / 1000.0 * tran.getFundPriceHistory().getPrice())); user.setCash(user.getCash() - tran.getAmount()); Position p = PositionDao.getInstance() .getByCustomerIdFundId( user.getId(), tran.getFundPriceHistory().getFund() .getId()); if (p == null) { p = new Position(); p.setFund(tran.getFundPriceHistory().getFund()); p.setIduser(user.getId()); p.setShares(shares); operation = TransitionDao.OPERATION_NEW; } else { p.setShares(shares + p.getShares()); } tran.setStatus(Transaction.TRANS_STATUS_FINISH); if (!TransitionDao.getInstance().buyAndSell(p, user, tran, operation)) { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } } } else { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } break; case Transaction.TRANS_TYPE_SELL: Position p = PositionDao.getInstance().getByCustomerIdFundId( user.getId(), tran.getFundPriceHistory().getFund().getId()); if (p.getShares() >= tran.getShares()) { long money = (long) (tran.getShares() / 1000.0 * tran.getFundPriceHistory().getPrice()); user.setCash(user.getCash() + money); tran.setAmount(money); if (p.getShares() == tran.getShares()) { operation = TransitionDao.OPERATION_DELETE; } else { p.setShares(p.getShares() - tran.getShares()); } tran.setStatus(Transaction.TRANS_STATUS_FINISH); if (!TransitionDao.getInstance().buyAndSell(p, user, tran, operation)) { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } } else { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } break; case Transaction.TRANS_TYPE_DEPOSIT: user.setCash(user.getCash() + tran.getAmount()); tran.setStatus(Transaction.TRANS_STATUS_FINISH); if (!TransitionDao.getInstance().withDrawAndDepsit(user, tran)) { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } break; case Transaction.TRANS_TYPE_WITHDRAW: if (user.getCash() >= tran.getAmount()) { user.setCash(user.getCash() - tran.getAmount()); tran.setStatus(Transaction.TRANS_STATUS_FINISH); if (!TransitionDao.getInstance().withDrawAndDepsit(user, tran)) { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } } else { tran.setStatus(Transaction.TRANS_STATUS_FAIL); TransactionDao.getInstance().update(tran); } break; } }
diff --git a/src/com/bitsofproof/supernode/core/ByteUtils.java b/src/com/bitsofproof/supernode/core/ByteUtils.java index b9524b08..418f456e 100644 --- a/src/com/bitsofproof/supernode/core/ByteUtils.java +++ b/src/com/bitsofproof/supernode/core/ByteUtils.java @@ -1,73 +1,77 @@ package com.bitsofproof.supernode.core; import java.io.UnsupportedEncodingException; import org.bouncycastle.util.encoders.Hex; public class ByteUtils { public static byte[] reverse (byte[] data) { for ( int i = 0, j = data.length - 1; i < data.length / 2; i++, j-- ) { data[i] ^= data[j]; data[j] ^= data[i]; data[i] ^= data[j]; } return data; } public boolean equals (byte[] a, byte[] b) { if ( a == null && b == null ) { return true; } if ( a == null || b == null ) { return false; } if ( a.length == b.length ) { for ( int i = 0; i < a.length; ++i ) { if ( a[i] != b[i] ) { return false; } } } + else + { + return false; + } return true; } public byte[] dup (byte[] b) { byte[] a = new byte[b.length]; System.arraycopy (b, 0, a, 0, b.length); return a; } public byte[] dup (byte[] b, int offset, int length) { byte[] a = new byte[length - offset]; System.arraycopy (b, offset, a, 0, length); return a; } public static String toHex (byte[] data) { try { return new String (Hex.encode (data), "US-ASCII"); } catch ( UnsupportedEncodingException e ) { } return null; } public static byte[] fromHex (String hex) { return Hex.decode (hex); } }
true
true
public boolean equals (byte[] a, byte[] b) { if ( a == null && b == null ) { return true; } if ( a == null || b == null ) { return false; } if ( a.length == b.length ) { for ( int i = 0; i < a.length; ++i ) { if ( a[i] != b[i] ) { return false; } } } return true; }
public boolean equals (byte[] a, byte[] b) { if ( a == null && b == null ) { return true; } if ( a == null || b == null ) { return false; } if ( a.length == b.length ) { for ( int i = 0; i < a.length; ++i ) { if ( a[i] != b[i] ) { return false; } } } else { return false; } return true; }
diff --git a/src/main/java/nl/surfnet/bod/AppConfigWebApplicationContext.java b/src/main/java/nl/surfnet/bod/AppConfigWebApplicationContext.java index e8896b67e..61e423294 100644 --- a/src/main/java/nl/surfnet/bod/AppConfigWebApplicationContext.java +++ b/src/main/java/nl/surfnet/bod/AppConfigWebApplicationContext.java @@ -1,86 +1,87 @@ /** * Copyright (c) 2012, 2013 SURFnet BV * 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 SURFnet BV nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package nl.surfnet.bod; import static nl.surfnet.bod.BodProperties.getDefaultProperties; import static nl.surfnet.bod.BodProperties.getEnvProperties; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import com.google.common.base.Joiner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.Resource; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; public class AppConfigWebApplicationContext extends AnnotationConfigWebApplicationContext { private Logger logger = LoggerFactory.getLogger(AppConfigWebApplicationContext.class); @Override protected ConfigurableEnvironment createEnvironment() { StandardEnvironment env = new StandardEnvironment(); String nbiMode = getNbiMode(); switch (nbiMode) { case "opendrac": env.setActiveProfiles("opendrac"); + break; case "opendrac-offline": env.setActiveProfiles("opendrac-offline"); break; case "onecontrol": env.setActiveProfiles("onecontrol"); break; default: - throw new AssertionError("Could not set the nbi active profile"); + throw new AssertionError("Could not set the NBI active profile"); } logger.info("Starting with active profiles: {}", Joiner.on(",").join(env.getActiveProfiles())); return env; } private String getNbiMode() { Resource propertiesResource = getEnvOrDefaultProperties(); try (InputStream is = propertiesResource.getInputStream()) { Properties props = new Properties(); props.load(is); return props.getProperty("nbi.mode"); } catch (IOException e) { throw new AssertionError("Could not determine the nbi.mode"); } } private Resource getEnvOrDefaultProperties() { Resource propertiesResource = getEnvProperties(); return propertiesResource.exists() ? propertiesResource : getDefaultProperties(); } }
false
true
protected ConfigurableEnvironment createEnvironment() { StandardEnvironment env = new StandardEnvironment(); String nbiMode = getNbiMode(); switch (nbiMode) { case "opendrac": env.setActiveProfiles("opendrac"); case "opendrac-offline": env.setActiveProfiles("opendrac-offline"); break; case "onecontrol": env.setActiveProfiles("onecontrol"); break; default: throw new AssertionError("Could not set the nbi active profile"); } logger.info("Starting with active profiles: {}", Joiner.on(",").join(env.getActiveProfiles())); return env; }
protected ConfigurableEnvironment createEnvironment() { StandardEnvironment env = new StandardEnvironment(); String nbiMode = getNbiMode(); switch (nbiMode) { case "opendrac": env.setActiveProfiles("opendrac"); break; case "opendrac-offline": env.setActiveProfiles("opendrac-offline"); break; case "onecontrol": env.setActiveProfiles("onecontrol"); break; default: throw new AssertionError("Could not set the NBI active profile"); } logger.info("Starting with active profiles: {}", Joiner.on(",").join(env.getActiveProfiles())); return env; }
diff --git a/hci/src/nonui/ImageController.java b/hci/src/nonui/ImageController.java index 5cccb75..6adb9c1 100644 --- a/hci/src/nonui/ImageController.java +++ b/hci/src/nonui/ImageController.java @@ -1,466 +1,464 @@ package src.nonui; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.swing.JFrame; import javax.swing.JOptionPane; import src.ui.ImagePanelView; import src.utils.Point; import src.utils.Polygon; public class ImageController { // How far a user can click from a point and still select it (in pixels) private static final double EDITING_THRESHOLD_DISTANCE = 5.0; private final AppController appController; private JFrame appFrame; private ImagePanelView imagePanel; // Used when adding/editing points. private Polygon polygonInCreation = new Polygon(); private Polygon polygonInEditing = new Polygon(); private Point currentPoint = null; public ImageController(AppController appController, JFrame appFrame) { this.appController = appController; this.appFrame = appFrame; } /** * Sets the panel that this controller is for. * * @param imagePanel the panel this controller is for */ public void setPanel(ImagePanelView imagePanel) { this.imagePanel = imagePanel; } /** * Returns a list of the points of the completed polygons. */ public List<List<Point>> getCompletedPolygonsPoints() { Map<String, Polygon> completedPolygons = appController.getCompletedPolygons(); List<List<Point>> points = new ArrayList<List<Point>>(completedPolygons.size()); for (Polygon polygon : completedPolygons.values()) { points.add(new ArrayList<Point>(polygon.getPoints())); } return points; } /** * Returns a list of the points of the currently selected polygons. */ public List<List<Point>> getSelectedPolygonsPoints() { List<Polygon> selectedPolygons = getSelectedPolygons(); List<List<Point>> points = new ArrayList<List<Point>>(selectedPolygons.size()); for (Polygon selectedPolygon : selectedPolygons) { points.add(selectedPolygon.getPoints()); } return points; } /** * Returns a list of the points of the polygon that is currently being created. */ public List<Point> getCurrentPolygonPoints() { if (polygonInCreation != null) return polygonInCreation.getPoints(); return null; } /** * Returns a list of the points of the polygon that is currently being edited, * or null if no polygon is being edited. */ public List<Point> getEditedPolygonPoints() { if (appController.getApplicationState() == ApplicationState.EDITING_POLYGON) { return polygonInEditing.getPoints(); } return null; } /** * Called when the image is clicked on. * * @param x the x-coordinate of the mouse click * @param y the y-coordinate of the mouse click * @param doubleClick whether or not the user is double clicking */ public void imageMouseClick(int x, int y, boolean doubleClick) { switch (appController.getApplicationState()) { case DEFAULT: if (doubleClick) { // Double clicking does nothing in the default state. return; } // If an existing point is recognised as being clicked, // select it and change the state to EDITING selectClosestPoint(x, y); break; case ADDING_POLYGON: if (doubleClick) { finishedAddingPolygon(); } else { if (nearFirstPoint(x,y)) { finishedAddingPolygon(); } else { polygonInCreation.addPoint(new Point(x, y)); imagePanel.repaint(); } } break; case EDITING_POLYGON: // If a point is being clicked, select this polygon. if (!selectClosestPoint(x, y)) { addPointToCompletedPolygon(x,y); } else { } imagePanel.repaint(); default: // TODO: Throw/show appropriate error. } } /** * Called when the mouse is pressed over the image (but not released * immediately). * * @param x the x coordinate where the mouse was pressed * @param y the y coordinate where the mouse was pressed */ public void imageMousePress(int x, int y) { switch (appController.getApplicationState()) { case DEFAULT: // If the user clicked on an existing point, select it. selectClosestPoint(x, y); break; case ADDING_POLYGON: // Do nothing. break; case EDITING_POLYGON: // The user is either selecting a point on a polygon, or trying to add // a new point to a polygon. if (!selectClosestPoint(x, y)) { addPointToCompletedPolygon(x,y); imagePanel.repaint(); } break; default: // TODO: Throw/show appropriate error. } } /** * Called when the mouse is released (from a press/drag, not a click) over * the image. */ public void imageMouseReleased() { switch (appController.getApplicationState()) { case DEFAULT: currentPoint = null; polygonInCreation = new Polygon(); imagePanel.repaint(); break; case ADDING_POLYGON: // Do nothing. break; case EDITING_POLYGON: currentPoint = null; polygonInCreation = new Polygon(); break; default: // TODO: Throw/show appropriate error. } } /** * Called when the user drags their mouse over the image. * * @param x the x coordinate they have dragged to * @param y the y coordinate they have dragged to */ public void imageMouseDrag(int x, int y) { switch (appController.getApplicationState()) { case DEFAULT: // Do nothing break; case ADDING_POLYGON: // Do nothing. break; case EDITING_POLYGON: if (currentPoint != null && polygonInEditing != null) { // Move the point. Point newPoint = new Point(x, y); if (polygonInEditing.replacePoint(currentPoint, newPoint)) { currentPoint = newPoint; } imagePanel.repaint(); } break; default: // TODO: Throw/show appropriate error. } } /** * Called when the user is finished adding the current polygon, either by * clicking on the starting point, double-clicking, or clicking the "Done" * button on the toolbox. */ public void finishedAddingPolygon() { if (appController.getApplicationState() != ApplicationState.ADDING_POLYGON) { return; } if (polygonInCreation.getPoints().size() < 3) { JOptionPane.showMessageDialog(appFrame, "A label must have 3 or more vertices.", "Error", JOptionPane.ERROR_MESSAGE); return; } String name = ""; boolean hasName = false; while (!hasName) { String message = "Label Name"; name = JOptionPane.showInputDialog(appFrame, message, name); // TODO: Should this totally cancel, or only cancel the "done"? // Occurs if the user hits the cancel option. if (name == null) { - polygonInCreation = new Polygon(); - imagePanel.repaint(); return; } name = name.trim(); if (appController.getCompletedPolygons().containsKey(name)) { JOptionPane.showMessageDialog(appFrame, "That name is already in use.", "Error", JOptionPane.ERROR_MESSAGE); } else if (name.isEmpty()) { JOptionPane.showMessageDialog(appFrame, "Blank names are not allowed.", "Error", JOptionPane.ERROR_MESSAGE); - } else if (!name.matches("[a-zA-Z0-9]+")) { + } else if (!name.matches("[a-zA-Z0-9 ]+")) { JOptionPane.showMessageDialog(appFrame, "Only alphanumeric characters are allowed in label names.", "Error", JOptionPane.ERROR_MESSAGE); } else { hasName = true; } } polygonInCreation.setName(name); appController.getCompletedPolygons().put(name, polygonInCreation); polygonInCreation = new Polygon(); appController.finishedAddingPolygon(name); imagePanel.repaint(); if (appController.areTipsOn()) { appController.showNewLabelTip(); } } /** * Undoes the last added vertex on the current polygon. */ public void undo() { polygonInCreation.removeLastPoint(); imagePanel.repaint(); } /** * Redoes the last undone vertex on the current polygon. */ public void redo() { polygonInCreation.redoPoint(); imagePanel.repaint(); } /** * Gets the polygon that is currently being edited. */ public Polygon getEditedPolygon() { return polygonInEditing; } /** * Cancels the adding of the current polygon. */ public void cancel() { polygonInCreation = new Polygon(); imagePanel.repaint(); } /** * Sets the image from a file. * * @param bufferedImage the file to open the image from */ public void setImage(BufferedImage image) { imagePanel.setImage(image); } /** * Sets the default text for the image panel. * * @param text the text to display */ public void setDefaultText(String text) { imagePanel.setDefaultText(text); } /** * Gets a list of the currently selected polygons. */ private List<Polygon> getSelectedPolygons() { Map<String, Polygon> completedPolygons = appController.getCompletedPolygons(); List<String> selectedNames = appController.getSelectedNames(); List<Polygon> selectedPolygons = new ArrayList<Polygon>(selectedNames.size()); for (String name : selectedNames) { selectedPolygons.add(completedPolygons.get(name)); } return selectedPolygons; } /** * Selects the closest point to a given target point. * * @param x the x coordinate of the target * @param y the y coordinate of the target */ private boolean selectClosestPoint(int x, int y) { Point targetPoint = new Point(x, y); Point closestPoint = null; Polygon closestPolygon = null; double smallestDistance = -1; for (Polygon polygon : appController.getCompletedPolygons().values()) { for (Point point : polygon.getPoints()) { double distanceToTarget = targetPoint.distanceFrom(point); if (distanceToTarget < smallestDistance || smallestDistance < 0) { if (isSelected(polygon)) { smallestDistance = distanceToTarget; closestPoint = point; closestPolygon = polygon; } } } } if (smallestDistance >= 0 && smallestDistance < EDITING_THRESHOLD_DISTANCE) { appController.setApplicationState(ApplicationState.EDITING_POLYGON); currentPoint = closestPoint; polygonInEditing = closestPolygon; return true; } else { appController.setApplicationState(ApplicationState.DEFAULT); } return false; } /** * Adds a point to the nearest completed polygon. * * @param x the x coordinate of the point * @param y the y coordinate of the point */ private void addPointToCompletedPolygon(int x, int y) { Point targetPoint = new Point(x, y); polygonInCreation = null; for (Polygon polygon : getSelectedPolygons()) { List<Point> polygonPoints = polygon.getPoints(); for (int i = 0; i < polygonPoints.size(); i++) { Point point1 = polygonPoints.get(i); Point point2 = polygonPoints.get((i + 1) % polygonPoints.size()); // y = mx + c double m = (double) (point1.getY() - point2.getY()) / (double) (point1.getX() - point2.getX()); double c = point1.getY() - (double)(m * point1.getX()); // Plug the new point into the line equation to see what the coordinates should be. double expectedY = (m * (double) x) + c; double expectedX = ((double) y - c) / m; if (Math.abs(expectedY - (double) y) < EDITING_THRESHOLD_DISTANCE || Math.abs(expectedX - (double) x) < EDITING_THRESHOLD_DISTANCE) { if (withinBoundingBox(targetPoint, point1, point2)) { polygon.addPointAt(targetPoint, ((i+1) % polygonPoints.size())); appController.setApplicationState(ApplicationState.EDITING_POLYGON); polygonInEditing = polygon; return; } } } } } /** * Checks if a target point is within the bounding box created by two other points. * * @param targetPoint the target point to check * @param point1 one of the points that define the bounding box * @param point2 the other point that defines the bounding box */ private boolean withinBoundingBox(Point targetPoint, Point point1, Point point2) { int left = Math.min(point1.getX(), point2.getX()); int right = Math.max(point1.getX(), point2.getX()); int top = Math.min(point1.getY(), point2.getY()); int bottom = Math.max(point1.getY(), point2.getY()); int x = targetPoint.getX(); int y = targetPoint.getY(); return x >= left && x <= right && y >= top && y <= bottom; } /** * Checks if a set of coordinates is near the starting point of the in-progress * polygon. * * @param x the x coordinate to check * @param y the y coordinate to check */ private boolean nearFirstPoint(int x, int y) { if (polygonInCreation.getPoints().isEmpty()) { return false; } Point targetPoint = new Point(x, y); double distanceToTarget = targetPoint.distanceFrom(polygonInCreation.getPoints().get(0)); return distanceToTarget < EDITING_THRESHOLD_DISTANCE; } /** * Returns true if a given polygon is currently selected. * * @param polygon the polygon that may be selected */ private boolean isSelected(Polygon polygon) { return getSelectedPolygons().contains(polygon); } }
false
true
public void finishedAddingPolygon() { if (appController.getApplicationState() != ApplicationState.ADDING_POLYGON) { return; } if (polygonInCreation.getPoints().size() < 3) { JOptionPane.showMessageDialog(appFrame, "A label must have 3 or more vertices.", "Error", JOptionPane.ERROR_MESSAGE); return; } String name = ""; boolean hasName = false; while (!hasName) { String message = "Label Name"; name = JOptionPane.showInputDialog(appFrame, message, name); // TODO: Should this totally cancel, or only cancel the "done"? // Occurs if the user hits the cancel option. if (name == null) { polygonInCreation = new Polygon(); imagePanel.repaint(); return; } name = name.trim(); if (appController.getCompletedPolygons().containsKey(name)) { JOptionPane.showMessageDialog(appFrame, "That name is already in use.", "Error", JOptionPane.ERROR_MESSAGE); } else if (name.isEmpty()) { JOptionPane.showMessageDialog(appFrame, "Blank names are not allowed.", "Error", JOptionPane.ERROR_MESSAGE); } else if (!name.matches("[a-zA-Z0-9]+")) { JOptionPane.showMessageDialog(appFrame, "Only alphanumeric characters are allowed in label names.", "Error", JOptionPane.ERROR_MESSAGE); } else { hasName = true; } } polygonInCreation.setName(name); appController.getCompletedPolygons().put(name, polygonInCreation); polygonInCreation = new Polygon(); appController.finishedAddingPolygon(name); imagePanel.repaint(); if (appController.areTipsOn()) { appController.showNewLabelTip(); } }
public void finishedAddingPolygon() { if (appController.getApplicationState() != ApplicationState.ADDING_POLYGON) { return; } if (polygonInCreation.getPoints().size() < 3) { JOptionPane.showMessageDialog(appFrame, "A label must have 3 or more vertices.", "Error", JOptionPane.ERROR_MESSAGE); return; } String name = ""; boolean hasName = false; while (!hasName) { String message = "Label Name"; name = JOptionPane.showInputDialog(appFrame, message, name); // TODO: Should this totally cancel, or only cancel the "done"? // Occurs if the user hits the cancel option. if (name == null) { return; } name = name.trim(); if (appController.getCompletedPolygons().containsKey(name)) { JOptionPane.showMessageDialog(appFrame, "That name is already in use.", "Error", JOptionPane.ERROR_MESSAGE); } else if (name.isEmpty()) { JOptionPane.showMessageDialog(appFrame, "Blank names are not allowed.", "Error", JOptionPane.ERROR_MESSAGE); } else if (!name.matches("[a-zA-Z0-9 ]+")) { JOptionPane.showMessageDialog(appFrame, "Only alphanumeric characters are allowed in label names.", "Error", JOptionPane.ERROR_MESSAGE); } else { hasName = true; } } polygonInCreation.setName(name); appController.getCompletedPolygons().put(name, polygonInCreation); polygonInCreation = new Polygon(); appController.finishedAddingPolygon(name); imagePanel.repaint(); if (appController.areTipsOn()) { appController.showNewLabelTip(); } }
diff --git a/src/edu/ucla/cens/awserver/dao/SingleUserMostRecentActivityQueryDao.java b/src/edu/ucla/cens/awserver/dao/SingleUserMostRecentActivityQueryDao.java index 290ace91..a6867bc0 100644 --- a/src/edu/ucla/cens/awserver/dao/SingleUserMostRecentActivityQueryDao.java +++ b/src/edu/ucla/cens/awserver/dao/SingleUserMostRecentActivityQueryDao.java @@ -1,116 +1,116 @@ package edu.ucla.cens.awserver.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.apache.log4j.Logger; import org.springframework.jdbc.core.RowMapper; import edu.ucla.cens.awserver.domain.MobilityActivityQueryResult; import edu.ucla.cens.awserver.domain.MostRecentActivityQueryResult; import edu.ucla.cens.awserver.domain.PromptActivityQueryResult; import edu.ucla.cens.awserver.domain.User; import edu.ucla.cens.awserver.request.AwRequest; /** * DAO for looking up the most recent prompt response and mobility uploads for a particular user. * * @author selsky */ public class SingleUserMostRecentActivityQueryDao extends AbstractDao { private static Logger _logger = Logger.getLogger(MultiUserMostRecentActivityQueryDao.class); private String _promptResponseSql = "select max(prompt_response.time_stamp), prompt_response.phone_timezone" + " from prompt_response, prompt, campaign_prompt_group" + " where prompt_response.prompt_id = prompt.id" + " and prompt.campaign_prompt_group_id = campaign_prompt_group.id" + " and campaign_id = ?" + " and prompt_response.user_id = ?" + " group by prompt_response.user_id" + " order by prompt_response.user_id"; private String _mobilityUploadSql = "select max(time_stamp), phone_timezone" + " from mobility_mode_only_entry" + " where user_id = ?" + " group by user_id" + " order by user_id"; public SingleUserMostRecentActivityQueryDao(DataSource dataSource) { super(dataSource); } @Override public void execute(AwRequest awRequest) { List<MostRecentActivityQueryResult> results = new ArrayList<MostRecentActivityQueryResult>(); User user = awRequest.getUser(); results.add(executeSqlForSingleUser(Integer.parseInt(user.getCurrentCampaignId()), user.getId(), user.getUserName())); awRequest.setResultList(results); } protected MostRecentActivityQueryResult executeSqlForSingleUser(int campaignId, int userId, final String userName) { String currentSql = null; try { MostRecentActivityQueryResult result = new MostRecentActivityQueryResult(); currentSql = _promptResponseSql; List<?> results = getJdbcTemplate().query(_promptResponseSql, new Object[] {campaignId, userId}, new RowMapper() { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { PromptActivityQueryResult result = new PromptActivityQueryResult(); result.setUserName(userName); - result.setPromptTimestamp(rs.getTimestamp(2)); - result.setPromptTimezone(rs.getString(3)); + result.setPromptTimestamp(rs.getTimestamp(1)); + result.setPromptTimezone(rs.getString(2)); return result; } } ); if(results.size() != 0) { result.setPromptActivityQueryResult((PromptActivityQueryResult) results.get(0)); } currentSql = _mobilityUploadSql; results = getJdbcTemplate().query(_mobilityUploadSql, new Object[] {userId}, new RowMapper() { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { MobilityActivityQueryResult result = new MobilityActivityQueryResult(); result.setUserName(userName); - result.setMobilityTimestamp(rs.getTimestamp(2)); - result.setMobilityTimezone(rs.getString(3)); + result.setMobilityTimestamp(rs.getTimestamp(1)); + result.setMobilityTimezone(rs.getString(2)); return result; } } ); if(results.size() != 0) { result.setMobilityActivityQueryResult((MobilityActivityQueryResult) results.get(0)); } if(null == result.getMobilityActivityQueryResult() && null == result.getPromptActivityQueryResult()) { result.setUserName(userName); } return result; } catch (org.springframework.dao.DataAccessException dae) { _logger.error(dae.getMessage() + " SQL: '" + currentSql + "' Params: " + campaignId + ", " + userId); throw new DataAccessException(dae.getMessage()); } } }
false
true
protected MostRecentActivityQueryResult executeSqlForSingleUser(int campaignId, int userId, final String userName) { String currentSql = null; try { MostRecentActivityQueryResult result = new MostRecentActivityQueryResult(); currentSql = _promptResponseSql; List<?> results = getJdbcTemplate().query(_promptResponseSql, new Object[] {campaignId, userId}, new RowMapper() { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { PromptActivityQueryResult result = new PromptActivityQueryResult(); result.setUserName(userName); result.setPromptTimestamp(rs.getTimestamp(2)); result.setPromptTimezone(rs.getString(3)); return result; } } ); if(results.size() != 0) { result.setPromptActivityQueryResult((PromptActivityQueryResult) results.get(0)); } currentSql = _mobilityUploadSql; results = getJdbcTemplate().query(_mobilityUploadSql, new Object[] {userId}, new RowMapper() { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { MobilityActivityQueryResult result = new MobilityActivityQueryResult(); result.setUserName(userName); result.setMobilityTimestamp(rs.getTimestamp(2)); result.setMobilityTimezone(rs.getString(3)); return result; } } ); if(results.size() != 0) { result.setMobilityActivityQueryResult((MobilityActivityQueryResult) results.get(0)); } if(null == result.getMobilityActivityQueryResult() && null == result.getPromptActivityQueryResult()) { result.setUserName(userName); } return result; } catch (org.springframework.dao.DataAccessException dae) { _logger.error(dae.getMessage() + " SQL: '" + currentSql + "' Params: " + campaignId + ", " + userId); throw new DataAccessException(dae.getMessage()); } }
protected MostRecentActivityQueryResult executeSqlForSingleUser(int campaignId, int userId, final String userName) { String currentSql = null; try { MostRecentActivityQueryResult result = new MostRecentActivityQueryResult(); currentSql = _promptResponseSql; List<?> results = getJdbcTemplate().query(_promptResponseSql, new Object[] {campaignId, userId}, new RowMapper() { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { PromptActivityQueryResult result = new PromptActivityQueryResult(); result.setUserName(userName); result.setPromptTimestamp(rs.getTimestamp(1)); result.setPromptTimezone(rs.getString(2)); return result; } } ); if(results.size() != 0) { result.setPromptActivityQueryResult((PromptActivityQueryResult) results.get(0)); } currentSql = _mobilityUploadSql; results = getJdbcTemplate().query(_mobilityUploadSql, new Object[] {userId}, new RowMapper() { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { MobilityActivityQueryResult result = new MobilityActivityQueryResult(); result.setUserName(userName); result.setMobilityTimestamp(rs.getTimestamp(1)); result.setMobilityTimezone(rs.getString(2)); return result; } } ); if(results.size() != 0) { result.setMobilityActivityQueryResult((MobilityActivityQueryResult) results.get(0)); } if(null == result.getMobilityActivityQueryResult() && null == result.getPromptActivityQueryResult()) { result.setUserName(userName); } return result; } catch (org.springframework.dao.DataAccessException dae) { _logger.error(dae.getMessage() + " SQL: '" + currentSql + "' Params: " + campaignId + ", " + userId); throw new DataAccessException(dae.getMessage()); } }
diff --git a/htroot/Wiki.java b/htroot/Wiki.java index 8b7cd9d51..c92f06f24 100644 --- a/htroot/Wiki.java +++ b/htroot/Wiki.java @@ -1,182 +1,182 @@ // Wiki.java // ----------------------- // part of the AnomicHTTPD caching proxy // (C) by Michael Peter Christen; [email protected] // first published on http://www.anomic.de // Frankfurt, Germany, 2004 // last major change: 01.07.2003 // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Using this software in any meaning (reading, learning, copying, compiling, // running) means that you agree that the Author(s) is (are) not responsible // for cost, loss of data or any harm that may be caused directly or indirectly // by usage of this softare or this documentation. The usage of this software // is on your own risk. The installation and usage (starting/running) of this // software may allow other people or application to access your computer and // any attached devices and is highly dependent on the configuration of the // software which must be done by the user of the software; the author(s) is // (are) also not responsible for proper configuration and usage of the // software, even if provoked by documentation provided together with // the software. // // Any changes to this file according to the GPL as documented in the file // gpl.txt aside this file in the shipment you received can be done to the // lines that follows this copyright notice here, but changes must not be // done inside the copyright notive above. A re-distribution must contain // the intact and unchanged copyright notice. // Contributions and changes to the program code must be marked as such. // Contains contributions from Alexander Schier [AS] // and Marc Nause [MN] // You must compile this file with // javac -classpath .:../classes Wiki.java // if the shell's current path is HTROOT import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.HashMap; import de.anomic.data.wikiBoard; import de.anomic.data.wikiCode; import de.anomic.http.httpHeader; import de.anomic.plasma.plasmaSwitchboard; import de.anomic.server.serverObjects; import de.anomic.server.serverSwitch; import de.anomic.yacy.yacyNewsRecord; import de.anomic.yacy.yacyCore; public class Wiki { //private static String ListLevel = ""; //private static String numListLevel = ""; private static SimpleDateFormat SimpleFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); public static String dateString(Date date) { return SimpleFormatter.format(date); } public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) throws IOException { plasmaSwitchboard switchboard = (plasmaSwitchboard) env; serverObjects prop = new serverObjects(); if (post == null) { post = new serverObjects(); post.put("page", "start"); } String pagename = post.get("page", "start"); String ip = post.get("CLIENTIP", "127.0.0.1"); String author = post.get("author", "anonymous"); if (author.equals("anonymous")) { author = switchboard.wikiDB.guessAuthor(ip); if (author == null) { if (de.anomic.yacy.yacyCore.seedDB.mySeed == null) author = "anonymous"; else author = de.anomic.yacy.yacyCore.seedDB.mySeed.get("Name", "anonymous"); } } if (post.containsKey("submit")) { // store a new page byte[] content; try { content = post.get("content", "").getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { content = post.get("content", "").getBytes(); } switchboard.wikiDB.write(switchboard.wikiDB.newEntry(pagename, author, ip, post.get("reason", "edit"), content)); // create a news message HashMap map = new HashMap(); map.put("page", pagename); map.put("author", author); map.put("ip", ip); try { yacyCore.newsPool.publishMyNews(new yacyNewsRecord("wiki_upd", map)); } catch (IOException e) {} } wikiBoard.entry page = switchboard.wikiDB.read(pagename); if (post.containsKey("edit")) { // edit the page try { prop.put("mode", 1); //edit prop.put("mode_author", author); - prop.put("mode_page-code", new String(page.page(), "UTF-8")); + prop.put("mode_page-code", new String(page.page(), "UTF-8").replaceAll("</textarea>","<&#047;textarea>")); prop.put("mode_pagename", pagename); } catch (UnsupportedEncodingException e) {} } //contributed by [MN] else if (post.containsKey("preview")) { // preview the page wikiCode wikiTransformer=new wikiCode(switchboard); prop.put("mode", 2);//preview prop.put("mode_pagename", pagename); prop.put("mode_author", author); prop.put("mode_date", dateString(new Date())); prop.put("mode_page", wikiTransformer.transform(post.get("content", ""))); - prop.put("mode_page-code", post.get("content", "")); + prop.put("mode_page-code", post.get("content", "").replaceAll("</textarea>","<&#047;textarea>")); } //end contrib of [MN] else if (post.containsKey("index")) { // view an index prop.put("mode", 3); //Index String subject; try { Iterator i = switchboard.wikiDB.keys(true); wikiBoard.entry entry; int count=0; while (i.hasNext()) { subject = (String) i.next(); entry = switchboard.wikiDB.read(subject); prop.put("mode_pages_"+count+"_name",wikiBoard.webalize(subject)); prop.put("mode_pages_"+count+"_subject", subject); prop.put("mode_pages_"+count+"_date", dateString(entry.date())); prop.put("mode_pages_"+count+"_author", entry.author()); count++; } prop.put("mode_pages", count); } catch (IOException e) { prop.put("mode_error", 1); //IO Error reading Wiki prop.put("mode_error_message", e.getMessage()); } prop.put("mode_pagename", pagename); } else { wikiCode wikiTransformer=new wikiCode(switchboard); // show page prop.put("mode", 0); //viewing prop.put("mode_pagename", pagename); prop.put("mode_author", page.author()); prop.put("mode_date", dateString(page.date())); prop.put("mode_page", wikiTransformer.transform(page.page())); prop.put("controls", 0); prop.put("controls_pagename", pagename); } // return rewrite properties return prop; } }
false
true
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) throws IOException { plasmaSwitchboard switchboard = (plasmaSwitchboard) env; serverObjects prop = new serverObjects(); if (post == null) { post = new serverObjects(); post.put("page", "start"); } String pagename = post.get("page", "start"); String ip = post.get("CLIENTIP", "127.0.0.1"); String author = post.get("author", "anonymous"); if (author.equals("anonymous")) { author = switchboard.wikiDB.guessAuthor(ip); if (author == null) { if (de.anomic.yacy.yacyCore.seedDB.mySeed == null) author = "anonymous"; else author = de.anomic.yacy.yacyCore.seedDB.mySeed.get("Name", "anonymous"); } } if (post.containsKey("submit")) { // store a new page byte[] content; try { content = post.get("content", "").getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { content = post.get("content", "").getBytes(); } switchboard.wikiDB.write(switchboard.wikiDB.newEntry(pagename, author, ip, post.get("reason", "edit"), content)); // create a news message HashMap map = new HashMap(); map.put("page", pagename); map.put("author", author); map.put("ip", ip); try { yacyCore.newsPool.publishMyNews(new yacyNewsRecord("wiki_upd", map)); } catch (IOException e) {} } wikiBoard.entry page = switchboard.wikiDB.read(pagename); if (post.containsKey("edit")) { // edit the page try { prop.put("mode", 1); //edit prop.put("mode_author", author); prop.put("mode_page-code", new String(page.page(), "UTF-8")); prop.put("mode_pagename", pagename); } catch (UnsupportedEncodingException e) {} } //contributed by [MN] else if (post.containsKey("preview")) { // preview the page wikiCode wikiTransformer=new wikiCode(switchboard); prop.put("mode", 2);//preview prop.put("mode_pagename", pagename); prop.put("mode_author", author); prop.put("mode_date", dateString(new Date())); prop.put("mode_page", wikiTransformer.transform(post.get("content", ""))); prop.put("mode_page-code", post.get("content", "")); } //end contrib of [MN] else if (post.containsKey("index")) { // view an index prop.put("mode", 3); //Index String subject; try { Iterator i = switchboard.wikiDB.keys(true); wikiBoard.entry entry; int count=0; while (i.hasNext()) { subject = (String) i.next(); entry = switchboard.wikiDB.read(subject); prop.put("mode_pages_"+count+"_name",wikiBoard.webalize(subject)); prop.put("mode_pages_"+count+"_subject", subject); prop.put("mode_pages_"+count+"_date", dateString(entry.date())); prop.put("mode_pages_"+count+"_author", entry.author()); count++; } prop.put("mode_pages", count); } catch (IOException e) { prop.put("mode_error", 1); //IO Error reading Wiki prop.put("mode_error_message", e.getMessage()); } prop.put("mode_pagename", pagename); } else { wikiCode wikiTransformer=new wikiCode(switchboard); // show page prop.put("mode", 0); //viewing prop.put("mode_pagename", pagename); prop.put("mode_author", page.author()); prop.put("mode_date", dateString(page.date())); prop.put("mode_page", wikiTransformer.transform(page.page())); prop.put("controls", 0); prop.put("controls_pagename", pagename); } // return rewrite properties return prop; }
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) throws IOException { plasmaSwitchboard switchboard = (plasmaSwitchboard) env; serverObjects prop = new serverObjects(); if (post == null) { post = new serverObjects(); post.put("page", "start"); } String pagename = post.get("page", "start"); String ip = post.get("CLIENTIP", "127.0.0.1"); String author = post.get("author", "anonymous"); if (author.equals("anonymous")) { author = switchboard.wikiDB.guessAuthor(ip); if (author == null) { if (de.anomic.yacy.yacyCore.seedDB.mySeed == null) author = "anonymous"; else author = de.anomic.yacy.yacyCore.seedDB.mySeed.get("Name", "anonymous"); } } if (post.containsKey("submit")) { // store a new page byte[] content; try { content = post.get("content", "").getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { content = post.get("content", "").getBytes(); } switchboard.wikiDB.write(switchboard.wikiDB.newEntry(pagename, author, ip, post.get("reason", "edit"), content)); // create a news message HashMap map = new HashMap(); map.put("page", pagename); map.put("author", author); map.put("ip", ip); try { yacyCore.newsPool.publishMyNews(new yacyNewsRecord("wiki_upd", map)); } catch (IOException e) {} } wikiBoard.entry page = switchboard.wikiDB.read(pagename); if (post.containsKey("edit")) { // edit the page try { prop.put("mode", 1); //edit prop.put("mode_author", author); prop.put("mode_page-code", new String(page.page(), "UTF-8").replaceAll("</textarea>","<&#047;textarea>")); prop.put("mode_pagename", pagename); } catch (UnsupportedEncodingException e) {} } //contributed by [MN] else if (post.containsKey("preview")) { // preview the page wikiCode wikiTransformer=new wikiCode(switchboard); prop.put("mode", 2);//preview prop.put("mode_pagename", pagename); prop.put("mode_author", author); prop.put("mode_date", dateString(new Date())); prop.put("mode_page", wikiTransformer.transform(post.get("content", ""))); prop.put("mode_page-code", post.get("content", "").replaceAll("</textarea>","<&#047;textarea>")); } //end contrib of [MN] else if (post.containsKey("index")) { // view an index prop.put("mode", 3); //Index String subject; try { Iterator i = switchboard.wikiDB.keys(true); wikiBoard.entry entry; int count=0; while (i.hasNext()) { subject = (String) i.next(); entry = switchboard.wikiDB.read(subject); prop.put("mode_pages_"+count+"_name",wikiBoard.webalize(subject)); prop.put("mode_pages_"+count+"_subject", subject); prop.put("mode_pages_"+count+"_date", dateString(entry.date())); prop.put("mode_pages_"+count+"_author", entry.author()); count++; } prop.put("mode_pages", count); } catch (IOException e) { prop.put("mode_error", 1); //IO Error reading Wiki prop.put("mode_error_message", e.getMessage()); } prop.put("mode_pagename", pagename); } else { wikiCode wikiTransformer=new wikiCode(switchboard); // show page prop.put("mode", 0); //viewing prop.put("mode_pagename", pagename); prop.put("mode_author", page.author()); prop.put("mode_date", dateString(page.date())); prop.put("mode_page", wikiTransformer.transform(page.page())); prop.put("controls", 0); prop.put("controls_pagename", pagename); } // return rewrite properties return prop; }
diff --git a/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/Settings.java b/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/Settings.java index 80813d7..d2bdfa0 100755 --- a/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/Settings.java +++ b/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/Settings.java @@ -1,155 +1,155 @@ /* * Copyright 2000-2009 JetBrains s.r.o. * * 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 jetbrains.buildServer.buildTriggers.vcs.git; import com.intellij.openapi.util.text.StringUtil; import jetbrains.buildServer.vcs.VcsException; import jetbrains.buildServer.vcs.VcsRoot; import org.spearce.jgit.transport.URIish; import java.io.File; import java.net.URISyntaxException; /** * Git Vcs Settings */ public class Settings { /** * The url for the repository */ private String repositoryURL; /** * The public URL */ private String publicURL; /** * The current branch */ private String branch; /** * The repository path */ private File repositoryPath; /** * The style for user name */ private UserNameStyle usernameStyle; /** * The constructor from the root object * * @param root the root * @throws VcsException in case of incorrect configuration */ public Settings(VcsRoot root) throws VcsException { final String p = root.getProperty(Constants.PATH); repositoryPath = p == null ? null : new File(p); branch = root.getProperty(Constants.BRANCH_NAME); String username = root.getProperty(Constants.USERNAME); String password = root.getProperty(Constants.PASSWORD); final String remote = root.getProperty(Constants.URL); URIish uri; try { uri = new URIish(remote); } catch (URISyntaxException e) { throw new VcsException("Invalid URI: " + remote); } if (!StringUtil.isEmptyOrSpaces(username)) { - uri.setUser(username); + uri = uri.setUser(username); } if (!StringUtil.isEmpty(password)) { - uri.setUser(password); + uri = uri.setPass(password); } publicURL = uri.toString(); repositoryURL = uri.toPrivateString(); final String style = root.getProperty(Constants.USERNAME_STYLE); usernameStyle = style == null ? UserNameStyle.USERID : Enum.valueOf(UserNameStyle.class, style); } /** * @return username sytle */ public UserNameStyle getUsernameStyle() { return usernameStyle; } /** * @return the URL with pasword removed */ public String getPublicURL() { return publicURL; } /** * @return the local repository path */ public File getRepositoryPath() { return repositoryPath; } /** * Set repository path * * @param file the path to set */ public void setRepositoryPath(File file) { repositoryPath = file; } /** * @return the URL for the repository */ public String getRepositoryURL() { return repositoryURL; } /** * @return the branch name */ public String getBranch() { return branch == null || branch.length() == 0 ? "master" : branch; } /** * @return debug information that allows identify repository operation context */ public String debugInfo() { return " (" + getRepositoryPath() + ", " + getPublicURL() + "#" + getBranch() + ")"; } /** * The stype for user names */ enum UserNameStyle { /** * Name (John Smith) */ NAME, /** * User id based on email (jsmith) */ USERID, /** * Email ([email protected]) */ EMAIL, /** * Name and Email (John Smith &[email protected]&gt) */ FULL } }
false
true
public Settings(VcsRoot root) throws VcsException { final String p = root.getProperty(Constants.PATH); repositoryPath = p == null ? null : new File(p); branch = root.getProperty(Constants.BRANCH_NAME); String username = root.getProperty(Constants.USERNAME); String password = root.getProperty(Constants.PASSWORD); final String remote = root.getProperty(Constants.URL); URIish uri; try { uri = new URIish(remote); } catch (URISyntaxException e) { throw new VcsException("Invalid URI: " + remote); } if (!StringUtil.isEmptyOrSpaces(username)) { uri.setUser(username); } if (!StringUtil.isEmpty(password)) { uri.setUser(password); } publicURL = uri.toString(); repositoryURL = uri.toPrivateString(); final String style = root.getProperty(Constants.USERNAME_STYLE); usernameStyle = style == null ? UserNameStyle.USERID : Enum.valueOf(UserNameStyle.class, style); }
public Settings(VcsRoot root) throws VcsException { final String p = root.getProperty(Constants.PATH); repositoryPath = p == null ? null : new File(p); branch = root.getProperty(Constants.BRANCH_NAME); String username = root.getProperty(Constants.USERNAME); String password = root.getProperty(Constants.PASSWORD); final String remote = root.getProperty(Constants.URL); URIish uri; try { uri = new URIish(remote); } catch (URISyntaxException e) { throw new VcsException("Invalid URI: " + remote); } if (!StringUtil.isEmptyOrSpaces(username)) { uri = uri.setUser(username); } if (!StringUtil.isEmpty(password)) { uri = uri.setPass(password); } publicURL = uri.toString(); repositoryURL = uri.toPrivateString(); final String style = root.getProperty(Constants.USERNAME_STYLE); usernameStyle = style == null ? UserNameStyle.USERID : Enum.valueOf(UserNameStyle.class, style); }
diff --git a/org.cloudsmith.geppetto.junitresult/src/org/cloudsmith/geppetto/junitresult/util/JunitresultLoader.java b/org.cloudsmith.geppetto.junitresult/src/org/cloudsmith/geppetto/junitresult/util/JunitresultLoader.java index 73fc5159..174d8b51 100644 --- a/org.cloudsmith.geppetto.junitresult/src/org/cloudsmith/geppetto/junitresult/util/JunitresultLoader.java +++ b/org.cloudsmith.geppetto.junitresult/src/org/cloudsmith/geppetto/junitresult/util/JunitresultLoader.java @@ -1,306 +1,294 @@ package org.cloudsmith.geppetto.junitresult.util; import java.io.File; import java.io.IOException; import java.util.Calendar; import java.util.Date; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.cloudsmith.geppetto.junitresult.AbstractAggregatedTest; import org.cloudsmith.geppetto.junitresult.Error; import org.cloudsmith.geppetto.junitresult.Failure; import org.cloudsmith.geppetto.junitresult.JunitResult; import org.cloudsmith.geppetto.junitresult.JunitresultFactory; import org.cloudsmith.geppetto.junitresult.NegativeResult; import org.cloudsmith.geppetto.junitresult.Property; import org.cloudsmith.geppetto.junitresult.Testcase; import org.cloudsmith.geppetto.junitresult.Testrun; import org.cloudsmith.geppetto.junitresult.Testsuite; import org.cloudsmith.geppetto.junitresult.Testsuites; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import org.xml.sax.SAXNotSupportedException; public class JunitresultLoader { /** * Loader of so called JUnit result format, as first defined by the ANT junit task. Three main formats * exists, but these are not formalized so parsing is based on empirical studies. A result document * may have: * <ul> * <li>single <code>&lt;testsuite&gt;</code> element with optional nested elements of the same type</li> * <li>a <code>&lt;testrun&gt;</code> element with multiple child <code>&lt;testsuite&gt;</code> element, which may also be nested.</li> * <li>a <code>&lt;testsuites&gt;</code> element with multiple child <code>&lt;testsuite&gt;</code> element, which may be nested. When this format * is used, the testsuite elements have an extended attribute set ('id' and 'package') which are not present in the other formats.</li> * </ul> * * @param f * @return a {@link JunitResult} which is one of {@link Testsuite}, {@link Testrun} or {@link Testsuites} * @throws IOException * @throws RuntimeException * with nested detail exception if there is an internal error. */ public static JunitResult loadFromXML(File f) throws IOException { try { return new JunitresultLoader().loadFromXMLFile(f); } catch(ParserConfigurationException e) { throw new RuntimeException(e); } catch(SAXException e) { throw new RuntimeException(e); } } private int getIntAttributeWith0Default(Element element, String attribute) { try { return Integer.valueOf(element.getAttribute(attribute)); } catch(NumberFormatException e) { // ignore, will return 0 } return 0; } /** * Returns the node value of a child node of the given element tagged with the given tag. * If no such child element exists <code>null</code> is returned. * * @param element * @param tag * @return */ private String getTagValue(Element element, String tag) { NodeList children = element.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { Node n = children.item(i); if(n.getNodeType() == Node.ELEMENT_NODE && tag.equalsIgnoreCase(n.getNodeName())) { NodeList content = n.getChildNodes(); Node node = content.item(0); return node == null ? null : node.getNodeValue(); } } return null; } private Date getTimestamp(Element element, String attribute) { try { // jaxb parser has a useful method for parsing a timestamp in ISO8601 format Calendar calendar = javax.xml.bind.DatatypeConverter.parseDateTime(element.getAttribute(attribute)); return calendar.getTime(); } catch(IllegalArgumentException e) { // ouch - a date is always expected in ISO8601 form (gregorian) // be kind and do not fail - the spec is not formal. return new Date(); // pretend it was "now" } } private void loadAbstractAggregatedPart(AbstractAggregatedTest o, Element element) { o.setName(element.getAttribute("name")); o.setTests(getIntAttributeWith0Default(element, "tests")); o.setFailures(getIntAttributeWith0Default(element, "failures")); o.setErrors(getIntAttributeWith0Default(element, "errors")); } public JunitResult loadFromXMLFile(File f) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(f); Element docElement = doc.getDocumentElement(); // There are three types of document elements possible: final String rootName = docElement.getNodeName(); if("testrun".equalsIgnoreCase(rootName)) { return loadTestrun(docElement); } else if("testsuites".equalsIgnoreCase(rootName)) { return loadTestSuites(docElement); } else if("testsuite".equalsIgnoreCase(rootName)) { return loadTestSuite(docElement); } else { throw new SAXNotSupportedException("Can only load 'testrun', 'testsuites' or 'testsuite', but got: " + rootName); } } private void loadNegativeResult(NegativeResult o, NodeList negativeList) { Node negativeNode = negativeList.item(0); if(negativeNode != null) { Element errorElement = (Element) negativeNode; o.setMessage(errorElement.getAttribute("message")); o.setType(errorElement.getAttribute("type")); // value (if any) is in a child node NodeList children = errorElement.getChildNodes(); Node n = children.item(0); if(n != null) o.setValue(n.getNodeValue()); } } private Testcase loadTestCase(Element element) { if(!"testcase".equalsIgnoreCase(element.getNodeName())) throw new IllegalArgumentException("Non 'testcase' element passed to #loadTestCase"); Testcase o = JunitresultFactory.eINSTANCE.createTestcase(); o.setClassname(element.getAttribute("classname")); o.setName(element.getAttribute("name")); o.setTime(element.getAttribute("time")); // Error element NodeList errors = element.getElementsByTagName("error"); if(errors.getLength() > 0) { Error error = JunitresultFactory.eINSTANCE.createError(); loadNegativeResult(error, errors); o.setError(error); } // Failure element NodeList failures = element.getElementsByTagName("failure"); if(failures.getLength() > 0) { Failure failure = JunitresultFactory.eINSTANCE.createFailure(); loadNegativeResult(failure, failures); o.setFailure(failure); } return o; } /** * Loads a &lt;testrun&gt; element which is the format used by Eclipse JUnit result export. * * @param element * @return */ private Testrun loadTestrun(Element element) { if(!"testrun".equalsIgnoreCase(element.getNodeName())) { throw new IllegalArgumentException("Non 'testrun' element passed to #loadTestrun"); } Testrun o = JunitresultFactory.eINSTANCE.createTestrun(); loadAbstractAggregatedPart(o, element); o.setProject(element.getAttribute("project")); o.setStarted(getIntAttributeWith0Default(element, "started")); o.setIgnored(getIntAttributeWith0Default(element, "ignored")); // nested test suite(s) NodeList children = element.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { Node n = children.item(i); if(n.getNodeType() == Node.ELEMENT_NODE && "testsuite".equalsIgnoreCase(n.getNodeName())) o.getTestsuites().add(loadTestSuite((Element) n, false)); } return o; } /** * Loads a &lt;testsuite&gt; element in the form used by Eclipse testrun format, and when a testsuite is * the document root. (This implies that the extended attributes found in testsuite elements embedded in the * junitreport format are not parsed). * * @param element * @return */ private Testsuite loadTestSuite(Element element) { return loadTestSuite(element, false); } /** * Loads a &lt;testsuite&gt; element in one of two alternate forms as directed by the parameter <code>extendedForm</code>. * The extended form should be used when the element is part of a &lt;testsuites&gt; element as * generated by junitreport. * * @param element * @param extendedForm * @return */ private Testsuite loadTestSuite(Element element, boolean extendedForm) { Testsuite o = JunitresultFactory.eINSTANCE.createTestsuite(); // super class part loadAbstractAggregatedPart(o, element); // attributes o.setSystem_err(getTagValue(element, "system-err")); o.setSystem_out(getTagValue(element, "system-out")); o.setHostname(element.getAttribute("hostname")); o.setTime(element.getAttribute("time")); o.setTimestamp(getTimestamp(element, "timestamp")); // when embedded in a junitreport result where <testsuites> is the document root these two // attributes are present in each nested testsuite. // if(extendedForm) { o.setId(getIntAttributeWith0Default(element, "id")); o.setPackage(element.getAttribute("package")); } // child test suites (nested) & test cases NodeList children = element.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { Node n = children.item(i); if(n.getNodeType() == Node.ELEMENT_NODE) if("testsuite".equalsIgnoreCase(n.getNodeName())) o.getTestsuites().add(loadTestSuite((Element) n, extendedForm)); else if("testcase".equalsIgnoreCase(n.getNodeName())) o.getTestcases().add(loadTestCase((Element) n)); else if("properties".equalsIgnoreCase(n.getNodeName())) { NodeList properties = ((Element) n).getElementsByTagName("property"); for(int j = 0; j < properties.getLength(); j++) { - Node pn = properties.item(i); + Node pn = properties.item(j); if(pn.getNodeType() == Node.ELEMENT_NODE) { Element propertyElement = (Element) pn; Property p = JunitresultFactory.eINSTANCE.createProperty(); p.setName(propertyElement.getAttribute("name")); p.setValue(propertyElement.getAttribute("value")); o.getProperties().add(p); } } } } - // properties (optional) - NodeList properties = element.getElementsByTagName("property"); - for(int i = 0; i < properties.getLength(); i++) { - Node n = properties.item(i); - if(n.getNodeType() == Node.ELEMENT_NODE) { - Element propertyElement = (Element) n; - Property p = JunitresultFactory.eINSTANCE.createProperty(); - p.setName(propertyElement.getAttribute("name")); - p.setValue(propertyElement.getAttribute("value")); - o.getProperties().add(p); - } - } return o; } /** * Loads a &lt;testsuites&gt; element as found in the result from a junitreport. All nested * &lt;testsuite&gt; elements have extended attributes. * * @param docElement * @return */ private Testsuites loadTestSuites(Element docElement) { Testsuites o = JunitresultFactory.eINSTANCE.createTestsuites(); NodeList children = docElement.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { Node n = children.item(i); if(n.getNodeType() == Node.ELEMENT_NODE && "testsuite".equalsIgnoreCase(n.getNodeName())) o.getTestsuites().add(loadTestSuite((Element) n, true)); } return o; } }
false
true
private Testsuite loadTestSuite(Element element, boolean extendedForm) { Testsuite o = JunitresultFactory.eINSTANCE.createTestsuite(); // super class part loadAbstractAggregatedPart(o, element); // attributes o.setSystem_err(getTagValue(element, "system-err")); o.setSystem_out(getTagValue(element, "system-out")); o.setHostname(element.getAttribute("hostname")); o.setTime(element.getAttribute("time")); o.setTimestamp(getTimestamp(element, "timestamp")); // when embedded in a junitreport result where <testsuites> is the document root these two // attributes are present in each nested testsuite. // if(extendedForm) { o.setId(getIntAttributeWith0Default(element, "id")); o.setPackage(element.getAttribute("package")); } // child test suites (nested) & test cases NodeList children = element.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { Node n = children.item(i); if(n.getNodeType() == Node.ELEMENT_NODE) if("testsuite".equalsIgnoreCase(n.getNodeName())) o.getTestsuites().add(loadTestSuite((Element) n, extendedForm)); else if("testcase".equalsIgnoreCase(n.getNodeName())) o.getTestcases().add(loadTestCase((Element) n)); else if("properties".equalsIgnoreCase(n.getNodeName())) { NodeList properties = ((Element) n).getElementsByTagName("property"); for(int j = 0; j < properties.getLength(); j++) { Node pn = properties.item(i); if(pn.getNodeType() == Node.ELEMENT_NODE) { Element propertyElement = (Element) pn; Property p = JunitresultFactory.eINSTANCE.createProperty(); p.setName(propertyElement.getAttribute("name")); p.setValue(propertyElement.getAttribute("value")); o.getProperties().add(p); } } } } // properties (optional) NodeList properties = element.getElementsByTagName("property"); for(int i = 0; i < properties.getLength(); i++) { Node n = properties.item(i); if(n.getNodeType() == Node.ELEMENT_NODE) { Element propertyElement = (Element) n; Property p = JunitresultFactory.eINSTANCE.createProperty(); p.setName(propertyElement.getAttribute("name")); p.setValue(propertyElement.getAttribute("value")); o.getProperties().add(p); } } return o; }
private Testsuite loadTestSuite(Element element, boolean extendedForm) { Testsuite o = JunitresultFactory.eINSTANCE.createTestsuite(); // super class part loadAbstractAggregatedPart(o, element); // attributes o.setSystem_err(getTagValue(element, "system-err")); o.setSystem_out(getTagValue(element, "system-out")); o.setHostname(element.getAttribute("hostname")); o.setTime(element.getAttribute("time")); o.setTimestamp(getTimestamp(element, "timestamp")); // when embedded in a junitreport result where <testsuites> is the document root these two // attributes are present in each nested testsuite. // if(extendedForm) { o.setId(getIntAttributeWith0Default(element, "id")); o.setPackage(element.getAttribute("package")); } // child test suites (nested) & test cases NodeList children = element.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { Node n = children.item(i); if(n.getNodeType() == Node.ELEMENT_NODE) if("testsuite".equalsIgnoreCase(n.getNodeName())) o.getTestsuites().add(loadTestSuite((Element) n, extendedForm)); else if("testcase".equalsIgnoreCase(n.getNodeName())) o.getTestcases().add(loadTestCase((Element) n)); else if("properties".equalsIgnoreCase(n.getNodeName())) { NodeList properties = ((Element) n).getElementsByTagName("property"); for(int j = 0; j < properties.getLength(); j++) { Node pn = properties.item(j); if(pn.getNodeType() == Node.ELEMENT_NODE) { Element propertyElement = (Element) pn; Property p = JunitresultFactory.eINSTANCE.createProperty(); p.setName(propertyElement.getAttribute("name")); p.setValue(propertyElement.getAttribute("value")); o.getProperties().add(p); } } } } return o; }
diff --git a/src/ca/slashdev/bb/tasks/JadtoolTask.java b/src/ca/slashdev/bb/tasks/JadtoolTask.java index e40007b..e918b5c 100644 --- a/src/ca/slashdev/bb/tasks/JadtoolTask.java +++ b/src/ca/slashdev/bb/tasks/JadtoolTask.java @@ -1,198 +1,198 @@ /* * Copyright 2008 Josh Kropf * * This file is part of bb-ant-tools. * * bb-ant-tools 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. * * bb-ant-tools 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 bb-ant-tools; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package ca.slashdev.bb.tasks; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Vector; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.ResourceCollection; import org.apache.tools.ant.types.resources.FileResource; import org.apache.tools.ant.util.FileUtils; import org.apache.tools.ant.util.ResourceUtils; import ca.slashdev.bb.types.OverrideType; import ca.slashdev.bb.util.Utils; /** * @author josh */ public class JadtoolTask extends BaseTask { private File input; private File destDir; private Vector<ResourceCollection> resources = new Vector<ResourceCollection>(); private Vector<OverrideType> overrides = new Vector<OverrideType>(); private Map<String, OverrideType> overrideMap = new HashMap<String, OverrideType>(); public void setInput(File input) { this.input = input; } public void setDestDir(File destDir) { this.destDir = destDir; } public void add(ResourceCollection res) { resources.add(res); } public void add(OverrideType override) { overrides.add(override); } @Override public void execute() throws BuildException { super.execute(); if (input == null) throw new BuildException("input is a required attribute"); if (!input.exists()) throw new BuildException("input file is missing"); if (resources.size() == 0) throw new BuildException("specify at least one cod file"); if (destDir == null) throw new BuildException("destdir is a required attribute"); if (!destDir.exists()) if (!destDir.mkdirs()) throw new BuildException("unable to create destination directory"); for (OverrideType o : overrides) { o.validate(); overrideMap.put(o.getKey().toLowerCase(), o); } executeRewrite(); } @SuppressWarnings("unchecked") private void executeRewrite() { BufferedReader reader = null; PrintStream output = null; try { try { reader = new BufferedReader(new FileReader(input)); output = new PrintStream(new File(destDir, input.getName())); int i, num = 0; String line, key, value; OverrideType override; while ((line = reader.readLine()) != null) { num ++; i = line.indexOf(':'); if (i == -1) throw new BuildException("unexpected line in jad file: "+num); key = line.substring(0, i); value = line.substring(i+1); if (key.startsWith("RIM-COD-URL") || key.startsWith("RIM-COD-SHA1") || key.startsWith("RIM-COD-Size")) { continue; // ignore line } // check for .jad element override, remove from map if found override = overrideMap.get(key.toLowerCase()); if (override != null) { value = override.getValue(); overrideMap.remove(key.toLowerCase()); } output.printf("%s: %s\n", key, value); } } catch (IOException e) { throw new BuildException("error creating jad file", e); } try { int num = 0; File destFile; Resource r; for (ResourceCollection rc : resources) { Iterator<Resource> i = rc.iterator(); while (i.hasNext()) { r = i.next(); destFile = new File(destDir, Utils.getFilePart(r)); if (Utils.isZip(r)) { String[] zipEntries = Utils.extract(r, destDir); for (String entry : zipEntries) { destFile = new File(destDir, entry); if (num == 0) { output.printf("RIM-COD-URL: %s\n", destFile.getName()); output.printf("RIM-COD-SHA1: %s\n", Utils.getSHA1(destFile)); output.printf("RIM-COD-Size: %d\n", destFile.length()); } else { output.printf("RIM-COD-URL-%d: %s\n", num, destFile.getName()); output.printf("RIM-COD-SHA1-%d: %s\n", num, Utils.getSHA1(destFile)); output.printf("RIM-COD-Size-%d: %d\n", num, destFile.length()); } num++; } } else { ResourceUtils.copyResource(r, new FileResource(destFile)); if (num == 0) { output.printf("RIM-COD-URL: %s\n", destFile.getName()); output.printf("RIM-COD-SHA1: %s\n", Utils.getSHA1(destFile)); output.printf("RIM-COD-Size: %d\n", destFile.length()); } else { output.printf("RIM-COD-URL-%d: %s\n", num, destFile.getName()); output.printf("RIM-COD-SHA1-%d: %s\n", num, Utils.getSHA1(destFile)); output.printf("RIM-COD-Size-%d: %d\n", num, destFile.length()); } + num ++; } - num ++; } } } catch (IOException e) { throw new BuildException("error copying cod file", e); } // flush remaining overrides into target .jad for (OverrideType override : overrideMap.values()) { output.printf("%s: %s\n", override.getKey(), override.getValue()); } } finally { FileUtils.close(reader); FileUtils.close(output); } } }
false
true
private void executeRewrite() { BufferedReader reader = null; PrintStream output = null; try { try { reader = new BufferedReader(new FileReader(input)); output = new PrintStream(new File(destDir, input.getName())); int i, num = 0; String line, key, value; OverrideType override; while ((line = reader.readLine()) != null) { num ++; i = line.indexOf(':'); if (i == -1) throw new BuildException("unexpected line in jad file: "+num); key = line.substring(0, i); value = line.substring(i+1); if (key.startsWith("RIM-COD-URL") || key.startsWith("RIM-COD-SHA1") || key.startsWith("RIM-COD-Size")) { continue; // ignore line } // check for .jad element override, remove from map if found override = overrideMap.get(key.toLowerCase()); if (override != null) { value = override.getValue(); overrideMap.remove(key.toLowerCase()); } output.printf("%s: %s\n", key, value); } } catch (IOException e) { throw new BuildException("error creating jad file", e); } try { int num = 0; File destFile; Resource r; for (ResourceCollection rc : resources) { Iterator<Resource> i = rc.iterator(); while (i.hasNext()) { r = i.next(); destFile = new File(destDir, Utils.getFilePart(r)); if (Utils.isZip(r)) { String[] zipEntries = Utils.extract(r, destDir); for (String entry : zipEntries) { destFile = new File(destDir, entry); if (num == 0) { output.printf("RIM-COD-URL: %s\n", destFile.getName()); output.printf("RIM-COD-SHA1: %s\n", Utils.getSHA1(destFile)); output.printf("RIM-COD-Size: %d\n", destFile.length()); } else { output.printf("RIM-COD-URL-%d: %s\n", num, destFile.getName()); output.printf("RIM-COD-SHA1-%d: %s\n", num, Utils.getSHA1(destFile)); output.printf("RIM-COD-Size-%d: %d\n", num, destFile.length()); } num++; } } else { ResourceUtils.copyResource(r, new FileResource(destFile)); if (num == 0) { output.printf("RIM-COD-URL: %s\n", destFile.getName()); output.printf("RIM-COD-SHA1: %s\n", Utils.getSHA1(destFile)); output.printf("RIM-COD-Size: %d\n", destFile.length()); } else { output.printf("RIM-COD-URL-%d: %s\n", num, destFile.getName()); output.printf("RIM-COD-SHA1-%d: %s\n", num, Utils.getSHA1(destFile)); output.printf("RIM-COD-Size-%d: %d\n", num, destFile.length()); } } num ++; } } } catch (IOException e) { throw new BuildException("error copying cod file", e); } // flush remaining overrides into target .jad for (OverrideType override : overrideMap.values()) { output.printf("%s: %s\n", override.getKey(), override.getValue()); } } finally { FileUtils.close(reader); FileUtils.close(output); } }
private void executeRewrite() { BufferedReader reader = null; PrintStream output = null; try { try { reader = new BufferedReader(new FileReader(input)); output = new PrintStream(new File(destDir, input.getName())); int i, num = 0; String line, key, value; OverrideType override; while ((line = reader.readLine()) != null) { num ++; i = line.indexOf(':'); if (i == -1) throw new BuildException("unexpected line in jad file: "+num); key = line.substring(0, i); value = line.substring(i+1); if (key.startsWith("RIM-COD-URL") || key.startsWith("RIM-COD-SHA1") || key.startsWith("RIM-COD-Size")) { continue; // ignore line } // check for .jad element override, remove from map if found override = overrideMap.get(key.toLowerCase()); if (override != null) { value = override.getValue(); overrideMap.remove(key.toLowerCase()); } output.printf("%s: %s\n", key, value); } } catch (IOException e) { throw new BuildException("error creating jad file", e); } try { int num = 0; File destFile; Resource r; for (ResourceCollection rc : resources) { Iterator<Resource> i = rc.iterator(); while (i.hasNext()) { r = i.next(); destFile = new File(destDir, Utils.getFilePart(r)); if (Utils.isZip(r)) { String[] zipEntries = Utils.extract(r, destDir); for (String entry : zipEntries) { destFile = new File(destDir, entry); if (num == 0) { output.printf("RIM-COD-URL: %s\n", destFile.getName()); output.printf("RIM-COD-SHA1: %s\n", Utils.getSHA1(destFile)); output.printf("RIM-COD-Size: %d\n", destFile.length()); } else { output.printf("RIM-COD-URL-%d: %s\n", num, destFile.getName()); output.printf("RIM-COD-SHA1-%d: %s\n", num, Utils.getSHA1(destFile)); output.printf("RIM-COD-Size-%d: %d\n", num, destFile.length()); } num++; } } else { ResourceUtils.copyResource(r, new FileResource(destFile)); if (num == 0) { output.printf("RIM-COD-URL: %s\n", destFile.getName()); output.printf("RIM-COD-SHA1: %s\n", Utils.getSHA1(destFile)); output.printf("RIM-COD-Size: %d\n", destFile.length()); } else { output.printf("RIM-COD-URL-%d: %s\n", num, destFile.getName()); output.printf("RIM-COD-SHA1-%d: %s\n", num, Utils.getSHA1(destFile)); output.printf("RIM-COD-Size-%d: %d\n", num, destFile.length()); } num ++; } } } } catch (IOException e) { throw new BuildException("error copying cod file", e); } // flush remaining overrides into target .jad for (OverrideType override : overrideMap.values()) { output.printf("%s: %s\n", override.getKey(), override.getValue()); } } finally { FileUtils.close(reader); FileUtils.close(output); } }
diff --git a/unfolding/examples/de/fhpotsdam/unfolding/examples/MBTilesMapApp.java b/unfolding/examples/de/fhpotsdam/unfolding/examples/MBTilesMapApp.java index 0d272ee..9f08939 100644 --- a/unfolding/examples/de/fhpotsdam/unfolding/examples/MBTilesMapApp.java +++ b/unfolding/examples/de/fhpotsdam/unfolding/examples/MBTilesMapApp.java @@ -1,32 +1,32 @@ package de.fhpotsdam.unfolding.examples; import processing.core.PApplet; import codeanticode.glgraphics.GLConstants; import de.fhpotsdam.unfolding.Map; import de.fhpotsdam.unfolding.providers.MBTilesMapProvider; import de.fhpotsdam.unfolding.utils.MapUtils; public class MBTilesMapApp extends PApplet { // Connection to SQLite/MBTiles in distribution (outside of the jar) public static final String JDBC_CONN_STRING_TABLE = "jdbc:sqlite:./data/muse-dark-2-8.mbtiles"; // Connection to SQLite/MBTiles in dev environemtn (link to the project) public static final String JDBC_CONN_STRING_MAC = "jdbc:sqlite:../../unfolding/data/muse-dark-2-8.mbtiles"; Map map; public void setup() { size(800, 600, GLConstants.GLGRAPHICS); map = new Map(this, 0, 0, width, height, new MBTilesMapProvider(JDBC_CONN_STRING_MAC)); MapUtils.createDefaultEventDispatcher(this, map); - map.setZoomRange(2, 9); + map.setZoomRange(2, 8); } public void draw() { background(0); map.draw(); } }
true
true
public void setup() { size(800, 600, GLConstants.GLGRAPHICS); map = new Map(this, 0, 0, width, height, new MBTilesMapProvider(JDBC_CONN_STRING_MAC)); MapUtils.createDefaultEventDispatcher(this, map); map.setZoomRange(2, 9); }
public void setup() { size(800, 600, GLConstants.GLGRAPHICS); map = new Map(this, 0, 0, width, height, new MBTilesMapProvider(JDBC_CONN_STRING_MAC)); MapUtils.createDefaultEventDispatcher(this, map); map.setZoomRange(2, 8); }
diff --git a/utils/common/src/main/java/brooklyn/util/net/Urls.java b/utils/common/src/main/java/brooklyn/util/net/Urls.java index 0a8740e95..e3740e941 100644 --- a/utils/common/src/main/java/brooklyn/util/net/Urls.java +++ b/utils/common/src/main/java/brooklyn/util/net/Urls.java @@ -1,105 +1,105 @@ package brooklyn.util.net; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import javax.annotation.Nullable; import com.google.common.base.Function; import com.google.common.base.Throwables; public class Urls { public static Function<String,URI> stringToUriFunction() { return StringToUri.INSTANCE; } public static Function<String,URL> stringToUrlFunction() { return StringToUrl.INSTANCE; } private static enum StringToUri implements Function<String,URI> { INSTANCE; @Override public URI apply(@Nullable String input) { return toUri(input); } @Override public String toString() { return "StringToUri"; } } private static enum StringToUrl implements Function<String,URL> { INSTANCE; @Override public URL apply(@Nullable String input) { return toUrl(input); } @Override public String toString() { return "StringToUrl"; } } /** creates a URL, preserving null and propagating exceptions *unchecked* */ public static final URL toUrl(@Nullable String url) { if (url==null) return null; try { return new URL(url); } catch (MalformedURLException e) { // FOAD throw Throwables.propagate(e); } } /** creates a URL, preserving null and propagating exceptions *unchecked* */ public static final URL toUrl(@Nullable URI uri) { if (uri==null) return null; try { return uri.toURL(); } catch (MalformedURLException e) { // FOAD throw Throwables.propagate(e); } } /** creates a URI, preserving null and propagating exceptions *unchecked* */ public static final URI toUri(@Nullable String uri) { if (uri==null) return null; return URI.create(uri); } /** creates a URI, preserving null and propagating exceptions *unchecked* */ public static final URI toUri(@Nullable URL url) { if (url==null) return null; try { return url.toURI(); } catch (URISyntaxException e) { // FOAD throw Throwables.propagate(e); } } /** returns the items with exactly one "/" between items (whether or not the individual items start or end with /), * except where character before the / is a : (url syntax) in which case it will permit multiple (will not remove any) */ public static String mergePaths(String ...items) { StringBuilder result = new StringBuilder(); for (String item: items) { boolean trimThisMerge = result.length()>0 && !result.toString().endsWith("://") && !result.toString().endsWith(":///") && !result.toString().endsWith(":"); if (trimThisMerge) { while (result.charAt(result.length()-1)=='/') result.deleteCharAt(result.length()-1); result.append('/'); } int i = result.length(); result.append(item); if (trimThisMerge) { - while (result.charAt(i)=='/') + while (result.length()>i && result.charAt(i)=='/') result.deleteCharAt(i); } } return result.toString(); } }
true
true
public static String mergePaths(String ...items) { StringBuilder result = new StringBuilder(); for (String item: items) { boolean trimThisMerge = result.length()>0 && !result.toString().endsWith("://") && !result.toString().endsWith(":///") && !result.toString().endsWith(":"); if (trimThisMerge) { while (result.charAt(result.length()-1)=='/') result.deleteCharAt(result.length()-1); result.append('/'); } int i = result.length(); result.append(item); if (trimThisMerge) { while (result.charAt(i)=='/') result.deleteCharAt(i); } } return result.toString(); }
public static String mergePaths(String ...items) { StringBuilder result = new StringBuilder(); for (String item: items) { boolean trimThisMerge = result.length()>0 && !result.toString().endsWith("://") && !result.toString().endsWith(":///") && !result.toString().endsWith(":"); if (trimThisMerge) { while (result.charAt(result.length()-1)=='/') result.deleteCharAt(result.length()-1); result.append('/'); } int i = result.length(); result.append(item); if (trimThisMerge) { while (result.length()>i && result.charAt(i)=='/') result.deleteCharAt(i); } } return result.toString(); }
diff --git a/src/com/tokenizer/util/FileReader.java b/src/com/tokenizer/util/FileReader.java index 722ca04..54aaf0f 100644 --- a/src/com/tokenizer/util/FileReader.java +++ b/src/com/tokenizer/util/FileReader.java @@ -1,177 +1,177 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.tokenizer.util; import com.tokenizer.controller.*; import com.tokenizer.model.BigConcurentHashMap; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.concurrent.Callable; /** * * @author irfannurhakim */ public class FileReader implements Callable { private FileWalker fileWalker; private File file; private Path path; private int count; public FileReader(){ } public FileReader(File file) { this.file = file; } public FileReader(Path path, int count) { this.path = path; this.count = count; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } /* * public StringBuilder getText() { return text; } * * public void setText(StringBuilder text) { this.text = text; } */ public void setCaller(FileWalker fileWalker) { this.fileWalker = fileWalker; } public FileWalker getCaller() { return fileWalker; } @Override public Object call() throws IOException, InterruptedException { String line = Files.readAllLines(this.path, StandardCharsets.UTF_8).toString().toLowerCase().replaceAll("x-to|x-from", ""); //System.out.println(line); /* * raw -> array 0 head, array 1 tail */ String[] raw = line.split("date: ", 2); String [] date = raw[1].split("from: ",2); HashMap <String,Integer> dateMap = dateTokenizer.getListDate(date[0]); synchronized(BigConcurentHashMap.dateConcurentMap ) { BigConcurentHashMap.mergeBigHashMap(BigConcurentHashMap.dateConcurentMap, dateMap); } //System.out.println(dateMap); if (date.length == 1) { date[1] = ""; } String[] from; if (date[1].contains("to: ")) { from = date[1].split("to: ", 2); } else { from = date; } - HashMap <String,Integer> fromMap = FromTokenizer.getListFrom(from[0].replaceAll(", ", "")); + HashMap <String,Integer> fromMap = FromTokenizer.getListFrom(from[0].replaceAll(", ", " ")); synchronized(BigConcurentHashMap.fromConcurentMap ) { BigConcurentHashMap.mergeBigHashMap(BigConcurentHashMap.fromConcurentMap, fromMap); } //System.out.println(fromMap); if (from.length == 1) { from[1] = ""; } String[] to; if (from[1].contains("subject: ")) { to = from[1].split("subject: ", 2); } else { to = from; } HashMap <String,Integer> toMap = toTokenizer.getListTo(to[0]); synchronized(BigConcurentHashMap.toConcurentMap ) { BigConcurentHashMap.mergeBigHashMap(BigConcurentHashMap.toConcurentMap, toMap); } if (to.length == 1) { to[1] = ""; } String[] subject; - if (to[1].contains("mime-version : ")) { + if (to[1].contains("mime-version: ")) { subject = to[1].split("mime-version: ", 2); } else { subject = to; } HashMap <String,Integer> subjectMap = subject_bodyTokenizer.getListTerm(subject[0]); synchronized(BigConcurentHashMap.subjectConcurentMap ) { BigConcurentHashMap.mergeBigHashMap(BigConcurentHashMap.subjectConcurentMap, subjectMap); } HashMap <String,Integer> bodyMap = new HashMap<String, Integer>(); if (subject.length == 1) { subject[1] = ""; } String[] body; if (subject[1].contains(".pst") || subject[1].contains(".nsf")) { body = subject[1].split("(\\.pst)|(\\.nsf)", 2); } else { body = subject; } if (body.length == 1) { body[1] = ""; } bodyMap= subject_bodyTokenizer.getListTerm(body[1]); synchronized(BigConcurentHashMap.bodyConcurentMap ) { BigConcurentHashMap.mergeBigHashMap(BigConcurentHashMap.bodyConcurentMap, bodyMap); } HashMap <String,Integer> allFieldMap = AllFieldTokenizer.allFieldTermList(dateMap, toMap, fromMap, subjectMap, bodyMap); synchronized(BigConcurentHashMap.allConcurentMap ) { BigConcurentHashMap.mergeBigHashMap(BigConcurentHashMap.allConcurentMap, allFieldMap); } //System.out.println(allFieldMap); //System.out.println(path.toString()); fileWalker.callback(dateMap, fromMap, toMap, subjectMap, bodyMap, allFieldMap, count); return null; } }
false
true
public Object call() throws IOException, InterruptedException { String line = Files.readAllLines(this.path, StandardCharsets.UTF_8).toString().toLowerCase().replaceAll("x-to|x-from", ""); //System.out.println(line); /* * raw -> array 0 head, array 1 tail */ String[] raw = line.split("date: ", 2); String [] date = raw[1].split("from: ",2); HashMap <String,Integer> dateMap = dateTokenizer.getListDate(date[0]); synchronized(BigConcurentHashMap.dateConcurentMap ) { BigConcurentHashMap.mergeBigHashMap(BigConcurentHashMap.dateConcurentMap, dateMap); } //System.out.println(dateMap); if (date.length == 1) { date[1] = ""; } String[] from; if (date[1].contains("to: ")) { from = date[1].split("to: ", 2); } else { from = date; } HashMap <String,Integer> fromMap = FromTokenizer.getListFrom(from[0].replaceAll(", ", "")); synchronized(BigConcurentHashMap.fromConcurentMap ) { BigConcurentHashMap.mergeBigHashMap(BigConcurentHashMap.fromConcurentMap, fromMap); } //System.out.println(fromMap); if (from.length == 1) { from[1] = ""; } String[] to; if (from[1].contains("subject: ")) { to = from[1].split("subject: ", 2); } else { to = from; } HashMap <String,Integer> toMap = toTokenizer.getListTo(to[0]); synchronized(BigConcurentHashMap.toConcurentMap ) { BigConcurentHashMap.mergeBigHashMap(BigConcurentHashMap.toConcurentMap, toMap); } if (to.length == 1) { to[1] = ""; } String[] subject; if (to[1].contains("mime-version : ")) { subject = to[1].split("mime-version: ", 2); } else { subject = to; } HashMap <String,Integer> subjectMap = subject_bodyTokenizer.getListTerm(subject[0]); synchronized(BigConcurentHashMap.subjectConcurentMap ) { BigConcurentHashMap.mergeBigHashMap(BigConcurentHashMap.subjectConcurentMap, subjectMap); } HashMap <String,Integer> bodyMap = new HashMap<String, Integer>(); if (subject.length == 1) { subject[1] = ""; } String[] body; if (subject[1].contains(".pst") || subject[1].contains(".nsf")) { body = subject[1].split("(\\.pst)|(\\.nsf)", 2); } else { body = subject; } if (body.length == 1) { body[1] = ""; } bodyMap= subject_bodyTokenizer.getListTerm(body[1]); synchronized(BigConcurentHashMap.bodyConcurentMap ) { BigConcurentHashMap.mergeBigHashMap(BigConcurentHashMap.bodyConcurentMap, bodyMap); } HashMap <String,Integer> allFieldMap = AllFieldTokenizer.allFieldTermList(dateMap, toMap, fromMap, subjectMap, bodyMap); synchronized(BigConcurentHashMap.allConcurentMap ) { BigConcurentHashMap.mergeBigHashMap(BigConcurentHashMap.allConcurentMap, allFieldMap); } //System.out.println(allFieldMap); //System.out.println(path.toString()); fileWalker.callback(dateMap, fromMap, toMap, subjectMap, bodyMap, allFieldMap, count); return null; }
public Object call() throws IOException, InterruptedException { String line = Files.readAllLines(this.path, StandardCharsets.UTF_8).toString().toLowerCase().replaceAll("x-to|x-from", ""); //System.out.println(line); /* * raw -> array 0 head, array 1 tail */ String[] raw = line.split("date: ", 2); String [] date = raw[1].split("from: ",2); HashMap <String,Integer> dateMap = dateTokenizer.getListDate(date[0]); synchronized(BigConcurentHashMap.dateConcurentMap ) { BigConcurentHashMap.mergeBigHashMap(BigConcurentHashMap.dateConcurentMap, dateMap); } //System.out.println(dateMap); if (date.length == 1) { date[1] = ""; } String[] from; if (date[1].contains("to: ")) { from = date[1].split("to: ", 2); } else { from = date; } HashMap <String,Integer> fromMap = FromTokenizer.getListFrom(from[0].replaceAll(", ", " ")); synchronized(BigConcurentHashMap.fromConcurentMap ) { BigConcurentHashMap.mergeBigHashMap(BigConcurentHashMap.fromConcurentMap, fromMap); } //System.out.println(fromMap); if (from.length == 1) { from[1] = ""; } String[] to; if (from[1].contains("subject: ")) { to = from[1].split("subject: ", 2); } else { to = from; } HashMap <String,Integer> toMap = toTokenizer.getListTo(to[0]); synchronized(BigConcurentHashMap.toConcurentMap ) { BigConcurentHashMap.mergeBigHashMap(BigConcurentHashMap.toConcurentMap, toMap); } if (to.length == 1) { to[1] = ""; } String[] subject; if (to[1].contains("mime-version: ")) { subject = to[1].split("mime-version: ", 2); } else { subject = to; } HashMap <String,Integer> subjectMap = subject_bodyTokenizer.getListTerm(subject[0]); synchronized(BigConcurentHashMap.subjectConcurentMap ) { BigConcurentHashMap.mergeBigHashMap(BigConcurentHashMap.subjectConcurentMap, subjectMap); } HashMap <String,Integer> bodyMap = new HashMap<String, Integer>(); if (subject.length == 1) { subject[1] = ""; } String[] body; if (subject[1].contains(".pst") || subject[1].contains(".nsf")) { body = subject[1].split("(\\.pst)|(\\.nsf)", 2); } else { body = subject; } if (body.length == 1) { body[1] = ""; } bodyMap= subject_bodyTokenizer.getListTerm(body[1]); synchronized(BigConcurentHashMap.bodyConcurentMap ) { BigConcurentHashMap.mergeBigHashMap(BigConcurentHashMap.bodyConcurentMap, bodyMap); } HashMap <String,Integer> allFieldMap = AllFieldTokenizer.allFieldTermList(dateMap, toMap, fromMap, subjectMap, bodyMap); synchronized(BigConcurentHashMap.allConcurentMap ) { BigConcurentHashMap.mergeBigHashMap(BigConcurentHashMap.allConcurentMap, allFieldMap); } //System.out.println(allFieldMap); //System.out.println(path.toString()); fileWalker.callback(dateMap, fromMap, toMap, subjectMap, bodyMap, allFieldMap, count); return null; }
diff --git a/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java b/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java index a8dea67b..90284396 100644 --- a/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java +++ b/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java @@ -1,8741 +1,8741 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.assignment.tool; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Hashtable; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.sakaiproject.announcement.api.AnnouncementChannel; import org.sakaiproject.announcement.api.AnnouncementMessageEdit; import org.sakaiproject.announcement.api.AnnouncementMessageHeaderEdit; import org.sakaiproject.announcement.api.AnnouncementService; import org.sakaiproject.assignment.api.Assignment; import org.sakaiproject.assignment.api.AssignmentContentEdit; import org.sakaiproject.assignment.api.AssignmentEdit; import org.sakaiproject.assignment.api.AssignmentSubmission; import org.sakaiproject.assignment.api.AssignmentSubmissionEdit; import org.sakaiproject.assignment.cover.AssignmentService; import org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer; import org.sakaiproject.assignment.taggable.api.TaggingHelperInfo; import org.sakaiproject.assignment.taggable.api.TaggingManager; import org.sakaiproject.assignment.taggable.api.TaggingProvider; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Pager; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Sort; import org.sakaiproject.authz.api.AuthzGroup; import org.sakaiproject.authz.api.GroupNotDefinedException; import org.sakaiproject.authz.api.PermissionsHelper; import org.sakaiproject.authz.api.SecurityAdvisor; import org.sakaiproject.authz.api.SecurityAdvisor.SecurityAdvice; import org.sakaiproject.authz.cover.AuthzGroupService; import org.sakaiproject.authz.cover.SecurityService; import org.sakaiproject.calendar.api.Calendar; import org.sakaiproject.calendar.api.CalendarEvent; import org.sakaiproject.calendar.api.CalendarService; import org.sakaiproject.cheftool.Context; import org.sakaiproject.cheftool.JetspeedRunData; import org.sakaiproject.cheftool.PagedResourceActionII; import org.sakaiproject.cheftool.PortletConfig; import org.sakaiproject.cheftool.RunData; import org.sakaiproject.cheftool.VelocityPortlet; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.content.api.ContentResource; import org.sakaiproject.content.api.ContentTypeImageService; import org.sakaiproject.content.api.FilePickerHelper; import org.sakaiproject.content.cover.ContentHostingService; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.ResourcePropertiesEdit; import org.sakaiproject.entity.cover.EntityManager; import org.sakaiproject.event.api.SessionState; import org.sakaiproject.event.cover.EventTrackingService; import org.sakaiproject.event.cover.NotificationService; import org.sakaiproject.exception.IdInvalidException; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.IdUsedException; import org.sakaiproject.exception.InUseException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.javax.PagingPosition; import org.sakaiproject.service.gradebook.shared.AssignmentHasIllegalPointsException; import org.sakaiproject.service.gradebook.shared.GradebookService; import org.sakaiproject.site.api.Group; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.time.api.Time; import org.sakaiproject.time.api.TimeBreakdown; import org.sakaiproject.time.cover.TimeService; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.tool.cover.ToolManager; import org.sakaiproject.user.api.User; import org.sakaiproject.user.cover.UserDirectoryService; import org.sakaiproject.util.FileItem; import org.sakaiproject.util.FormattedText; import org.sakaiproject.util.ParameterParser; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.SortedIterator; import org.sakaiproject.util.StringUtil; import org.sakaiproject.util.Validator; import org.sakaiproject.contentreview.service.ContentReviewService; /** * <p> * AssignmentAction is the action class for the assignment tool. * </p> */ public class AssignmentAction extends PagedResourceActionII { private static ResourceLoader rb = new ResourceLoader("assignment"); private static final Boolean allowReviewService = ServerConfigurationService.getBoolean("assignment.useContentReview", false); /** Is the review service available? */ private static final String ALLOW_REVIEW_SERVICE = "allow_review_service"; /** Is review service enabled? */ private static final String ENABLE_REVIEW_SERVICE = "enable_review_service"; private static final String NEW_ASSIGNMENT_USE_REVIEW_SERVICE = "new_assignment_use_review_service"; private static final String NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW = "new_assignment_allow_student_view"; /** The attachments */ private static final String ATTACHMENTS = "Assignment.attachments"; /** The content type image lookup service in the State. */ private static final String STATE_CONTENT_TYPE_IMAGE_SERVICE = "Assignment.content_type_image_service"; /** The calendar service in the State. */ private static final String STATE_CALENDAR_SERVICE = "Assignment.calendar_service"; /** The announcement service in the State. */ private static final String STATE_ANNOUNCEMENT_SERVICE = "Assignment.announcement_service"; /** The calendar object */ private static final String CALENDAR = "calendar"; /** The announcement channel */ private static final String ANNOUNCEMENT_CHANNEL = "announcement_channel"; /** The state mode */ private static final String STATE_MODE = "Assignment.mode"; /** The context string */ private static final String STATE_CONTEXT_STRING = "Assignment.context_string"; /** The user */ private static final String STATE_USER = "Assignment.user"; // SECTION MOD /** Used to keep track of the section info not currently being used. */ private static final String STATE_SECTION_STRING = "Assignment.section_string"; /** **************************** sort assignment ********************** */ /** state sort * */ private static final String SORTED_BY = "Assignment.sorted_by"; /** state sort ascendingly * */ private static final String SORTED_ASC = "Assignment.sorted_asc"; /** sort by assignment title */ private static final String SORTED_BY_TITLE = "title"; /** sort by assignment section */ private static final String SORTED_BY_SECTION = "section"; /** sort by assignment due date */ private static final String SORTED_BY_DUEDATE = "duedate"; /** sort by assignment open date */ private static final String SORTED_BY_OPENDATE = "opendate"; /** sort by assignment status */ private static final String SORTED_BY_ASSIGNMENT_STATUS = "assignment_status"; /** sort by assignment submission status */ private static final String SORTED_BY_SUBMISSION_STATUS = "submission_status"; /** sort by assignment number of submissions */ private static final String SORTED_BY_NUM_SUBMISSIONS = "num_submissions"; /** sort by assignment number of ungraded submissions */ private static final String SORTED_BY_NUM_UNGRADED = "num_ungraded"; /** sort by assignment submission grade */ private static final String SORTED_BY_GRADE = "grade"; /** sort by assignment maximun grade available */ private static final String SORTED_BY_MAX_GRADE = "max_grade"; /** sort by assignment range */ private static final String SORTED_BY_FOR = "for"; /** sort by group title */ private static final String SORTED_BY_GROUP_TITLE = "group_title"; /** sort by group description */ private static final String SORTED_BY_GROUP_DESCRIPTION = "group_description"; /** *************************** sort submission in instructor grade view *********************** */ /** state sort submission* */ private static final String SORTED_GRADE_SUBMISSION_BY = "Assignment.grade_submission_sorted_by"; /** state sort submission ascendingly * */ private static final String SORTED_GRADE_SUBMISSION_ASC = "Assignment.grade_submission_sorted_asc"; /** state sort submission by submitters last name * */ private static final String SORTED_GRADE_SUBMISSION_BY_LASTNAME = "sorted_grade_submission_by_lastname"; /** state sort submission by submit time * */ private static final String SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME = "sorted_grade_submission_by_submit_time"; /** state sort submission by submission status * */ private static final String SORTED_GRADE_SUBMISSION_BY_STATUS = "sorted_grade_submission_by_status"; /** state sort submission by submission grade * */ private static final String SORTED_GRADE_SUBMISSION_BY_GRADE = "sorted_grade_submission_by_grade"; /** state sort submission by submission released * */ private static final String SORTED_GRADE_SUBMISSION_BY_RELEASED = "sorted_grade_submission_by_released"; /** state sort submissuib by content review score **/ private static final String SORTED_GRADE_SUBMISSION_CONTENTREVIEW = "sorted_grade_submission_by_contentreview"; /** *************************** sort submission *********************** */ /** state sort submission* */ private static final String SORTED_SUBMISSION_BY = "Assignment.submission_sorted_by"; /** state sort submission ascendingly * */ private static final String SORTED_SUBMISSION_ASC = "Assignment.submission_sorted_asc"; /** state sort submission by submitters last name * */ private static final String SORTED_SUBMISSION_BY_LASTNAME = "sorted_submission_by_lastname"; /** state sort submission by submit time * */ private static final String SORTED_SUBMISSION_BY_SUBMIT_TIME = "sorted_submission_by_submit_time"; /** state sort submission by submission grade * */ private static final String SORTED_SUBMISSION_BY_GRADE = "sorted_submission_by_grade"; /** state sort submission by submission status * */ private static final String SORTED_SUBMISSION_BY_STATUS = "sorted_submission_by_status"; /** state sort submission by submission released * */ private static final String SORTED_SUBMISSION_BY_RELEASED = "sorted_submission_by_released"; /** state sort submission by assignment title */ private static final String SORTED_SUBMISSION_BY_ASSIGNMENT = "sorted_submission_by_assignment"; /** state sort submission by max grade */ private static final String SORTED_SUBMISSION_BY_MAX_GRADE = "sorted_submission_by_max_grade"; /** ******************** student's view assignment submission ****************************** */ /** the assignment object been viewing * */ private static final String VIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "Assignment.view_submission_assignment_reference"; /** the submission text to the assignment * */ private static final String VIEW_SUBMISSION_TEXT = "Assignment.view_submission_text"; /** the submission answer to Honor Pledge * */ private static final String VIEW_SUBMISSION_HONOR_PLEDGE_YES = "Assignment.view_submission_honor_pledge_yes"; /** ***************** student's preview of submission *************************** */ /** the assignment id * */ private static final String PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "preview_submission_assignment_reference"; /** the submission text * */ private static final String PREVIEW_SUBMISSION_TEXT = "preview_submission_text"; /** the submission honor pledge answer * */ private static final String PREVIEW_SUBMISSION_HONOR_PLEDGE_YES = "preview_submission_honor_pledge_yes"; /** the submission attachments * */ private static final String PREVIEW_SUBMISSION_ATTACHMENTS = "preview_attachments"; /** the flag indicate whether the to show the student view or not */ private static final String PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG = "preview_assignment_student_view_hide_flag"; /** the flag indicate whether the to show the assignment info or not */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG = "preview_assignment_assignment_hide_flag"; /** the assignment id */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_ID = "preview_assignment_assignment_id"; /** the assignment content id */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID = "preview_assignment_assignmentcontent_id"; /** ************** view assignment ***************************************** */ /** the hide assignment flag in the view assignment page * */ private static final String VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG = "view_assignment_hide_assignment_flag"; /** the hide student view flag in the view assignment page * */ private static final String VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG = "view_assignment_hide_student_view_flag"; /** ******************* instructor's view assignment ***************************** */ private static final String VIEW_ASSIGNMENT_ID = "view_assignment_id"; /** ******************* instructor's edit assignment ***************************** */ private static final String EDIT_ASSIGNMENT_ID = "edit_assignment_id"; /** ******************* instructor's delete assignment ids ***************************** */ private static final String DELETE_ASSIGNMENT_IDS = "delete_assignment_ids"; /** ******************* flags controls the grade assignment page layout ******************* */ private static final String GRADE_ASSIGNMENT_EXPAND_FLAG = "grade_assignment_expand_flag"; private static final String GRADE_SUBMISSION_EXPAND_FLAG = "grade_submission_expand_flag"; private static final String GRADE_NO_SUBMISSION_DEFAULT_GRADE = "grade_no_submission_default_grade"; /** ******************* instructor's grade submission ***************************** */ private static final String GRADE_SUBMISSION_ASSIGNMENT_ID = "grade_submission_assignment_id"; private static final String GRADE_SUBMISSION_SUBMISSION_ID = "grade_submission_submission_id"; private static final String GRADE_SUBMISSION_FEEDBACK_COMMENT = "grade_submission_feedback_comment"; private static final String GRADE_SUBMISSION_FEEDBACK_TEXT = "grade_submission_feedback_text"; private static final String GRADE_SUBMISSION_FEEDBACK_ATTACHMENT = "grade_submission_feedback_attachment"; private static final String GRADE_SUBMISSION_GRADE = "grade_submission_grade"; private static final String GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG = "grade_submission_assignment_expand_flag"; private static final String GRADE_SUBMISSION_ALLOW_RESUBMIT = "grade_submission_allow_resubmit"; /** ******************* instructor's export assignment ***************************** */ private static final String EXPORT_ASSIGNMENT_REF = "export_assignment_ref"; private static final String EXPORT_ASSIGNMENT_ID = "export_assignment_id"; /** ****************** instructor's new assignment ****************************** */ private static final String NEW_ASSIGNMENT_TITLE = "new_assignment_title"; // open date private static final String NEW_ASSIGNMENT_OPENMONTH = "new_assignment_openmonth"; private static final String NEW_ASSIGNMENT_OPENDAY = "new_assignment_openday"; private static final String NEW_ASSIGNMENT_OPENYEAR = "new_assignment_openyear"; private static final String NEW_ASSIGNMENT_OPENHOUR = "new_assignment_openhour"; private static final String NEW_ASSIGNMENT_OPENMIN = "new_assignment_openmin"; private static final String NEW_ASSIGNMENT_OPENAMPM = "new_assignment_openampm"; // due date private static final String NEW_ASSIGNMENT_DUEMONTH = "new_assignment_duemonth"; private static final String NEW_ASSIGNMENT_DUEDAY = "new_assignment_dueday"; private static final String NEW_ASSIGNMENT_DUEYEAR = "new_assignment_dueyear"; private static final String NEW_ASSIGNMENT_DUEHOUR = "new_assignment_duehour"; private static final String NEW_ASSIGNMENT_DUEMIN = "new_assignment_duemin"; private static final String NEW_ASSIGNMENT_DUEAMPM = "new_assignment_dueampm"; // close date private static final String NEW_ASSIGNMENT_ENABLECLOSEDATE = "new_assignment_enableclosedate"; private static final String NEW_ASSIGNMENT_CLOSEMONTH = "new_assignment_closemonth"; private static final String NEW_ASSIGNMENT_CLOSEDAY = "new_assignment_closeday"; private static final String NEW_ASSIGNMENT_CLOSEYEAR = "new_assignment_closeyear"; private static final String NEW_ASSIGNMENT_CLOSEHOUR = "new_assignment_closehour"; private static final String NEW_ASSIGNMENT_CLOSEMIN = "new_assignment_closemin"; private static final String NEW_ASSIGNMENT_CLOSEAMPM = "new_assignment_closeampm"; private static final String NEW_ASSIGNMENT_ATTACHMENT = "new_assignment_attachment"; private static final String NEW_ASSIGNMENT_SECTION = "new_assignment_section"; private static final String NEW_ASSIGNMENT_SUBMISSION_TYPE = "new_assignment_submission_type"; private static final String NEW_ASSIGNMENT_GRADE_TYPE = "new_assignment_grade_type"; private static final String NEW_ASSIGNMENT_GRADE_POINTS = "new_assignment_grade_points"; private static final String NEW_ASSIGNMENT_DESCRIPTION = "new_assignment_instructions"; private static final String NEW_ASSIGNMENT_DUE_DATE_SCHEDULED = "new_assignment_due_date_scheduled"; private static final String NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED = "new_assignment_open_date_announced"; private static final String NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE = "new_assignment_check_add_honor_pledge"; private static final String NEW_ASSIGNMENT_HIDE_OPTION_FLAG = "new_assignment_hide_option_flag"; private static final String NEW_ASSIGNMENT_FOCUS = "new_assignment_focus"; private static final String NEW_ASSIGNMENT_DESCRIPTION_EMPTY = "new_assignment_description_empty"; private static final String NEW_ASSIGNMENT_RANGE = "new_assignment_range"; private static final String NEW_ASSIGNMENT_GROUPS = "new_assignment_groups"; /**************************** assignment year range *************************/ private static final String NEW_ASSIGNMENT_YEAR_RANGE_FROM = "new_assignment_year_range_from"; private static final String NEW_ASSIGNMENT_YEAR_RANGE_TO = "new_assignment_year_range_to"; // submission level of resubmit due time private static final String ALLOW_RESUBMIT_CLOSEMONTH = "allow_resubmit_closeMonth"; private static final String ALLOW_RESUBMIT_CLOSEDAY = "allow_resubmit_closeDay"; private static final String ALLOW_RESUBMIT_CLOSEYEAR = "allow_resubmit_closeYear"; private static final String ALLOW_RESUBMIT_CLOSEHOUR = "allow_resubmit_closeHour"; private static final String ALLOW_RESUBMIT_CLOSEMIN = "allow_resubmit_closeMin"; private static final String ALLOW_RESUBMIT_CLOSEAMPM = "allow_resubmit_closeAMPM"; private static final String ATTACHMENTS_MODIFIED = "attachments_modified"; /** **************************** instructor's view student submission ***************** */ // the show/hide table based on member id private static final String STUDENT_LIST_SHOW_TABLE = "STUDENT_LIST_SHOW_TABLE"; /** **************************** student view grade submission id *********** */ private static final String VIEW_GRADE_SUBMISSION_ID = "view_grade_submission_id"; // alert for grade exceeds max grade setting private static final String GRADE_GREATER_THAN_MAX_ALERT = "grade_greater_than_max_alert"; /** **************************** modes *************************** */ /** The list view of assignments */ private static final String MODE_LIST_ASSIGNMENTS = "lisofass1"; // set in velocity template /** The student view of an assignment submission */ private static final String MODE_STUDENT_VIEW_SUBMISSION = "Assignment.mode_view_submission"; /** The student view of an assignment submission confirmation */ private static final String MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "Assignment.mode_view_submission_confirmation"; /** The student preview of an assignment submission */ private static final String MODE_STUDENT_PREVIEW_SUBMISSION = "Assignment.mode_student_preview_submission"; /** The student view of graded submission */ private static final String MODE_STUDENT_VIEW_GRADE = "Assignment.mode_student_view_grade"; /** The student view of assignments */ private static final String MODE_STUDENT_VIEW_ASSIGNMENT = "Assignment.mode_student_view_assignment"; /** The instructor view of creating a new assignment or editing an existing one */ private static final String MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "Assignment.mode_instructor_new_edit_assignment"; /** The instructor view to delete an assignment */ private static final String MODE_INSTRUCTOR_DELETE_ASSIGNMENT = "Assignment.mode_instructor_delete_assignment"; /** The instructor view to grade an assignment */ private static final String MODE_INSTRUCTOR_GRADE_ASSIGNMENT = "Assignment.mode_instructor_grade_assignment"; /** The instructor view to grade a submission */ private static final String MODE_INSTRUCTOR_GRADE_SUBMISSION = "Assignment.mode_instructor_grade_submission"; /** The instructor view of preview grading a submission */ private static final String MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "Assignment.mode_instructor_preview_grade_submission"; /** The instructor preview of one assignment */ private static final String MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "Assignment.mode_instructor_preview_assignments"; /** The instructor view of one assignment */ private static final String MODE_INSTRUCTOR_VIEW_ASSIGNMENT = "Assignment.mode_instructor_view_assignments"; /** The instructor view to list students of an assignment */ private static final String MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "lisofass2"; // set in velocity template /** The instructor view of assignment submission report */ private static final String MODE_INSTRUCTOR_REPORT_SUBMISSIONS = "grarep"; // set in velocity template /** The instructor view of uploading all from archive file */ private static final String MODE_INSTRUCTOR_UPLOAD_ALL = "uploadAll"; /** The student view of assignment submission report */ private static final String MODE_STUDENT_VIEW = "stuvie"; // set in velocity template /** ************************* vm names ************************** */ /** The list view of assignments */ private static final String TEMPLATE_LIST_ASSIGNMENTS = "_list_assignments"; /** The student view of assignment */ private static final String TEMPLATE_STUDENT_VIEW_ASSIGNMENT = "_student_view_assignment"; /** The student view of showing an assignment submission */ private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION = "_student_view_submission"; /** The student view of an assignment submission confirmation */ private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "_student_view_submission_confirmation"; /** The student preview an assignment submission */ private static final String TEMPLATE_STUDENT_PREVIEW_SUBMISSION = "_student_preview_submission"; /** The student view of graded submission */ private static final String TEMPLATE_STUDENT_VIEW_GRADE = "_student_view_grade"; /** The instructor view to create a new assignment or edit an existing one */ private static final String TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "_instructor_new_edit_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT = "_instructor_delete_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION = "_instructor_grading_submission"; /** The instructor preview to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "_instructor_preview_grading_submission"; /** The instructor view to grade the assignment */ private static final String TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT = "_instructor_list_submissions"; /** The instructor preview of assignment */ private static final String TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "_instructor_preview_assignment"; /** The instructor view of assignment */ private static final String TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT = "_instructor_view_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "_instructor_student_list_submissions"; /** The instructor view to assignment submission report */ private static final String TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS = "_instructor_report_submissions"; /** The instructor view to upload all information from archive file */ private static final String TEMPLATE_INSTRUCTOR_UPLOAD_ALL = "_instructor_uploadAll"; /** The opening mark comment */ private static final String COMMENT_OPEN = "{{"; /** The closing mark for comment */ private static final String COMMENT_CLOSE = "}}"; /** The selected view */ private static final String STATE_SELECTED_VIEW = "state_selected_view"; /** The configuration choice of with grading option or not */ private static final String WITH_GRADES = "with_grades"; /** The alert flag when doing global navigation from improper mode */ private static final String ALERT_GLOBAL_NAVIGATION = "alert_global_navigation"; /** The total list item before paging */ private static final String STATE_PAGEING_TOTAL_ITEMS = "state_paging_total_items"; /** is current user allowed to grade assignment? */ private static final String STATE_ALLOW_GRADE_SUBMISSION = "state_allow_grade_submission"; /** property for previous feedback attachments **/ private static final String PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS = "prop_submission_previous_feedback_attachments"; /** the user and submission list for list of submissions page */ private static final String USER_SUBMISSIONS = "user_submissions"; /** ************************* Taggable constants ************************** */ /** identifier of tagging provider that will provide the appropriate helper */ private static final String PROVIDER_ID = "providerId"; /** Reference to an activity */ private static final String ACTIVITY_REF = "activityRef"; /** Reference to an item */ private static final String ITEM_REF = "itemRef"; /** session attribute for list of decorated tagging providers */ private static final String PROVIDER_LIST = "providerList"; // whether the choice of emails instructor submission notification is available in the installation private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS = "assignment.instructor.notifications"; // default for whether or how the instructor receive submission notification emails, none(default)|each|digest private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT = "assignment.instructor.notifications.default"; /****************************** Upload all screen ***************************/ private static final String UPLOAD_ALL_HAS_SUBMISSIONS = "upload_all_has_submissions"; private static final String UPLOAD_ALL_HAS_GRADEFILE = "upload_all_has_gradefile"; private static final String UPLOAD_ALL_HAS_COMMENTS= "upload_all_has_comments"; private static final String UPLOAD_ALL_RELEASE_GRADES = "upload_all_release_grades"; /** * central place for dispatching the build routines based on the state name */ public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String template = null; context.put("tlang", rb); context.put("cheffeedbackhelper", this); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // allow add assignment? boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString); context.put("allowAddAssignment", Boolean.valueOf(allowAddAssignment)); Object allowGradeSubmission = state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION); // allow update site? context.put("allowUpdateSite", Boolean .valueOf(SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING)))); //Is the review service allowed? context.put("allowReviewService", allowReviewService); // grading option context.put("withGrade", state.getAttribute(WITH_GRADES)); String mode = (String) state.getAttribute(STATE_MODE); if (!mode.equals(MODE_LIST_ASSIGNMENTS)) { // allow grade assignment? if (state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION) == null) { state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, Boolean.FALSE); } context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION)); } if (mode.equals(MODE_LIST_ASSIGNMENTS)) { // build the context for the student assignment view template = build_list_assignments_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_ASSIGNMENT)) { // the student view of assignment template = build_student_view_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for showing one assignment submission template = build_student_view_submission_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION)) { // build the context for showing one assignment submission confirmation template = build_student_view_submission_confirmation_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_PREVIEW_SUBMISSION)) { // build the context for showing one assignment submission template = build_student_preview_submission_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_GRADE)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for showing one graded submission template = build_student_view_grade_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT)) { // allow add assignment? boolean allowAddSiteAssignment = AssignmentService.allowAddSiteAssignment(contextString); context.put("allowAddSiteAssignment", Boolean.valueOf(allowAddSiteAssignment)); // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's create new assignment view template = build_instructor_new_edit_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_DELETE_ASSIGNMENT)) { if (state.getAttribute(DELETE_ASSIGNMENT_IDS) != null) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's delete assignment template = build_instructor_delete_assignment_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_GRADE_ASSIGNMENT)) { if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's grade assignment template = build_instructor_grade_assignment_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION)) { if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's grade submission template = build_instructor_grade_submission_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's preview grade submission template = build_instructor_preview_grade_submission_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT)) { // build the context for preview one assignment template = build_instructor_preview_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_VIEW_ASSIGNMENT)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for view one assignment template = build_instructor_view_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's create new assignment view template = build_instructor_view_students_assignment_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_REPORT_SUBMISSIONS)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's view of report submissions template = build_instructor_report_submissions(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_UPLOAD_ALL)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's view of uploading all info from archive file template = build_instructor_upload_all(portlet, context, data, state); } } if (template == null) { // default to student list view state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); template = build_list_assignments_context(portlet, context, data, state); } return template; } // buildNormalContext /** * build the student view of showing an assignment submission */ protected String build_student_view_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("context", contextString); User user = (User) state.getAttribute(STATE_USER); String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment assignment = null; try { assignment = AssignmentService.getAssignment(currentAssignmentReference); context.put("assignment", assignment); context.put("canSubmit", Boolean.valueOf(AssignmentService.canSubmit(contextString, assignment))); if (assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { context.put("nonElectronicType", Boolean.TRUE); } AssignmentSubmission s = AssignmentService.getSubmission(assignment.getReference(), user); if (s != null) { context.put("submission", s); ResourceProperties p = s.getProperties(); if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null) { context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)); } if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null) { context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)); } if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null) { context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p)); } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannot_find_assignment")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot16")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } // name value pairs for the vm context.put("name_submission_text", VIEW_SUBMISSION_TEXT); context.put("value_submission_text", state.getAttribute(VIEW_SUBMISSION_TEXT)); context.put("name_submission_honor_pledge_yes", VIEW_SUBMISSION_HONOR_PLEDGE_YES); context.put("value_submission_honor_pledge_yes", state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES)); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("currentTime", TimeService.newTime()); boolean allowSubmit = AssignmentService.allowAddSubmission((String) state.getAttribute(STATE_CONTEXT_STRING)); if (!allowSubmit) { addAlert(state, rb.getString("not_allowed_to_submit")); } context.put("allowSubmit", new Boolean(allowSubmit)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_SUBMISSION; } // build_student_view_submission_context /** * build the student view of showing an assignment submission confirmation */ protected String build_student_view_submission_confirmation_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("context", contextString); // get user information User user = (User) state.getAttribute(STATE_USER); context.put("user_name", user.getDisplayName()); context.put("user_id", user.getDisplayId()); // get site information try { // get current site Site site = SiteService.getSite(contextString); context.put("site_title", site.getTitle()); } catch (Exception ignore) { Log.warn("chef", this + ignore.getMessage() + " siteId= " + contextString); } // get assignment and submission information String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); try { Assignment currentAssignment = AssignmentService.getAssignment(currentAssignmentReference); context.put("assignment_title", currentAssignment.getTitle()); AssignmentSubmission s = AssignmentService.getSubmission(currentAssignment.getReference(), user); if (s != null) { context.put("submission_id", s.getId()); context.put("submit_time", s.getTimeSubmitted().toStringLocalFull()); List attachments = s.getSubmittedAttachments(); if (attachments != null && attachments.size()>0) { context.put("submit_attachments", s.getSubmittedAttachments()); } context.put("submit_text", StringUtil.trimToNull(s.getSubmittedText())); context.put("email_confirmation", Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.submission.confirmation.email", true))); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannot_find_assignment")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot16")); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION; } // build_student_view_submission_confirmation_context /** * build the student view of assignment */ protected String build_student_view_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("context", state.getAttribute(STATE_CONTEXT_STRING)); String aId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); Assignment assignment = null; try { assignment = AssignmentService.getAssignment(aId); context.put("assignment", assignment); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannot_find_assignment")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("gradeTypeTable", gradeTypeTable()); context.put("userDirectoryService", UserDirectoryService.getInstance()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_ASSIGNMENT; } // build_student_view_submission_context /** * build the student preview of showing an assignment submission */ protected String build_student_preview_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { User user = (User) state.getAttribute(STATE_USER); String aReference = (String) state.getAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE); try { context.put("assignment", AssignmentService.getAssignment(aReference)); context.put("submission", AssignmentService.getSubmission(aReference, user)); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot16")); } context.put("text", state.getAttribute(PREVIEW_SUBMISSION_TEXT)); context.put("honor_pledge_yes", state.getAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES)); context.put("attachments", state.getAttribute(PREVIEW_SUBMISSION_ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_PREVIEW_SUBMISSION; } // build_student_preview_submission_context /** * build the student view of showing a graded submission */ protected String build_student_view_grade_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); AssignmentSubmission submission = null; try { submission = AssignmentService.getSubmission((String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID)); context.put("assignment", submission.getAssignment()); context.put("submission", submission); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_get_submission")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && submission != null) { AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); List<DecoratedTaggingProvider> providers = addProviders(context, state); List<TaggingHelperInfo> itemHelpers = new ArrayList<TaggingHelperInfo>(); for (DecoratedTaggingProvider provider : providers) { TaggingHelperInfo helper = provider.getProvider() .getItemHelperInfo( assignmentActivityProducer.getItem( submission, UserDirectoryService.getCurrentUser() .getId()).getReference()); if (helper != null) { itemHelpers.add(helper); } } addItem(context, submission, UserDirectoryService.getCurrentUser().getId()); addActivity(context, submission.getAssignment()); context.put("itemHelpers", itemHelpers); context.put("taggable", Boolean.valueOf(true)); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_GRADE; } // build_student_view_grade_context /** * build the view of assignments list */ protected String build_list_assignments_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable()) { context.put("producer", ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer")); context.put("providers", taggingManager.getProviders()); context.put("taggable", Boolean.valueOf(true)); } String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("contextString", contextString); context.put("user", state.getAttribute(STATE_USER)); context.put("service", AssignmentService.getInstance()); context.put("TimeService", TimeService.getInstance()); context.put("LongObject", new Long(TimeService.newTime().getTime())); context.put("currentTime", TimeService.newTime()); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); // clean sort criteria if (sortedBy.equals(SORTED_BY_GROUP_TITLE) || sortedBy.equals(SORTED_BY_GROUP_DESCRIPTION)) { sortedBy = SORTED_BY_DUEDATE; sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_BY, sortedBy); state.setAttribute(SORTED_ASC, sortedAsc); } context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); if (state.getAttribute(STATE_SELECTED_VIEW) != null) { context.put("view", state.getAttribute(STATE_SELECTED_VIEW)); } GradebookService g = null; String gradebookUid = null; boolean gradebookDefined = AssignmentService.isGradebookDefined(); if (gradebookDefined) { g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); } List assignments = prepPage(state); // make sure for all non-electronic submission type of assignment, the submission number matches the number of site members for (int i = 0; i < assignments.size(); i++) { Assignment a = (Assignment) assignments.get(i); if (a.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { List allowAddSubmissionUsers = AssignmentService.allowAddSubmissionUsers(a.getReference()); List submissions = AssignmentService.getSubmissions(a); if (submissions != null && allowAddSubmissionUsers != null && allowAddSubmissionUsers.size() != submissions.size()) { // if there is any newly added user who doesn't have a submission object yet, add the submission try { addSubmissionsForNonElectronicAssignment(state, AssignmentService.editAssignment(a.getReference())); } catch (Exception e) { Log.warn("chef", this + e.getMessage()); } } } // update externally maintained assignment entry in Gradebook if (gradebookDefined) { updateExternalAssignmentInGB(a, g, gradebookUid); } } context.put("assignments", assignments.iterator()); // allow get assignment context.put("allowGetAssignment", Boolean.valueOf(AssignmentService.allowGetAssignment(contextString))); // test whether user user can grade at least one assignment // and update the state variable. boolean allowGradeSubmission = false; for (Iterator aIterator=assignments.iterator(); !allowGradeSubmission && aIterator.hasNext(); ) { if (AssignmentService.allowGradeSubmission(((Assignment) aIterator.next()).getReference())) { allowGradeSubmission = true; } } state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, new Boolean(allowGradeSubmission)); context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION)); // allow remove assignment? boolean allowRemoveAssignment = false; for (Iterator aIterator=assignments.iterator(); !allowRemoveAssignment && aIterator.hasNext(); ) { if (AssignmentService.allowRemoveAssignment(((Assignment) aIterator.next()).getReference())) { allowRemoveAssignment = true; } } context.put("allowRemoveAssignment", Boolean.valueOf(allowRemoveAssignment)); add2ndToolbarFields(data, context); // inform the observing courier that we just updated the page... // if there are pending requests to do so they can be cleared justDelivered(state); pagingInfoToContext(state, context); // put site object into context try { // get current site Site site = SiteService.getSite(contextString); context.put("site", site); // any group in the site? Collection groups = site.getGroups(); context.put("groups", (groups != null && groups.size()>0)?Boolean.TRUE:Boolean.FALSE); // add active user list AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(contextString)); if (realm != null) { context.put("activeUserIds", realm.getUsers()); } } catch (Exception ignore) { Log.warn("chef", this + ignore.getMessage() + " siteId= " + contextString); } boolean allowSubmit = AssignmentService.allowAddSubmission(contextString); context.put("allowSubmit", new Boolean(allowSubmit)); // related to resubmit settings context.put("allowResubmitNumberProp", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); context.put("allowResubmitCloseTimeProp", AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); // the type int for non-electronic submission context.put("typeNonElectronic", Integer.valueOf(Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_LIST_ASSIGNMENTS; } // build_list_assignments_context /** * build the instructor view of creating a new assignment or editing an existing one */ protected String build_instructor_new_edit_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { // is the assignment an new assignment String assignmentId = (String) state.getAttribute(EDIT_ASSIGNMENT_ID); if (assignmentId != null) { try { Assignment a = AssignmentService.getAssignment(assignmentId); context.put("assignment", a); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3") + ": " + assignmentId); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14") + ": " + assignmentId); } } // set up context variables setAssignmentFormContext(state, context); context.put("fField", state.getAttribute(NEW_ASSIGNMENT_FOCUS)); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT; } // build_instructor_new_assignment_context protected void setAssignmentFormContext(SessionState state, Context context) { // put the names and values into vm file context.put("name_UseReviewService", NEW_ASSIGNMENT_USE_REVIEW_SERVICE); context.put("name_AllowStudentView", NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW); context.put("name_title", NEW_ASSIGNMENT_TITLE); context.put("name_OpenMonth", NEW_ASSIGNMENT_OPENMONTH); context.put("name_OpenDay", NEW_ASSIGNMENT_OPENDAY); context.put("name_OpenYear", NEW_ASSIGNMENT_OPENYEAR); context.put("name_OpenHour", NEW_ASSIGNMENT_OPENHOUR); context.put("name_OpenMin", NEW_ASSIGNMENT_OPENMIN); context.put("name_OpenAMPM", NEW_ASSIGNMENT_OPENAMPM); context.put("name_DueMonth", NEW_ASSIGNMENT_DUEMONTH); context.put("name_DueDay", NEW_ASSIGNMENT_DUEDAY); context.put("name_DueYear", NEW_ASSIGNMENT_DUEYEAR); context.put("name_DueHour", NEW_ASSIGNMENT_DUEHOUR); context.put("name_DueMin", NEW_ASSIGNMENT_DUEMIN); context.put("name_DueAMPM", NEW_ASSIGNMENT_DUEAMPM); context.put("name_EnableCloseDate", NEW_ASSIGNMENT_ENABLECLOSEDATE); context.put("name_CloseMonth", NEW_ASSIGNMENT_CLOSEMONTH); context.put("name_CloseDay", NEW_ASSIGNMENT_CLOSEDAY); context.put("name_CloseYear", NEW_ASSIGNMENT_CLOSEYEAR); context.put("name_CloseHour", NEW_ASSIGNMENT_CLOSEHOUR); context.put("name_CloseMin", NEW_ASSIGNMENT_CLOSEMIN); context.put("name_CloseAMPM", NEW_ASSIGNMENT_CLOSEAMPM); context.put("name_Section", NEW_ASSIGNMENT_SECTION); context.put("name_SubmissionType", NEW_ASSIGNMENT_SUBMISSION_TYPE); context.put("name_GradeType", NEW_ASSIGNMENT_GRADE_TYPE); context.put("name_GradePoints", NEW_ASSIGNMENT_GRADE_POINTS); context.put("name_Description", NEW_ASSIGNMENT_DESCRIPTION); // do not show the choice when there is no Schedule tool yet if (state.getAttribute(CALENDAR) != null) context.put("name_CheckAddDueDate", ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); //don't show the choice when there is no Announcement tool yet if (state.getAttribute(ANNOUNCEMENT_CHANNEL) != null) context.put("name_CheckAutoAnnounce", ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE); context.put("name_CheckAddHonorPledge", NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); // number of resubmissions allowed context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // set the values context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM)); context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO)); context.put("value_title", state.getAttribute(NEW_ASSIGNMENT_TITLE)); context.put("value_OpenMonth", state.getAttribute(NEW_ASSIGNMENT_OPENMONTH)); context.put("value_OpenDay", state.getAttribute(NEW_ASSIGNMENT_OPENDAY)); context.put("value_OpenYear", state.getAttribute(NEW_ASSIGNMENT_OPENYEAR)); context.put("value_OpenHour", state.getAttribute(NEW_ASSIGNMENT_OPENHOUR)); context.put("value_OpenMin", state.getAttribute(NEW_ASSIGNMENT_OPENMIN)); context.put("value_OpenAMPM", state.getAttribute(NEW_ASSIGNMENT_OPENAMPM)); context.put("value_DueMonth", state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)); context.put("value_DueDay", state.getAttribute(NEW_ASSIGNMENT_DUEDAY)); context.put("value_DueYear", state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)); context.put("value_DueHour", state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)); context.put("value_DueMin", state.getAttribute(NEW_ASSIGNMENT_DUEMIN)); context.put("value_DueAMPM", state.getAttribute(NEW_ASSIGNMENT_DUEAMPM)); context.put("value_EnableCloseDate", state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)); context.put("value_CloseMonth", state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH)); context.put("value_CloseDay", state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY)); context.put("value_CloseYear", state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR)); context.put("value_CloseHour", state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR)); context.put("value_CloseMin", state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN)); context.put("value_CloseAMPM", state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM)); context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION)); context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)); context.put("value_totalSubmissionTypes", new Integer(Assignment.SUBMISSION_TYPES.length)); context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)); // format to show one decimal place String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); context.put("value_GradePoints", displayGrade(state, maxGrade)); context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION)); // Keep the use review service setting context.put("value_UseReviewService", state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE)); context.put("value_AllowStudentView", state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW)); // don't show the choice when there is no Schedule tool yet if (state.getAttribute(CALENDAR) != null) context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); // don't show the choice when there is no Announcement tool yet if (state.getAttribute(ANNOUNCEMENT_CHANNEL) != null) context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); String s = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); if (s == null) s = "1"; context.put("value_CheckAddHonorPledge", s); // number of resubmissions allowed if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { context.put("value_allowResubmitNumber", Integer.valueOf((String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER))); } else { // defaults to 0 context.put("value_allowResubmitNumber", Integer.valueOf(0)); } // get all available assignments from Gradebook tool except for those created from boolean gradebookExists = AssignmentService.isGradebookDefined(); if (gradebookExists) { GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); try { // get all assignments in Gradebook List gradebookAssignments = g.getAssignments(gradebookUid); List gradebookAssignmentsExceptSamigo = new Vector(); // filtering out those from Samigo for (Iterator i=gradebookAssignments.iterator(); i.hasNext();) { org.sakaiproject.service.gradebook.shared.Assignment gAssignment = (org.sakaiproject.service.gradebook.shared.Assignment) i.next(); if (!gAssignment.isExternallyMaintained() || gAssignment.isExternallyMaintained() && gAssignment.getExternalAppName().equals(getToolTitle())) { gradebookAssignmentsExceptSamigo.add(gAssignment); } } context.put("gradebookAssignments", gradebookAssignmentsExceptSamigo); if (StringUtil.trimToNull((String) state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null) { state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO); } context.put("withGradebook", Boolean.TRUE); // offer the gradebook integration choice only in the Assignments with Grading tool boolean withGrade = ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue(); if (withGrade) { context.put("name_Addtogradebook", AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); context.put("name_AssociateGradebookAssignment", AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); } context.put("gradebookChoice", state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); context.put("gradebookChoice_no", AssignmentService.GRADEBOOK_INTEGRATION_NO); context.put("gradebookChoice_add", AssignmentService.GRADEBOOK_INTEGRATION_ADD); context.put("gradebookChoice_associate", AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE); context.put("associateGradebookAssignment", state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); } catch (Exception e) { // not able to link to Gradebook Log.warn("chef", this + e.getMessage()); } } context.put("monthTable", monthTable()); context.put("gradeTypeTable", gradeTypeTable()); context.put("submissionTypeTable", submissionTypeTable()); context.put("hide_assignment_option_flag", state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG)); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); String range = (String) state.getAttribute(NEW_ASSIGNMENT_RANGE); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // put site object into context try { // get current site Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); context.put("site", site); } catch (Exception ignore) { } if (AssignmentService.getAllowGroupAssignments()) { Collection groupsAllowAddAssignment = AssignmentService.getGroupsAllowAddAssignment(contextString); if (AssignmentService.allowAddSiteAssignment(contextString)) { // default to make site selection context.put("range", "site"); } else if (groupsAllowAddAssignment.size() > 0) { // to group otherwise context.put("range", "groups"); } // group list which user can add message to if (groupsAllowAddAssignment.size() > 0) { String sort = (String) state.getAttribute(SORTED_BY); String asc = (String) state.getAttribute(SORTED_ASC); if (sort == null || (!sort.equals(SORTED_BY_GROUP_TITLE) && !sort.equals(SORTED_BY_GROUP_DESCRIPTION))) { sort = SORTED_BY_GROUP_TITLE; asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_BY, sort); state.setAttribute(SORTED_ASC, asc); } context.put("groups", new SortedIterator(groupsAllowAddAssignment.iterator(), new AssignmentComparator(state, sort, asc))); context.put("assignmentGroups", state.getAttribute(NEW_ASSIGNMENT_GROUPS)); } } context.put("allowGroupAssignmentsInGradebook", new Boolean(AssignmentService.getAllowGroupAssignmentsInGradebook())); // the notification email choices if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS) != null && ((Boolean) state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS)).booleanValue()) { context.put("name_assignment_instructor_notifications", ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS); if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) == null) { // set the notification value using site default state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT)); } context.put("value_assignment_instructor_notifications", state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); // the option values context.put("value_assignment_instructor_notifications_none", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE); context.put("value_assignment_instructor_notifications_each", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_EACH); context.put("value_assignment_instructor_notifications_digest", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DIGEST); } } // setAssignmentFormContext /** * build the instructor view of create a new assignment */ protected String build_instructor_preview_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("time", TimeService.newTime()); context.put("user", UserDirectoryService.getCurrentUser()); context.put("value_Title", (String) state.getAttribute(NEW_ASSIGNMENT_TITLE)); Time openTime = getOpenTime(state); context.put("value_OpenDate", openTime); // due time int dueMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)).intValue(); int dueDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEDAY)).intValue(); int dueYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)).intValue(); int dueHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)).intValue(); int dueMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMIN)).intValue(); String dueAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_DUEAMPM); if ((dueAMPM.equals("PM")) && (dueHour != 12)) { dueHour = dueHour + 12; } if ((dueHour == 12) && (dueAMPM.equals("AM"))) { dueHour = 0; } Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0); context.put("value_DueDate", dueTime); // close time Time closeTime = TimeService.newTime(); Boolean enableCloseDate = (Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE); context.put("value_EnableCloseDate", enableCloseDate); if ((enableCloseDate).booleanValue()) { int closeMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH)).intValue(); int closeDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY)).intValue(); int closeYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR)).intValue(); int closeHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR)).intValue(); int closeMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN)).intValue(); String closeAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); context.put("value_CloseDate", closeTime); } context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION)); context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)); context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)); String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); context.put("value_GradePoints", displayGrade(state, maxGrade)); context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION)); context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); context.put("value_CheckAddHonorPledge", state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE)); // get all available assignments from Gradebook tool except for those created from if (AssignmentService.isGradebookDefined()) { context.put("gradebookChoice", state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); context.put("associateGradebookAssignment", state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); } context.put("monthTable", monthTable()); context.put("gradeTypeTable", gradeTypeTable()); context.put("submissionTypeTable", submissionTypeTable()); context.put("hide_assignment_option_flag", state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG)); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("preview_assignment_assignment_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG)); context.put("preview_assignment_student_view_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG)); context.put("value_assignment_id", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID)); context.put("value_assignmentcontent_id", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID)); context.put("currentTime", TimeService.newTime()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT; } // build_instructor_preview_assignment_context /** * build the instructor view to delete an assignment */ protected String build_instructor_delete_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { Vector assignments = new Vector(); Vector assignmentIds = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < assignmentIds.size(); i++) { try { Assignment a = AssignmentService.getAssignment((String) assignmentIds.get(i)); Iterator submissions = AssignmentService.getSubmissions(a).iterator(); if (submissions.hasNext()) { // if there is submission to the assignment, show the alert addAlert(state, rb.getString("areyousur") + " \"" + a.getTitle() + "\" " + rb.getString("whihassub") + "\n"); } assignments.add(a); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } context.put("assignments", assignments); context.put("service", AssignmentService.getInstance()); context.put("currentTime", TimeService.newTime()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT; } // build_instructor_delete_assignment_context /** * build the instructor view to grade an submission */ protected String build_instructor_grade_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { int gradeType = -1; // assignment Assignment a = null; try { a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); context.put("assignment", a); gradeType = a.getContent().getTypeOfGrade(); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } // assignment submission try { AssignmentSubmission s = AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID)); if (s != null) { context.put("submission", s); ResourceProperties p = s.getProperties(); if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null) { context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)); } if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null) { context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)); } if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null) { context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p)); } // get the submission level of close date setting context.put("name_CloseMonth", ALLOW_RESUBMIT_CLOSEMONTH); context.put("name_CloseDay", ALLOW_RESUBMIT_CLOSEDAY); context.put("name_CloseYear", ALLOW_RESUBMIT_CLOSEYEAR); context.put("name_CloseHour", ALLOW_RESUBMIT_CLOSEHOUR); context.put("name_CloseMin", ALLOW_RESUBMIT_CLOSEMIN); context.put("name_CloseAMPM", ALLOW_RESUBMIT_CLOSEAMPM); String closeTimeString =(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); Time time = null; if (closeTimeString != null) { // if there is a local setting time = TimeService.newTime(Long.parseLong(closeTimeString)); } else if (a != null) { // if there is no local setting, default to assignment close time time = a.getCloseTime(); } TimeBreakdown closeTime = time.breakdownLocal(); context.put("value_CloseMonth", new Integer(closeTime.getMonth())); context.put("value_CloseDay", new Integer(closeTime.getDay())); context.put("value_CloseYear", new Integer(closeTime.getYear())); int closeHour = closeTime.getHour(); if (closeHour >= 12) { context.put("value_CloseAMPM", "PM"); } else { context.put("value_CloseAMPM", "AM"); } if (closeHour == 0) { // for midnight point, we mark it as 12AM closeHour = 12; } context.put("value_CloseHour", new Integer((closeHour > 12) ? closeHour - 12 : closeHour)); context.put("value_CloseMin", new Integer(closeTime.getMin())); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } context.put("user", state.getAttribute(STATE_USER)); context.put("submissionTypeTable", submissionTypeTable()); context.put("gradeTypeTable", gradeTypeTable()); context.put("instructorAttachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); // names context.put("name_grade_assignment_id", GRADE_SUBMISSION_ASSIGNMENT_ID); context.put("name_feedback_comment", GRADE_SUBMISSION_FEEDBACK_COMMENT); context.put("name_feedback_text", GRADE_SUBMISSION_FEEDBACK_TEXT); context.put("name_feedback_attachment", GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); context.put("name_grade", GRADE_SUBMISSION_GRADE); context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // values context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM)); context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO)); context.put("value_grade_assignment_id", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); context.put("value_feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); context.put("value_feedback_text", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT)); context.put("value_feedback_attachment", state.getAttribute(ATTACHMENTS)); if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { context.put("value_allowResubmitNumber", Integer.valueOf((String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER))); } // format to show one decimal place in grade context.put("value_grade", (gradeType == 3) ? displayGrade(state, (String) state.getAttribute(GRADE_SUBMISSION_GRADE)) : state.getAttribute(GRADE_SUBMISSION_GRADE)); context.put("assignment_expand_flag", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG)); context.put("gradingAttachments", state.getAttribute(ATTACHMENTS)); // is this a non-electronic submission type of assignment context.put("nonElectronic", (a!=null && a.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)?Boolean.TRUE:Boolean.FALSE); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION; } // build_instructor_grade_submission_context private List getPrevFeedbackAttachments(ResourceProperties p) { String attachmentsString = p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS); String[] attachmentsReferences = attachmentsString.split(","); List prevFeedbackAttachments = EntityManager.newReferenceList(); for (int k =0; k < attachmentsReferences.length; k++) { prevFeedbackAttachments.add(EntityManager.newReference(attachmentsReferences[k])); } return prevFeedbackAttachments; } /** * build the instructor preview of grading submission */ protected String build_instructor_preview_grade_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { // assignment int gradeType = -1; try { Assignment a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); context.put("assignment", a); gradeType = a.getContent().getTypeOfGrade(); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } // submission try { context.put("submission", AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID))); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } User user = (User) state.getAttribute(STATE_USER); context.put("user", user); context.put("submissionTypeTable", submissionTypeTable()); context.put("gradeTypeTable", gradeTypeTable()); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); // filter the feedback text for the instructor comment and mark it as red String feedbackText = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT); context.put("feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); context.put("feedback_text", feedbackText); context.put("feedback_attachment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT)); // format to show one decimal place String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); if (gradeType == 3) { grade = displayGrade(state, grade); } context.put("grade", grade); context.put("comment_open", COMMENT_OPEN); context.put("comment_close", COMMENT_CLOSE); context.put("allowResubmitNumber", state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); String closeTimeString =(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); if (closeTimeString != null) { // close time for resubmit Time time = TimeService.newTime(Long.parseLong(closeTimeString)); context.put("allowResubmitCloseTime", time.toStringLocalFull()); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION; } // build_instructor_preview_grade_submission_context /** * build the instructor view to grade an assignment */ protected String build_instructor_grade_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("user", state.getAttribute(STATE_USER)); // sorting related fields context.put("sortedBy", state.getAttribute(SORTED_GRADE_SUBMISSION_BY)); context.put("sortedAsc", state.getAttribute(SORTED_GRADE_SUBMISSION_ASC)); context.put("sort_lastName", SORTED_GRADE_SUBMISSION_BY_LASTNAME); context.put("sort_submitTime", SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME); context.put("sort_submitStatus", SORTED_GRADE_SUBMISSION_BY_STATUS); context.put("sort_submitGrade", SORTED_GRADE_SUBMISSION_BY_GRADE); context.put("sort_submitReleased", SORTED_GRADE_SUBMISSION_BY_RELEASED); context.put("sort_submitReview", SORTED_GRADE_SUBMISSION_CONTENTREVIEW); Assignment assignment = null; try { assignment = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); context.put("assignment", assignment); state.setAttribute(EXPORT_ASSIGNMENT_ID, assignment.getId()); List userSubmissions = prepPage(state); state.setAttribute(USER_SUBMISSIONS, userSubmissions); context.put("userSubmissions", state.getAttribute(USER_SUBMISSIONS)); // ever set the default grade for no-submissions String noSubmissionDefaultGrade = assignment.getProperties().getProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE); if (noSubmissionDefaultGrade != null) { context.put("noSubmissionDefaultGrade", noSubmissionDefaultGrade); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { context.put("producer", ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer")); addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } context.put("submissionTypeTable", submissionTypeTable()); context.put("gradeTypeTable", gradeTypeTable()); context.put("attachments", state.getAttribute(ATTACHMENTS)); // Get turnitin results for instructors context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); context.put("assignment_expand_flag", state.getAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG)); context.put("submission_expand_flag", state.getAttribute(GRADE_SUBMISSION_EXPAND_FLAG)); // the user directory service context.put("userDirectoryService", UserDirectoryService.getInstance()); add2ndToolbarFields(data, context); pagingInfoToContext(state, context); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("accessPointUrl", (ServerConfigurationService.getAccessUrl()).concat(AssignmentService.submissionsZipReference( contextString, (String) state.getAttribute(EXPORT_ASSIGNMENT_REF)))); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT; } // build_instructor_grade_assignment_context /** * build the instructor view of an assignment */ protected String build_instructor_view_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("tlang", rb); Assignment assignment = null; try { assignment = AssignmentService.getAssignment((String) state.getAttribute(VIEW_ASSIGNMENT_ID)); context.put("assignment", assignment); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { List<DecoratedTaggingProvider> providers = addProviders(context, state); List<TaggingHelperInfo> activityHelpers = new ArrayList<TaggingHelperInfo>(); AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); for (DecoratedTaggingProvider provider : providers) { TaggingHelperInfo helper = provider.getProvider() .getActivityHelperInfo( assignmentActivityProducer.getActivity( assignment).getReference()); if (helper != null) { activityHelpers.add(helper); } } addActivity(context, assignment); context.put("activityHelpers", activityHelpers); context.put("taggable", Boolean.valueOf(true)); } context.put("currentTime", TimeService.newTime()); context.put("submissionTypeTable", submissionTypeTable()); context.put("gradeTypeTable", gradeTypeTable()); context.put("hideAssignmentFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG)); context.put("hideStudentViewFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); // the user directory service context.put("userDirectoryService", UserDirectoryService.getInstance()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT; } // build_instructor_view_assignment_context /** * build the instructor view to view the list of students for an assignment */ protected String build_instructor_view_students_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // get the realm and its member List studentMembers = new Vector(); String realmId = SiteService.siteReference((String) state.getAttribute(STATE_CONTEXT_STRING)); try { AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId); Set allowSubmitMembers = realm.getUsersIsAllowed(AssignmentService.SECURE_ADD_ASSIGNMENT_SUBMISSION); for (Iterator allowSubmitMembersIterator=allowSubmitMembers.iterator(); allowSubmitMembersIterator.hasNext();) { // get user try { String userId = (String) allowSubmitMembersIterator.next(); User user = UserDirectoryService.getUser(userId); studentMembers.add(user); } catch (Exception ee) { Log.warn("chef", this + ee.getMessage()); } } } catch (GroupNotDefinedException e) { Log.warn("chef", this + " IdUnusedException, not found, or not an AuthzGroup object"); addAlert(state, rb.getString("java.realm") + realmId); } context.put("studentMembers", studentMembers); context.put("assignmentService", AssignmentService.getInstance()); Hashtable showStudentAssignments = new Hashtable(); if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) != null) { Set showStudentListSet = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); context.put("studentListShowSet", showStudentListSet); for (Iterator showStudentListSetIterator=showStudentListSet.iterator(); showStudentListSetIterator.hasNext();) { // get user try { String userId = (String) showStudentListSetIterator.next(); User user = UserDirectoryService.getUser(userId); showStudentAssignments.put(user, AssignmentService.getAssignmentsForContext(contextString, userId)); } catch (Exception ee) { Log.warn("chef", this + ee.getMessage()); } } } context.put("studentAssignmentsTable", showStudentAssignments); add2ndToolbarFields(data, context); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT; } // build_instructor_view_students_assignment_context /** * build the instructor view to report the submissions */ protected String build_instructor_report_submissions(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("submissions", prepPage(state)); context.put("sortedBy", (String) state.getAttribute(SORTED_SUBMISSION_BY)); context.put("sortedAsc", (String) state.getAttribute(SORTED_SUBMISSION_ASC)); context.put("sortedBy_lastName", SORTED_SUBMISSION_BY_LASTNAME); context.put("sortedBy_submitTime", SORTED_SUBMISSION_BY_SUBMIT_TIME); context.put("sortedBy_grade", SORTED_SUBMISSION_BY_GRADE); context.put("sortedBy_status", SORTED_SUBMISSION_BY_STATUS); context.put("sortedBy_released", SORTED_SUBMISSION_BY_RELEASED); context.put("sortedBy_assignment", SORTED_SUBMISSION_BY_ASSIGNMENT); context.put("sortedBy_maxGrade", SORTED_SUBMISSION_BY_MAX_GRADE); add2ndToolbarFields(data, context); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("accessPointUrl", ServerConfigurationService.getAccessUrl() + AssignmentService.gradesSpreadsheetReference(contextString, null)); pagingInfoToContext(state, context); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS; } // build_instructor_report_submissions /** * build the instructor view to upload information from archive file */ protected String build_instructor_upload_all(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("hasSubmissions", state.getAttribute(UPLOAD_ALL_HAS_SUBMISSIONS)); context.put("hasGradeFile", state.getAttribute(UPLOAD_ALL_HAS_GRADEFILE)); context.put("hasComments", state.getAttribute(UPLOAD_ALL_HAS_COMMENTS)); context.put("releaseGrades", state.getAttribute(UPLOAD_ALL_RELEASE_GRADES)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_UPLOAD_ALL; } // build_instructor_upload_all /** ** Retrieve tool title from Tool configuration file or use default ** (This should return i18n version of tool title if available) **/ private String getToolTitle() { Tool tool = ToolManager.getTool("sakai.assignment.grades"); String toolTitle = null; if (tool == null) toolTitle = "Assignments"; else toolTitle = tool.getTitle(); return toolTitle; } /** * Go to the instructor view */ public void doView_instructor(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(SORTED_BY, SORTED_BY_DUEDATE); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doView_instructor /** * Go to the student view */ public void doView_student(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // to the student list of assignment view state.setAttribute(SORTED_BY, SORTED_BY_DUEDATE); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doView_student /** * Action is to view the content of one specific assignment submission */ public void doView_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the submission context resetViewSubmission(state); ParameterParser params = data.getParameters(); String assignmentReference = params.getString("assignmentReference"); state.setAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE, assignmentReference); User u = (User) state.getAttribute(STATE_USER); try { AssignmentSubmission submission = AssignmentService.getSubmission(assignmentReference, u); if (submission != null) { state.setAttribute(VIEW_SUBMISSION_TEXT, submission.getSubmittedText()); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, (new Boolean(submission.getHonorPledgeFlag())).toString()); List v = EntityManager.newReferenceList(); Iterator l = submission.getSubmittedAttachments().iterator(); while (l.hasNext()) { v.add(l.next()); } state.setAttribute(ATTACHMENTS, v); } else { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false"); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } // try } // doView_submission /** * Preview of the submission */ public void doPreview_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // String assignmentId = params.getString(assignmentId); state.setAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE, state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE)); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(PREVIEW_SUBMISSION_TEXT, text); state.setAttribute(VIEW_SUBMISSION_TEXT, text); // assign the honor pledge attribute String honor_pledge_yes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honor_pledge_yes == null) { honor_pledge_yes = "false"; } state.setAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes); state.setAttribute(PREVIEW_SUBMISSION_ATTACHMENTS, state.getAttribute(ATTACHMENTS)); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_PREVIEW_SUBMISSION); } } // doPreview_submission /** * Preview of the grading of submission */ public void doPreview_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // read user input readGradeForm(data, state, "read"); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION); } } // doPreview_grade_submission /** * Action is to end the preview submission process */ public void doDone_preview_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION); } // doDone_preview_submission /** * Action is to end the view assignment process */ public void doDone_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doDone_view_assignments /** * Action is to end the preview new assignment process */ public void doDone_preview_new_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the new assignment page state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } // doDone_preview_new_assignment /** * Action is to end the preview edit assignment process */ public void doDone_preview_edit_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the edit assignment page state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } // doDone_preview_edit_assignment /** * Action is to end the user view assignment process and redirect him to the assignment list view */ public void doCancel_student_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view assignment state.setAttribute(VIEW_ASSIGNMENT_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_student_view_assignment /** * Action is to end the show submission process */ public void doCancel_show_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view assignment state.setAttribute(VIEW_ASSIGNMENT_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_show_submission /** * Action is to cancel the delete assignment process */ public void doCancel_delete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the show assignment object state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector()); // back to the instructor list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_delete_assignment /** * Action is to end the show submission process */ public void doCancel_edit_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_edit_assignment /** * Action is to end the show submission process */ public void doCancel_new_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the assignment object resetAssignment(state); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_new_assignment /** * Action is to cancel the grade submission process */ public void doCancel_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the assignment object // resetAssignment (state); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } // doCancel_grade_submission /** * Action is to cancel the preview grade process */ public void doCancel_preview_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the instructor view of grading a submission state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION); } // doCancel_preview_grade_submission /** * Action is to cancel the preview grade process */ public void doCancel_preview_to_list_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the instructor view of grading a submission state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } // doCancel_preview_to_list_submission /** * Action is to return to the view of list assignments */ public void doList_assignments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(SORTED_BY, SORTED_BY_DUEDATE); state.setAttribute(SORTED_ASC, Boolean.FALSE.toString()); } // doList_assignments /** * Action is to cancel the student view grade process */ public void doCancel_view_grade(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view grade submission id state.setAttribute(VIEW_GRADE_SUBMISSION_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_view_grade /** * Action is to save the grade to submission */ public void doSave_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "save"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "save"); } } // doSave_grade_submission /** * Action is to release the grade to submission */ public void doRelease_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "release"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "release"); } } // doRelease_grade_submission /** * Action is to return submission with or without grade */ public void doReturn_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "return"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "return"); } } // doReturn_grade_submission /** * Action is to return submission with or without grade from preview */ public void doReturn_preview_grade_submission(RunData data) { grade_submission_option(data, "return"); } // doReturn_grade_preview_submission /** * Action is to save submission with or without grade from preview */ public void doSave_preview_grade_submission(RunData data) { grade_submission_option(data, "save"); } // doSave_grade_preview_submission /** * Common grading routine plus specific operation to differenciate cases when saving, releasing or returning grade. */ private void grade_submission_option(RunData data, String gradeOption) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID); try { // for points grading, one have to enter number as the points String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(sId); Assignment a = sEdit.getAssignment(); if (gradeOption.equals("release")) { sEdit.setGradeReleased(true); // clear the returned flag sEdit.setReturned(false); sEdit.setTimeReturned(null); } else if (gradeOption.equals("return")) { if (StringUtil.trimToNull(grade) != null) { sEdit.setGradeReleased(true); } sEdit.setReturned(true); sEdit.setTimeReturned(TimeService.newTime()); sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue()); } boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue(): false; int typeOfGrade = a.getContent().getTypeOfGrade(); if (!withGrade) { // no grade input needed for the without-grade version of assignment tool sEdit.setGraded(true); if (gradeOption.equals("return") || gradeOption.equals("release")) { sEdit.setGradeReleased(true); } } else if (grade == null) { sEdit.setGrade(""); sEdit.setGraded(false); sEdit.setGradeReleased(false); } else { if (typeOfGrade == 1) { sEdit.setGrade("no grade"); sEdit.setGraded(true); } else { if (!grade.equals("")) { if (typeOfGrade == 3) { sEdit.setGrade(grade); } else { sEdit.setGrade(grade); } sEdit.setGraded(true); } } } if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { // get resubmit number ResourcePropertiesEdit pEdit = sEdit.getPropertiesEdit(); pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); if (state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR) != null) { // get resubmit time Time closeTime = getAllowSubmitCloseTime(state); pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime())); } else { pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } } // the instructor comment String feedbackCommentString = StringUtil .trimToNull((String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); if (feedbackCommentString != null) { sEdit.setFeedbackComment(feedbackCommentString); } // the instructor inline feedback String feedbackTextString = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT); if (feedbackTextString != null) { sEdit.setFeedbackText(feedbackTextString); } List v = (List) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); if (v != null) { // clear the old attachments first sEdit.clearFeedbackAttachments(); for (int i = 0; i < v.size(); i++) { sEdit.addFeedbackAttachment((Reference) v.get(i)); } } String sReference = sEdit.getReference(); AssignmentService.commitEdit(sEdit); } catch (IdUnusedException e) { } catch (PermissionException e) { } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } // try if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } } // grade_submission_option /** * Action is to save the submission as a draft */ public void doSave_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); if (text == null) { text = (String) state.getAttribute(VIEW_SUBMISSION_TEXT); } String honorPledgeYes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honorPledgeYes == null) { honorPledgeYes = "false"; } String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); User u = (User) state.getAttribute(STATE_USER); if (state.getAttribute(STATE_MESSAGE) == null) { try { Assignment a = AssignmentService.getAssignment(aReference); String assignmentId = a.getId(); AssignmentSubmission submission = AssignmentService.getSubmission(aReference, u); if (submission != null) { // the submission already exists, change the text and honor pledge value, save as draft try { AssignmentSubmissionEdit edit = AssignmentService.editSubmission(submission.getReference()); edit.setSubmittedText(text); edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); edit.setSubmitted(false); // edit.addSubmitter (u); edit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { // clear the old attachments first edit.clearSubmittedAttachments(); // add each new attachment Iterator it = attachments.iterator(); while (it.hasNext()) { edit.addSubmittedAttachment((Reference) it.next()); } } AssignmentService.commitEdit(edit); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin2") + " " + a.getTitle()); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot12")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } } else { // new submission, save as draft try { AssignmentSubmissionEdit edit = AssignmentService.addSubmission((String) state .getAttribute(STATE_CONTEXT_STRING), assignmentId); edit.setSubmittedText(text); edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); edit.setSubmitted(false); // edit.addSubmitter (u); edit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { // add each attachment Iterator it = attachments.iterator(); while (it.hasNext()) { edit.addSubmittedAttachment((Reference) it.next()); } } AssignmentService.commitEdit(edit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot4")); } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } } // doSave_submission /** * Action is to post the submission */ public void doPost_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment a = null; try { a = AssignmentService.getAssignment(aReference); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin2")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } if (AssignmentService.canSubmit(contextString, a)) { ParameterParser params = data.getParameters(); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); if (text == null) { text = (String) state.getAttribute(VIEW_SUBMISSION_TEXT); } else { state.setAttribute(VIEW_SUBMISSION_TEXT, text); } String honorPledgeYes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honorPledgeYes == null) { honorPledgeYes = (String) state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES); } if (honorPledgeYes == null) { honorPledgeYes = "false"; } User u = (User) state.getAttribute(STATE_USER); String assignmentId = ""; if (state.getAttribute(STATE_MESSAGE) == null) { assignmentId = a.getId(); if (a.getContent().getHonorPledge() != 1) { if (!Boolean.valueOf(honorPledgeYes).booleanValue()) { addAlert(state, rb.getString("youarenot18")); } state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honorPledgeYes); } // check the submission inputs based on the submission type int submissionType = a.getContent().getTypeOfSubmission(); if (submissionType == 1) { // for the inline only submission if (text.length() == 0) { addAlert(state, rb.getString("youmust7")); } } else if (submissionType == 2) { // for the attachment only submission Vector v = (Vector) state.getAttribute(ATTACHMENTS); if ((v == null) || (v.size() == 0)) { addAlert(state, rb.getString("youmust1")); } } else if (submissionType == 3) { // for the inline and attachment submission Vector v = (Vector) state.getAttribute(ATTACHMENTS); if ((text.length() == 0) && ((v == null) || (v.size() == 0))) { addAlert(state, rb.getString("youmust2")); } } } if ((state.getAttribute(STATE_MESSAGE) == null) && (a != null)) { try { AssignmentSubmission submission = AssignmentService.getSubmission(a.getReference(), u); if (submission != null) { // the submission already exists, change the text and honor pledge value, post it try { AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference()); sEdit.setSubmittedText(text); sEdit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); sEdit.setTimeSubmitted(TimeService.newTime()); sEdit.setSubmitted(true); // for resubmissions // when resubmit, keep the Returned flag on till the instructor grade again. if (sEdit.getReturned()) { ResourcePropertiesEdit sPropertiesEdit = sEdit.getPropertiesEdit(); if (sEdit.getGraded()) { // add the current grade into previous grade histroy String previousGrades = (String) sEdit.getProperties().getProperty( ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES); if (previousGrades == null) { previousGrades = (String) sEdit.getProperties().getProperty( ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES); if (previousGrades != null) { int typeOfGrade = a.getContent().getTypeOfGrade(); if (typeOfGrade == 3) { // point grade assignment type // some old unscaled grades, need to scale the number and remove the old property String[] grades = StringUtil.split(previousGrades, " "); String newGrades = ""; for (int jj = 0; jj < grades.length; jj++) { String grade = grades[jj]; if (grade.indexOf(".") == -1) { // show the grade with decimal point grade = grade.concat(".0"); } newGrades = newGrades.concat(grade + " "); } previousGrades = newGrades; } sPropertiesEdit.removeProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES); } else { previousGrades = ""; } } previousGrades = previousGrades.concat(sEdit.getGradeDisplay() + " "); sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES, previousGrades); // clear the current grade and make the submission ungraded sEdit.setGraded(false); sEdit.setGrade(""); sEdit.setGradeReleased(false); } // keep the history of assignment feed back text String feedbackTextHistory = sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null ? sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) : ""; feedbackTextHistory = sEdit.getFeedbackText() + "\n" + feedbackTextHistory; sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT, feedbackTextHistory); // keep the history of assignment feed back comment String feedbackCommentHistory = sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null ? sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) : ""; feedbackCommentHistory = sEdit.getFeedbackComment() + "\n" + feedbackCommentHistory; sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT, feedbackCommentHistory); // keep the history of assignment feed back comment String feedbackAttachmentHistory = sPropertiesEdit .getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null ? sPropertiesEdit .getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) : ""; List feedbackAttachments = sEdit.getFeedbackAttachments(); for (int k = 0; k<feedbackAttachments.size();k++) { feedbackAttachmentHistory = ((Reference) feedbackAttachments.get(k)).getReference() + "," + feedbackAttachmentHistory; } sPropertiesEdit.addProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS, feedbackAttachmentHistory); // reset the previous grading context sEdit.setFeedbackText(""); sEdit.setFeedbackComment(""); sEdit.clearFeedbackAttachments(); // decrease the allow_resubmit_number if (sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { int number = Integer.parseInt(sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); // minus 1 from the submit number if (number>=1) { sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, String.valueOf(number-1)); } else if (number == -1) { sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, String.valueOf(-1)); } } } // sEdit.addSubmitter (u); sEdit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { //Post the attachments before clearing so that we don't sumbit duplicate attachments //Check if we need to post the attachments if (a.getContent().getAllowReviewService()) { if (!attachments.isEmpty()) { sEdit.postAttachment((Reference) attachments.get(0)); } } // clear the old attachments first sEdit.clearSubmittedAttachments(); // add each new attachment Iterator it = attachments.iterator(); while (it.hasNext()) { sEdit.addSubmittedAttachment((Reference) it.next()); } } AssignmentService.commitEdit(sEdit); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin2") + " " + a.getTitle()); } catch (PermissionException e) { addAlert(state, rb.getString("no_permissiion_to_edit_submission")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } } else { // new submission, post it try { AssignmentSubmissionEdit edit = AssignmentService.addSubmission(contextString, assignmentId); edit.setSubmittedText(text); edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); edit.setTimeSubmitted(TimeService.newTime()); edit.setSubmitted(true); // edit.addSubmitter (u); edit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { // add each attachment if ((!attachments.isEmpty()) && a.getContent().getAllowReviewService()) edit.postAttachment((Reference) attachments.get(0)); // add each attachment Iterator it = attachments.iterator(); while (it.hasNext()) { edit.addSubmittedAttachment((Reference) it.next()); } } // get the assignment setting for resubmitting if (a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { edit.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); } AssignmentService.commitEdit(edit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot13")); } } // if -else } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } } // if if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION); } } // if } // doPost_submission /** * Action is to confirm the submission and return to list view */ public void doConfirm_assignment_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } /** * Action is to show the new assignment screen */ public void doNew_assignment(RunData data, Context context) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { if (AssignmentService.allowAddAssignment((String) state.getAttribute(STATE_CONTEXT_STRING))) { resetAssignment(state); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } else { addAlert(state, rb.getString("youarenot2")); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } } // doNew_Assignment /** * Action is to save the input infos for assignment fields * * @param validify * Need to validify the inputs or not */ protected void setNewAssignmentParameters(RunData data, boolean validify) { // read the form inputs SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // put the input value into the state attributes String title = params.getString(NEW_ASSIGNMENT_TITLE); state.setAttribute(NEW_ASSIGNMENT_TITLE, title); if (title.length() == 0) { // empty assignment title addAlert(state, rb.getString("plespethe1")); } // open time int openMonth = (new Integer(params.getString(NEW_ASSIGNMENT_OPENMONTH))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(openMonth)); int openDay = (new Integer(params.getString(NEW_ASSIGNMENT_OPENDAY))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(openDay)); int openYear = (new Integer(params.getString(NEW_ASSIGNMENT_OPENYEAR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(openYear)); int openHour = (new Integer(params.getString(NEW_ASSIGNMENT_OPENHOUR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer(openHour)); int openMin = (new Integer(params.getString(NEW_ASSIGNMENT_OPENMIN))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(openMin)); String openAMPM = params.getString(NEW_ASSIGNMENT_OPENAMPM); state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, openAMPM); if ((openAMPM.equals("PM")) && (openHour != 12)) { openHour = openHour + 12; } if ((openHour == 12) && (openAMPM.equals("AM"))) { openHour = 0; } Time openTime = TimeService.newTimeLocal(openYear, openMonth, openDay, openHour, openMin, 0, 0); // validate date if (!Validator.checkDate(openDay, openMonth, openYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.opendate") + "."); } // due time int dueMonth = (new Integer(params.getString(NEW_ASSIGNMENT_DUEMONTH))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(dueMonth)); int dueDay = (new Integer(params.getString(NEW_ASSIGNMENT_DUEDAY))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(dueDay)); int dueYear = (new Integer(params.getString(NEW_ASSIGNMENT_DUEYEAR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(dueYear)); int dueHour = (new Integer(params.getString(NEW_ASSIGNMENT_DUEHOUR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer(dueHour)); int dueMin = (new Integer(params.getString(NEW_ASSIGNMENT_DUEMIN))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(dueMin)); String dueAMPM = params.getString(NEW_ASSIGNMENT_DUEAMPM); state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, dueAMPM); if ((dueAMPM.equals("PM")) && (dueHour != 12)) { dueHour = dueHour + 12; } if ((dueHour == 12) && (dueAMPM.equals("AM"))) { dueHour = 0; } Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0); // validate date if (dueTime.before(TimeService.newTime())) { addAlert(state, rb.getString("assig4")); } if (!Validator.checkDate(dueDay, dueMonth, dueYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.duedate") + "."); } state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true)); // close time int closeMonth = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEMONTH))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(closeMonth)); int closeDay = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEDAY))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(closeDay)); int closeYear = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEYEAR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(closeYear)); int closeHour = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEHOUR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer(closeHour)); int closeMin = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEMIN))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(closeMin)); String closeAMPM = params.getString(NEW_ASSIGNMENT_CLOSEAMPM); state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, closeAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); // validate date if (!Validator.checkDate(closeDay, closeMonth, closeYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.closedate") + "."); } if (closeTime.before(openTime)) { addAlert(state, rb.getString("acesubdea3")); } if (closeTime.before(dueTime)) { addAlert(state, rb.getString("acesubdea2")); } // SECTION MOD String sections_string = ""; String mode = (String) state.getAttribute(STATE_MODE); if (mode == null) mode = ""; state.setAttribute(NEW_ASSIGNMENT_SECTION, sections_string); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(params.getString(NEW_ASSIGNMENT_SUBMISSION_TYPE))); int gradeType = -1; // grade type and grade points if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()) { gradeType = Integer.parseInt(params.getString(NEW_ASSIGNMENT_GRADE_TYPE)); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(gradeType)); } String r = params.getString(NEW_ASSIGNMENT_USE_REVIEW_SERVICE); String b; // set whether we use the review service or not if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE, b); //set whether students can view the review service results r = params.getString(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW, b); // treat the new assignment description as formatted text boolean checkForFormattingErrors = true; // instructor is creating a new assignment - so check for errors String description = processFormattedTextFromBrowser(state, params.getCleanString(NEW_ASSIGNMENT_DESCRIPTION), checkForFormattingErrors); state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, description); if (state.getAttribute(CALENDAR) != null) { // calendar enabled for the site if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE) != null && params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE).equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.TRUE.toString()); } else { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString()); } } else { // no calendar yet for the site state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); } if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE) != null && params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE) .equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.TRUE.toString()); } else { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString()); } String s = params.getString(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); // set the honor pledge to be "no honor pledge" if (s == null) s = "1"; state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, s); String grading = params.getString(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, grading); // only when choose to associate with assignment in Gradebook String associateAssignment = params.getString(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); if (grading != null) { if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE)) { state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateAssignment); } else { state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, ""); } if (!grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // gradebook integration only available to point-grade assignment if (gradeType != Assignment.SCORE_GRADE_TYPE) { addAlert(state, rb.getString("addtogradebook.wrongGradeScale")); } // if chosen as "associate", have to choose one assignment from Gradebook if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE) && StringUtil.trimToNull(associateAssignment) == null) { addAlert(state, rb.getString("grading.associate.alert")); } } } List attachments = (List) state.getAttribute(ATTACHMENTS); state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, attachments); // correct inputs // checks on the times if (validify && dueTime.before(openTime)) { addAlert(state, rb.getString("assig3")); } if (validify) { if (((description == null) || (description.length() == 0)) && ((attachments == null || attachments.size() == 0))) { // if there is no description nor an attachment, show the following alert message. // One could ignore the message and still post the assignment if (state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) == null) { state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY, Boolean.TRUE.toString()); } else { state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); } } else { state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); } } if (validify && state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) != null) { addAlert(state, rb.getString("thiasshas")); } if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()) { // the grade point String gradePoints = params.getString(NEW_ASSIGNMENT_GRADE_POINTS); state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints); if (gradePoints != null) { if (gradeType == 3) { if ((gradePoints.length() == 0)) { // in case of point grade assignment, user must specify maximum grade point addAlert(state, rb.getString("plespethe3")); } else { validPointGrade(state, gradePoints); // when scale is points, grade must be integer and less than maximum value if (state.getAttribute(STATE_MESSAGE) == null) { gradePoints = scalePointGrade(state, gradePoints); } state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints); } } } } // assignment range? String range = data.getParameters().getString("range"); state.setAttribute(NEW_ASSIGNMENT_RANGE, range); if (range.equals("groups")) { String[] groupChoice = data.getParameters().getStrings("selectedGroups"); if (groupChoice != null && groupChoice.length != 0) { state.setAttribute(NEW_ASSIGNMENT_GROUPS, new ArrayList(Arrays.asList(groupChoice))); } else { state.setAttribute(NEW_ASSIGNMENT_GROUPS, null); addAlert(state, rb.getString("java.alert.youchoosegroup")); } } else { state.removeAttribute(NEW_ASSIGNMENT_GROUPS); } // allow resubmission numbers String nString = params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); if (nString != null) { state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, nString); } // assignment notification option String notiOption = params.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS); if (notiOption != null) { state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, notiOption); } } // setNewAssignmentParameters /** * Action is to hide the preview assignment student view */ public void doHide_submission_assignment_instruction(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); // save user input readGradeForm(data, state, "read"); } // doHide_preview_assignment_student_view /** * Action is to show the preview assignment student view */ public void doShow_submission_assignment_instruction(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(true)); // save user input readGradeForm(data, state, "read"); } // doShow_submission_assignment_instruction /** * Action is to hide the preview assignment student view */ public void doHide_preview_assignment_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(true)); } // doHide_preview_assignment_student_view /** * Action is to show the preview assignment student view */ public void doShow_preview_assignment_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(false)); } // doShow_preview_assignment_student_view /** * Action is to hide the preview assignment assignment infos */ public void doHide_preview_assignment_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(true)); } // doHide_preview_assignment_assignment /** * Action is to show the preview assignment assignment info */ public void doShow_preview_assignment_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(false)); } // doShow_preview_assignment_assignment /** * Action is to hide the assignment option */ public void doHide_assignment_option(RunData data) { setNewAssignmentParameters(data, false); SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(true)); state.setAttribute(NEW_ASSIGNMENT_FOCUS, "eventSubmit_doShow_assignment_option"); } // doHide_assignment_option /** * Action is to show the assignment option */ public void doShow_assignment_option(RunData data) { setNewAssignmentParameters(data, false); SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(false)); state.setAttribute(NEW_ASSIGNMENT_FOCUS, NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); } // doShow_assignment_option /** * Action is to hide the assignment content in the view assignment page */ public void doHide_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(true)); } // doHide_view_assignment /** * Action is to show the assignment content in the view assignment page */ public void doShow_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(false)); } // doShow_view_assignment /** * Action is to hide the student view in the view assignment page */ public void doHide_view_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(true)); } // doHide_view_student_view /** * Action is to show the student view in the view assignment page */ public void doShow_view_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(false)); } // doShow_view_student_view /** * Action is to post assignment */ public void doPost_assignment(RunData data) { // post assignment postOrSaveAssignment(data, "post"); } // doPost_assignment /** * Action is to tag items via an items tagging helper */ public void doHelp_items(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String activityRef = params.getString(ACTIVITY_REF); TaggingHelperInfo helperInfo = provider .getItemsHelperInfo(activityRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (Iterator<String> keys = helperParms.keySet().iterator(); keys .hasNext();) { String key = keys.next(); state.setAttribute(key, helperParms.get(key)); } } // doHelp_items /** * Action is to tag an individual item via an item tagging helper */ public void doHelp_item(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String itemRef = params.getString(ITEM_REF); TaggingHelperInfo helperInfo = provider .getItemHelperInfo(itemRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (Iterator<String> keys = helperParms.keySet().iterator(); keys .hasNext();) { String key = keys.next(); state.setAttribute(key, helperParms.get(key)); } } // doHelp_item /** * Action is to tag an activity via an activity tagging helper */ public void doHelp_activity(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String activityRef = params.getString(ACTIVITY_REF); TaggingHelperInfo helperInfo = provider .getActivityHelperInfo(activityRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (String key : helperParms.keySet()) { state.setAttribute(key, helperParms.get(key)); } } // doHelp_activity /** * post or save assignment */ private void postOrSaveAssignment(RunData data, String postOrSave) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String siteId = (String) state.getAttribute(STATE_CONTEXT_STRING); boolean post = (postOrSave != null) && postOrSave.equals("post"); // assignment old title String aOldTitle = null; // assignment old associated Gradebook entry if any String oAssociateGradebookAssignment = null; String mode = (String) state.getAttribute(STATE_MODE); if (!mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT)) { // read input data if the mode is not preview mode setNewAssignmentParameters(data, true); } String assignmentId = params.getString("assignmentId"); String assignmentContentId = params.getString("assignmentContentId"); if (state.getAttribute(STATE_MESSAGE) == null) { // AssignmentContent object AssignmentContentEdit ac = getAssignmentContentEdit(state, assignmentContentId); // Assignment AssignmentEdit a = getAssignmentEdit(state, assignmentId); // put the names and values into vm file String title = (String) state.getAttribute(NEW_ASSIGNMENT_TITLE); // open time Time openTime = getOpenTime(state); // due time Time dueTime = getDueTime(state); // close time Time closeTime = dueTime; boolean enableCloseDate = ((Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)).booleanValue(); if (enableCloseDate) { closeTime = getCloseTime(state); } // sections String s = (String) state.getAttribute(NEW_ASSIGNMENT_SECTION); int submissionType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)).intValue(); int gradeType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)).intValue(); String gradePoints = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); String description = (String) state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION); String checkAddDueTime = state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)!=null?(String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE):null; String checkAutoAnnounce = (String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE); String checkAddHonorPledge = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); String addtoGradebook = state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null?(String) state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK):"" ; String associateGradebookAssignment = (String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); String allowResubmitNumber = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null?(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER):null; boolean useReviewService = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE)); boolean allowStudentViewReport = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW)); // the attachments List attachments = (List) state.getAttribute(ATTACHMENTS); List attachments1 = EntityManager.newReferenceList(attachments); // set group property String range = (String) state.getAttribute(NEW_ASSIGNMENT_RANGE); Collection groups = new Vector(); try { Site site = SiteService.getSite(siteId); Collection groupChoice = (Collection) state.getAttribute(NEW_ASSIGNMENT_GROUPS); if (range.equals(Assignment.AssignmentAccess.GROUPED) && (groupChoice == null || groupChoice.size() == 0)) { // show alert if no group is selected for the group access assignment addAlert(state, rb.getString("java.alert.youchoosegroup")); } else if (groupChoice != null) { for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();) { String groupId = (String) iGroups.next(); groups.add(site.getGroup(groupId)); } } } catch (Exception e) { Log.warn("chef", this + e.getMessage()); } if ((state.getAttribute(STATE_MESSAGE) == null) && (ac != null) && (a != null)) { aOldTitle = a.getTitle(); // old open time Time oldOpenTime = a.getOpenTime(); // old due time Time oldDueTime = a.getDueTime(); // commit the changes to AssignmentContent object commitAssignmentContentEdit(state, ac, title, submissionType,useReviewService,allowStudentViewReport, gradeType, gradePoints, description, checkAddHonorPledge, attachments1); // set the Assignment Properties object ResourcePropertiesEdit aPropertiesEdit = a.getPropertiesEdit(); oAssociateGradebookAssignment = aPropertiesEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); editAssignmentProperties(a, title, checkAddDueTime, checkAutoAnnounce, addtoGradebook, associateGradebookAssignment, allowResubmitNumber, aPropertiesEdit); // the notification option if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null) { aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); } // comment the changes to Assignment object commitAssignmentEdit(state, post, ac, a, title, openTime, dueTime, closeTime, enableCloseDate, s, range, groups); // in case of non-electronic submission, create submissions for all students and mark it as submitted if (ac.getTypeOfSubmission()== Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { try { Iterator sList = AssignmentService.getSubmissions(a).iterator(); if (sList == null || !sList.hasNext()) { // add non-electronic submissions if there is none yet addSubmissionsForNonElectronicAssignment(state, a); } } catch (Exception ee) { Log.warn("chef", this + ee.getMessage()); } } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); resetAssignment(state); } if (post) { // only if user is posting the assignment // add the due date to schedule if the schedule exists integrateWithCalendar(state, a, title, dueTime, checkAddDueTime, oldDueTime, aPropertiesEdit); // the open date been announced integrateWithAnnouncement(state, aOldTitle, a, title, openTime, checkAutoAnnounce, oldOpenTime); // integrate with Gradebook try { integrateWithGradebook(state, siteId, aOldTitle, oAssociateGradebookAssignment, a, title, dueTime, gradeType, gradePoints, addtoGradebook, associateGradebookAssignment, range); } catch (AssignmentHasIllegalPointsException e) { addAlert(state, rb.getString("addtogradebook.illegalPoints")); } } // if } // if } // if } // postOrSaveAssignment /** * Add submission objects if necessary for non-electronic type of assignment * @param state * @param a */ private void addSubmissionsForNonElectronicAssignment(SessionState state, Assignment a) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String authzGroupId = SiteService.siteReference(contextString); List allowAddSubmissionUsers = AssignmentService.allowAddSubmissionUsers(a.getReference()); try { AuthzGroup group = AuthzGroupService.getAuthzGroup(authzGroupId); Set grants = group.getUsers(); for (Iterator iUserIds = grants.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); try { User u = UserDirectoryService.getUser(userId); // only include those users that can submit to this assignment if (u != null && allowAddSubmissionUsers.contains(u)) { if (AssignmentService.getSubmission(a.getReference(), u) == null) { // construct fake submissions for grading purpose AssignmentSubmissionEdit submission = AssignmentService.addSubmission(contextString, a.getId()); submission.removeSubmitter(UserDirectoryService.getCurrentUser()); submission.addSubmitter(u); submission.setTimeSubmitted(TimeService.newTime()); submission.setSubmitted(true); submission.setAssignment(a); AssignmentService.commitEdit(submission); } } } catch (Exception e) { Log.warn("chef", this + e.toString() + " here userId = " + userId); } } } catch (Exception e) { Log.warn("chef", this + e.getMessage() + " authGroupId=" + authzGroupId); } } /** * Starting from Sakai 2.4, the linked assignment in GB will all be internal, instead of externally maintained. * Need to run the following method to update all the previously created externally maintained assignment * @param a */ private void updateExternalAssignmentInGB(Assignment a, GradebookService g, String gradebookUid) { ResourceProperties properties = a.getProperties(); if (properties.getProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null) { // temporally allow the user update gradebook records SecurityService.pushAdvisor(new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { return SecurityAdvice.ALLOWED; } }); String associateGradebookAssignment = StringUtil.trimToNull(properties.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); if (associateGradebookAssignment != null && g.isAssignmentDefined(gradebookUid, associateGradebookAssignment)) { // add or remove external grades to gradebook // a. if Gradebook does not exists, do nothing, 'cos setting should have been hidden // b. if Gradebook exists, do updates org.sakaiproject.service.gradebook.shared.Assignment assignmentDefinition = g.getAssignment(gradebookUid, associateGradebookAssignment); if (assignmentDefinition != null && assignmentDefinition.isExternallyMaintained()) { // those entries are created before Sakai2.4 as externally maintained accessment in Gradebook, need to update it to internal assignment assignmentDefinition.setExternallyMaintained(false); assignmentDefinition.setExternalId(null); assignmentDefinition.setExternalAppName(null); g.updateAssignment(gradebookUid, associateGradebookAssignment, assignmentDefinition); // bulk add all grades for assignment into gradebook AssignmentService.integrateGradebook(a.getReference(), associateGradebookAssignment, associateGradebookAssignment, null, null, null, -1, null, null, "update"); } } // clear the permission SecurityService.clearAdvisors(); } } /** * called from postOrSaveAssignment function to do integration * @param state * @param siteId * @param aOldTitle * @param oAssociateGradebookAssignment * @param a * @param title * @param dueTime * @param gradeType * @param gradePoints * @param addtoGradebook * @param associateGradebookAssignment * @param range */ private void integrateWithGradebook(SessionState state, String siteId, String aOldTitle, String oAssociateGradebookAssignment, AssignmentEdit a, String title, Time dueTime, int gradeType, String gradePoints, String addtoGradebook, String associateGradebookAssignment, String range) { String aReference = a.getReference(); if (!addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // if grouped assignment is not allowed to add into Gradebook if (!AssignmentService.getAllowGroupAssignmentsInGradebook() && (range.equals("groups"))) { addAlert(state, rb.getString("java.alert.noGroupedAssignmentIntoGB")); String ref = ""; try { ref = a.getReference(); AssignmentEdit aEdit = AssignmentService.editAssignment(ref); aEdit.getPropertiesEdit().removeProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); aEdit.getPropertiesEdit().removeProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); AssignmentService.commitEdit(aEdit); } catch (Exception ignore) { // ignore the exception Log.warn("chef", rb.getString("cannotfin2") + ref); } AssignmentService.integrateGradebook(aReference, associateGradebookAssignment, oAssociateGradebookAssignment, AssignmentService.GRADEBOOK_INTEGRATION_NO, null, null, -1, null, null, "remove"); } else { if (!addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO) && gradeType == 3) { try { //integrate assignment with gradebook //add all existing grades, if any, into Gradebook String rv = AssignmentService.integrateGradebook(aReference, associateGradebookAssignment, oAssociateGradebookAssignment, addtoGradebook, aOldTitle, title, Integer.parseInt (gradePoints), dueTime, null, "update"); if (rv != null && rv.length() > 0) { addAlert(state, rv); } } catch (NumberFormatException nE) { alertInvalidPoint(state, gradePoints); } } else { // otherwise, cannot do the association } } } else { // no need to do anything here, if the assignment is chosen to not hook up with GB. // user can go to GB and delete the entry there manually } } private void integrateWithAnnouncement(SessionState state, String aOldTitle, AssignmentEdit a, String title, Time openTime, String checkAutoAnnounce, Time oldOpenTime) { if (checkAutoAnnounce.equalsIgnoreCase(Boolean.TRUE.toString())) { AnnouncementChannel channel = (AnnouncementChannel) state.getAttribute(ANNOUNCEMENT_CHANNEL); if (channel != null) { String openDateAnnounced = a.getProperties().getProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED); // announcement channel is in place try { AnnouncementMessageEdit message = channel.addAnnouncementMessage(); AnnouncementMessageHeaderEdit header = message.getAnnouncementHeaderEdit(); header.setDraft(/* draft */false); header.replaceAttachments(/* attachment */EntityManager.newReferenceList()); if (openDateAnnounced == null) { // making new announcement header.setSubject(/* subject */rb.getString("assig6") + " " + title); message.setBody(/* body */rb.getString("opedat") + " " + FormattedText.convertPlaintextToFormattedText(title) + " " + rb.getString("is") + " " + openTime.toStringLocalFull() + ". "); } else { // revised announcement header.setSubject(/* subject */rb.getString("assig5") + " " + title); message.setBody(/* body */rb.getString("newope") + " " + FormattedText.convertPlaintextToFormattedText(title) + " " + rb.getString("is") + " " + openTime.toStringLocalFull() + ". "); } // group information if (a.getAccess().equals(Assignment.AssignmentAccess.GROUPED)) { try { // get the group ids selected Collection groupRefs = a.getGroups(); // make a collection of Group objects Collection groups = new Vector(); //make a collection of Group objects from the collection of group ref strings Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();) { String groupRef = (String) iGroupRefs.next(); groups.add(site.getGroup(groupRef)); } // set access header.setGroupAccess(groups); } catch (Exception exception) { // log Log.warn("chef", exception.getMessage()); } } else { // site announcement header.clearGroupAccess(); } channel.commitMessage(message, NotificationService.NOTI_NONE); // commit related properties into Assignment object String ref = ""; try { ref = a.getReference(); AssignmentEdit aEdit = AssignmentService.editAssignment(ref); aEdit.getPropertiesEdit().addProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED, Boolean.TRUE.toString()); if (message != null) { aEdit.getPropertiesEdit().addProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID, message.getId()); } AssignmentService.commitEdit(aEdit); } catch (Exception ignore) { // ignore the exception Log.warn("chef", rb.getString("cannotfin2") + ref); } } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotmak")); } } } // if } private void integrateWithCalendar(SessionState state, AssignmentEdit a, String title, Time dueTime, String checkAddDueTime, Time oldDueTime, ResourcePropertiesEdit aPropertiesEdit) { if (state.getAttribute(CALENDAR) != null) { Calendar c = (Calendar) state.getAttribute(CALENDAR); String dueDateScheduled = a.getProperties().getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); String oldEventId = aPropertiesEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); CalendarEvent e = null; if (dueDateScheduled != null || oldEventId != null) { // find the old event boolean found = false; if (oldEventId != null && c != null) { try { e = c.getEvent(oldEventId); found = true; } catch (IdUnusedException ee) { Log.warn("chef", "The old event has been deleted: event id=" + oldEventId + ". "); } catch (PermissionException ee) { Log.warn("chef", "You do not have the permission to view the schedule event id= " + oldEventId + "."); } } else { TimeBreakdown b = oldDueTime.breakdownLocal(); // TODO: check- this was new Time(year...), not local! -ggolden Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0); Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999); try { Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null) .iterator(); while ((!found) && (events.hasNext())) { e = (CalendarEvent) events.next(); if (((String) e.getDisplayName()).indexOf(rb.getString("assig1") + " " + title) != -1) { found = true; } } } catch (PermissionException ignore) { // ignore PermissionException } } if (found) { // remove the founded old event try { c.removeEvent(c.getEditEvent(e.getId(), CalendarService.EVENT_REMOVE_CALENDAR)); } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotrem") + " " + title + ". "); } catch (InUseException ee) { Log.warn("chef", rb.getString("somelsis") + " " + rb.getString("calen")); } catch (IdUnusedException ee) { Log.warn("chef", rb.getString("cannotfin6") + e.getId()); } } } if (checkAddDueTime.equalsIgnoreCase(Boolean.TRUE.toString())) { if (c != null) { // commit related properties into Assignment object String ref = ""; try { ref = a.getReference(); AssignmentEdit aEdit = AssignmentService.editAssignment(ref); try { e = null; CalendarEvent.EventAccess eAccess = CalendarEvent.EventAccess.SITE; Collection eGroups = new Vector(); if (aEdit.getAccess().equals(Assignment.AssignmentAccess.GROUPED)) { eAccess = CalendarEvent.EventAccess.GROUPED; Collection groupRefs = aEdit.getGroups(); // make a collection of Group objects from the collection of group ref strings Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();) { String groupRef = (String) iGroupRefs.next(); eGroups.add(site.getGroup(groupRef)); } } e = c.addEvent(/* TimeRange */TimeService.newTimeRange(dueTime.getTime(), /* 0 duration */0 * 60 * 1000), /* title */rb.getString("due") + " " + title, /* description */rb.getString("assig1") + " " + title + " " + "is due on " + dueTime.toStringLocalFull() + ". ", /* type */rb.getString("deadl"), /* location */"", /* access */ eAccess, /* groups */ eGroups, /* attachments */EntityManager.newReferenceList()); aEdit.getProperties().addProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED, Boolean.TRUE.toString()); if (e != null) { aEdit.getProperties().addProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID, e.getId()); } } catch (IdUnusedException ee) { Log.warn("chef", ee.getMessage()); } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotfin1")); } catch (Exception ee) { Log.warn("chef", ee.getMessage()); } // try-catch AssignmentService.commitEdit(aEdit); } catch (Exception ignore) { // ignore the exception Log.warn("chef", rb.getString("cannotfin2") + ref); } } // if } // if } } private void commitAssignmentEdit(SessionState state, boolean post, AssignmentContentEdit ac, AssignmentEdit a, String title, Time openTime, Time dueTime, Time closeTime, boolean enableCloseDate, String s, String range, Collection groups) { a.setTitle(title); a.setContent(ac); a.setContext((String) state.getAttribute(STATE_CONTEXT_STRING)); a.setSection(s); a.setOpenTime(openTime); a.setDueTime(dueTime); // set the drop dead date as the due date a.setDropDeadTime(dueTime); if (enableCloseDate) { a.setCloseTime(closeTime); } else { // if editing an old assignment with close date if (a.getCloseTime() != null) { a.setCloseTime(null); } } // post the assignment a.setDraft(!post); try { if (range.equals("site")) { a.setAccess(Assignment.AssignmentAccess.SITE); a.clearGroupAccess(); } else if (range.equals("groups")) { a.setGroupAccess(groups); } } catch (PermissionException e) { addAlert(state, rb.getString("youarenot1")); } if (state.getAttribute(STATE_MESSAGE) == null) { // commit assignment first AssignmentService.commitEdit(a); } } private void editAssignmentProperties(AssignmentEdit a, String title, String checkAddDueTime, String checkAutoAnnounce, String addtoGradebook, String associateGradebookAssignment, String allowResubmitNumber, ResourcePropertiesEdit aPropertiesEdit) { if (aPropertiesEdit.getProperty("newAssignment") != null) { if (aPropertiesEdit.getProperty("newAssignment").equalsIgnoreCase(Boolean.TRUE.toString())) { // not a newly created assignment, been added. aPropertiesEdit.addProperty("newAssignment", Boolean.FALSE.toString()); } } else { // for newly created assignment aPropertiesEdit.addProperty("newAssignment", Boolean.TRUE.toString()); } if (checkAddDueTime != null) { aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, checkAddDueTime); } else { aPropertiesEdit.removeProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); } aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, checkAutoAnnounce); aPropertiesEdit.addProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, addtoGradebook); aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateGradebookAssignment); if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD)) { // if the choice is to add an entry into Gradebook, let just mark it as associated with such new entry then aPropertiesEdit.addProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE); aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, title); } // allow resubmit number if (allowResubmitNumber != null) { aPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber); } } private void commitAssignmentContentEdit(SessionState state, AssignmentContentEdit ac, String title, int submissionType,boolean useReviewService, boolean allowStudentViewReport, int gradeType, String gradePoints, String description, String checkAddHonorPledge, List attachments1) { ac.setTitle(title); ac.setInstructions(description); ac.setHonorPledge(Integer.parseInt(checkAddHonorPledge)); ac.setTypeOfSubmission(submissionType); ac.setAllowReviewService(useReviewService); ac.setAllowStudentViewReport(allowStudentViewReport); ac.setTypeOfGrade(gradeType); if (gradeType == 3) { try { ac.setMaxGradePoint(Integer.parseInt(gradePoints)); } catch (NumberFormatException e) { alertInvalidPoint(state, gradePoints); } } ac.setGroupProject(true); ac.setIndividuallyGraded(false); if (submissionType != 1) { ac.setAllowAttachments(true); } else { ac.setAllowAttachments(false); } // clear attachments ac.clearAttachments(); // add each attachment Iterator it = EntityManager.newReferenceList(attachments1).iterator(); while (it.hasNext()) { Reference r = (Reference) it.next(); ac.addAttachment(r); } state.setAttribute(ATTACHMENTS_MODIFIED, new Boolean(false)); // commit the changes AssignmentService.commitEdit(ac); } private AssignmentEdit getAssignmentEdit(SessionState state, String assignmentId) { AssignmentEdit a = null; if (assignmentId.length() == 0) { // create a new assignment try { a = AssignmentService.addAssignment((String) state.getAttribute(STATE_CONTEXT_STRING)); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot1")); } } else { try { // edit assignment a = AssignmentService.editAssignment(assignmentId); } catch (InUseException e) { addAlert(state, rb.getString("theassicon")); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } // try-catch } // if-else return a; } private AssignmentContentEdit getAssignmentContentEdit(SessionState state, String assignmentContentId) { AssignmentContentEdit ac = null; if (assignmentContentId.length() == 0) { // new assignment try { ac = AssignmentService.addAssignmentContent((String) state.getAttribute(STATE_CONTEXT_STRING)); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot3")); } } else { try { // edit assignment ac = AssignmentService.editAssignmentContent(assignmentContentId); } catch (InUseException e) { addAlert(state, rb.getString("theassicon")); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin4")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot15")); } } return ac; } private Time getOpenTime(SessionState state) { int openMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENMONTH)).intValue(); int openDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENDAY)).intValue(); int openYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENYEAR)).intValue(); int openHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENHOUR)).intValue(); int openMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENMIN)).intValue(); String openAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_OPENAMPM); if ((openAMPM.equals("PM")) && (openHour != 12)) { openHour = openHour + 12; } if ((openHour == 12) && (openAMPM.equals("AM"))) { openHour = 0; } Time openTime = TimeService.newTimeLocal(openYear, openMonth, openDay, openHour, openMin, 0, 0); return openTime; } private Time getCloseTime(SessionState state) { Time closeTime; int closeMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH)).intValue(); int closeDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY)).intValue(); int closeYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR)).intValue(); int closeHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR)).intValue(); int closeMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN)).intValue(); String closeAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); return closeTime; } private Time getDueTime(SessionState state) { int dueMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)).intValue(); int dueDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEDAY)).intValue(); int dueYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)).intValue(); int dueHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)).intValue(); int dueMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMIN)).intValue(); String dueAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_DUEAMPM); if ((dueAMPM.equals("PM")) && (dueHour != 12)) { dueHour = dueHour + 12; } if ((dueHour == 12) && (dueAMPM.equals("AM"))) { dueHour = 0; } Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0); return dueTime; } private Time getAllowSubmitCloseTime(SessionState state) { int closeMonth = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEMONTH)).intValue(); int closeDay = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEDAY)).intValue(); int closeYear = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR)).intValue(); int closeHour = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEHOUR)).intValue(); int closeMin = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEMIN)).intValue(); String closeAMPM = (String) state.getAttribute(ALLOW_RESUBMIT_CLOSEAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); return closeTime; } /** * Action is to post new assignment */ public void doSave_assignment(RunData data) { postOrSaveAssignment(data, "save"); } // doSave_assignment /** * Action is to preview the selected assignment */ public void doPreview_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); setNewAssignmentParameters(data, false); String assignmentId = data.getParameters().getString("assignmentId"); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID, assignmentId); String assignmentContentId = data.getParameters().getString("assignmentContentId"); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID, assignmentContentId); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(false)); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(true)); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT); } } // doPreview_assignment /** * Action is to view the selected assignment */ public void doView_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // show the assignment portion state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(false)); // show the student view portion state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(true)); String assignmentId = params.getString("assignmentId"); state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId); try { Assignment a = AssignmentService.getAssignment(assignmentId); EventTrackingService.post(EventTrackingService.newEvent(AssignmentService.SECURE_ACCESS_ASSIGNMENT, a.getReference(), false)); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_ASSIGNMENT); } } // doView_Assignment /** * Action is for student to view one assignment content */ public void doView_assignment_as_student(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = params.getString("assignmentId"); state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_ASSIGNMENT); } } // doView_assignment_as_student /** * Action is to show the edit assignment screen */ public void doEdit_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = StringUtil.trimToNull(params.getString("assignmentId")); // whether the user can modify the assignment state.setAttribute(EDIT_ASSIGNMENT_ID, assignmentId); try { Assignment a = AssignmentService.getAssignment(assignmentId); // for the non_electronice assignment, submissions are auto-generated by the time that assignment is created; // don't need to go through the following checkings. if (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { Iterator submissions = AssignmentService.getSubmissions(a).iterator(); if (submissions.hasNext()) { boolean anySubmitted = false; for (;submissions.hasNext() && !anySubmitted;) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (s.getSubmitted()) { anySubmitted = true; } } if (anySubmitted) { // if there is any submitted submission to this assignment, show alert addAlert(state, rb.getString("assig1") + " " + a.getTitle() + " " + rb.getString("hassum")); } else { // otherwise, show alert about someone has started working on the assignment, not necessarily submitted addAlert(state, rb.getString("hasDraftSum")); } } } // SECTION MOD state.setAttribute(STATE_SECTION_STRING, a.getSection()); // put the names and values into vm file state.setAttribute(NEW_ASSIGNMENT_TITLE, a.getTitle()); TimeBreakdown openTime = a.getOpenTime().breakdownLocal(); state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(openTime.getMonth())); state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(openTime.getDay())); state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(openTime.getYear())); int openHour = openTime.getHour(); if (openHour >= 12) { state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "PM"); } else { state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "AM"); } if (openHour == 0) { // for midnight point, we mark it as 12AM openHour = 12; } state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer((openHour > 12) ? openHour - 12 : openHour)); state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(openTime.getMin())); TimeBreakdown dueTime = a.getDueTime().breakdownLocal(); state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(dueTime.getMonth())); state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(dueTime.getDay())); state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(dueTime.getYear())); int dueHour = dueTime.getHour(); if (dueHour >= 12) { state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "PM"); } else { state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "AM"); } if (dueHour == 0) { // for midnight point, we mark it as 12AM dueHour = 12; } state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer((dueHour > 12) ? dueHour - 12 : dueHour)); state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(dueTime.getMin())); // generate alert when editing an assignment past due date if (a.getDueTime().before(TimeService.newTime())) { addAlert(state, rb.getString("youarenot17")); } if (a.getCloseTime() != null) { state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true)); TimeBreakdown closeTime = a.getCloseTime().breakdownLocal(); state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(closeTime.getMonth())); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(closeTime.getDay())); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(closeTime.getYear())); int closeHour = closeTime.getHour(); if (closeHour >= 12) { state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "PM"); } else { state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "AM"); } if (closeHour == 0) { // for the midnight point, we mark it as 12 AM closeHour = 12; } state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer((closeHour > 12) ? closeHour - 12 : closeHour)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(closeTime.getMin())); } else { state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(false)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, state.getAttribute(NEW_ASSIGNMENT_DUEDAY)); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, state.getAttribute(NEW_ASSIGNMENT_DUEMIN)); state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, state.getAttribute(NEW_ASSIGNMENT_DUEAMPM)); } state.setAttribute(NEW_ASSIGNMENT_SECTION, a.getSection()); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(a.getContent().getTypeOfSubmission())); int typeOfGrade = a.getContent().getTypeOfGrade(); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(typeOfGrade)); if (typeOfGrade == 3) { state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, a.getContent().getMaxGradePointDisplay()); } state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, a.getContent().getInstructions()); ResourceProperties properties = a.getProperties(); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, properties.getProperty( ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, properties.getProperty( ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, Integer.toString(a.getContent().getHonorPledge())); state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, properties.getProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, properties.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); state.setAttribute(ATTACHMENTS, a.getContent().getAttachments()); // notification option if (properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null) { state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); } // group setting if (a.getAccess().equals(Assignment.AssignmentAccess.SITE)) { state.setAttribute(NEW_ASSIGNMENT_RANGE, "site"); } else { state.setAttribute(NEW_ASSIGNMENT_RANGE, "groups"); } state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, properties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null?properties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER):"0"); // set whether we use the review service or not state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE, new Boolean(a.getContent().getAllowReviewService()).toString()); //set whether students can view the review service results state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW, new Boolean(a.getContent().getAllowStudentViewReport()).toString()); state.setAttribute(NEW_ASSIGNMENT_GROUPS, a.getGroups()); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } // doEdit_Assignment /** * Action is to show the delete assigment confirmation screen */ public void doDelete_confirm_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String[] assignmentIds = params.getStrings("selectedAssignments"); if (assignmentIds != null) { Vector ids = new Vector(); for (int i = 0; i < assignmentIds.length; i++) { String id = (String) assignmentIds[i]; if (!AssignmentService.allowRemoveAssignment(id)) { addAlert(state, rb.getString("youarenot9") + " " + id + ". "); } ids.add(id); } if (state.getAttribute(STATE_MESSAGE) == null) { // can remove all the selected assignments state.setAttribute(DELETE_ASSIGNMENT_IDS, ids); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_DELETE_ASSIGNMENT); } } else { addAlert(state, rb.getString("youmust6")); } } // doDelete_confirm_Assignment /** * Action is to delete the confirmed assignments */ public void doDelete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the delete assignment ids Vector ids = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < ids.size(); i++) { String assignmentId = (String) ids.get(i); try { AssignmentEdit aEdit = AssignmentService.editAssignment(assignmentId); ResourcePropertiesEdit pEdit = aEdit.getPropertiesEdit(); String associateGradebookAssignment = pEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); String title = aEdit.getTitle(); // remove releted event if there is one String isThereEvent = pEdit.getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); if (isThereEvent != null && isThereEvent.equals(Boolean.TRUE.toString())) { removeCalendarEvent(state, aEdit, pEdit, title); } // if-else if (!AssignmentService.getSubmissions(aEdit).iterator().hasNext()) { // there is no submission to this assignment yet, delete the assignment record completely try { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); if (taggingManager.isTaggable()) { for (TaggingProvider provider : taggingManager .getProviders()) { provider.removeTags(assignmentActivityProducer .getActivity(aEdit)); } } AssignmentService.removeAssignment(aEdit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot11") + " " + aEdit.getTitle() + ". "); } } else { // remove the assignment by marking the remove status property true pEdit.addProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED, Boolean.TRUE.toString()); AssignmentService.commitEdit(aEdit); } // remove from Gradebook AssignmentService.integrateGradebook((String) ids.get (i), associateGradebookAssignment, null, AssignmentService.GRADEBOOK_INTEGRATION_NO, null, null, -1, null, null, "remove"); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("assig2")); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot6")); } } // for if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } // doDelete_Assignment private void removeCalendarEvent(SessionState state, AssignmentEdit aEdit, ResourcePropertiesEdit pEdit, String title) throws PermissionException { // remove the associated calender event Calendar c = (Calendar) state.getAttribute(CALENDAR); if (c != null) { // already has calendar object // get the old event CalendarEvent e = null; boolean found = false; String oldEventId = pEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); if (oldEventId != null) { try { e = c.getEvent(oldEventId); found = true; } catch (IdUnusedException ee) { // no action needed for this condition } catch (PermissionException ee) { } } else { TimeBreakdown b = aEdit.getDueTime().breakdownLocal(); // TODO: check- this was new Time(year...), not local! -ggolden Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0); Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999); Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null).iterator(); while ((!found) && (events.hasNext())) { e = (CalendarEvent) events.next(); if (((String) e.getDisplayName()).indexOf(rb.getString("assig1") + " " + title) != -1) { found = true; } } } // remove the founded old event if (found) { // found the old event delete it try { c.removeEvent(c.getEditEvent(e.getId(), CalendarService.EVENT_REMOVE_CALENDAR)); pEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); pEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotrem") + " " + title + ". "); } catch (InUseException ee) { Log.warn("chef", rb.getString("somelsis") + " " + rb.getString("calen")); } catch (IdUnusedException ee) { Log.warn("chef", rb.getString("cannotfin6") + e.getId()); } } } } /** * Action is to delete the assignment and also the related AssignmentSubmission */ public void doDeep_delete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the delete assignment ids Vector ids = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < ids.size(); i++) { String currentId = (String) ids.get(i); try { AssignmentEdit a = AssignmentService.editAssignment(currentId); try { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); if (taggingManager.isTaggable()) { for (TaggingProvider provider : taggingManager .getProviders()) { provider.removeTags(assignmentActivityProducer .getActivity(a)); } } AssignmentService.removeAssignment(a); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot11") + " " + a.getTitle() + ". "); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("assig2")); } } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } // doDeep_delete_Assignment /** * Action is to show the duplicate assignment screen */ public void doDuplicate_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the view, so start with first page again. resetPaging(state); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); ParameterParser params = data.getParameters(); String assignmentId = StringUtil.trimToNull(params.getString("assignmentId")); if (assignmentId != null) { try { AssignmentEdit aEdit = AssignmentService.addDuplicateAssignment(contextString, assignmentId); // clean the duplicate's property ResourcePropertiesEdit aPropertiesEdit = aEdit.getPropertiesEdit(); aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED); aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID); AssignmentService.commitEdit(aEdit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot5")); } catch (IdInvalidException e) { addAlert(state, rb.getString("theassiid") + " " + assignmentId + " " + rb.getString("isnotval")); } catch (IdUnusedException e) { addAlert(state, rb.getString("theassiid") + " " + assignmentId + " " + rb.getString("hasnotbee")); } catch (Exception e) { } } } // doDuplicate_Assignment /** * Action is to show the grade submission screen */ public void doGrade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the submission context resetViewSubmission(state); ParameterParser params = data.getParameters(); // reset the grade assignment id state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID, params.getString("assignmentId")); state.setAttribute(GRADE_SUBMISSION_SUBMISSION_ID, params.getString("submissionId")); // allow resubmit number String allowResubmitNumber = "0"; Assignment a = null; try { a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); if (a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { allowResubmitNumber= a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } try { AssignmentSubmission s = AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID)); if ((s.getFeedbackText() != null) && (s.getFeedbackText().length() == 0)) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getSubmittedText()); } else { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getFeedbackText()); } state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, s.getFeedbackComment()); List v = EntityManager.newReferenceList(); Iterator attachments = s.getFeedbackAttachments().iterator(); while (attachments.hasNext()) { v.add(attachments.next()); } state.setAttribute(ATTACHMENTS, v); state.setAttribute(GRADE_SUBMISSION_GRADE, s.getGrade()); ResourceProperties p = s.getProperties(); if (p.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { allowResubmitNumber = p.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); } else if (p.getProperty(GRADE_SUBMISSION_ALLOW_RESUBMIT) != null) { // if there is any legacy setting for generally allow resubmit, set the allow resubmit number to be 1, and remove the legacy property allowResubmitNumber = "1"; } state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION); } } // doGrade_submission /** * Action is to release all the grades of the submission */ public void doRelease_grades(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); try { // get the assignment Assignment a = AssignmentService.getAssignment(params.getString("assignmentId")); String aReference = a.getReference(); Iterator submissions = AssignmentService.getSubmissions(a).iterator(); while (submissions.hasNext()) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (s.getGraded()) { AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(s.getReference()); String grade = s.getGrade(); boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)) .booleanValue() : false; if (withGrade) { // for the assignment tool with grade option, a valide grade is needed if (grade != null && !grade.equals("")) { sEdit.setGradeReleased(true); } } else { // for the assignment tool without grade option, no grade is needed sEdit.setGradeReleased(true); } // also set the return status sEdit.setReturned(true); sEdit.setTimeReturned(TimeService.newTime()); sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue()); AssignmentService.commitEdit(sEdit); } } // while // add grades into Gradebook String integrateWithGradebook = a.getProperties().getProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); if (integrateWithGradebook != null && !integrateWithGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // integrate with Gradebook String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); AssignmentService.integrateGradebook(aReference, associateGradebookAssignment, null, null, a.getTitle(), a.getTitle(), -1, null, null, "update"); // set the gradebook assignment to be released to student AssignmentService.releaseGradebookAssignment(associateGradebookAssignment, true); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } } // doRelease_grades /** * Action is to show the assignment in grading page */ public void doExpand_grade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(true)); } // doExpand_grade_assignment /** * Action is to hide the assignment in grading page */ public void doCollapse_grade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); } // doCollapse_grade_assignment /** * Action is to show the submissions in grading page */ public void doExpand_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(true)); } // doExpand_grade_submission /** * Action is to hide the submissions in grading page */ public void doCollapse_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(false)); } // doCollapse_grade_submission /** * Action is to show the grade assignment */ public void doGrade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // clean state attribute state.removeAttribute(USER_SUBMISSIONS); state.setAttribute(EXPORT_ASSIGNMENT_REF, params.getString("assignmentId")); try { Assignment a = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); state.setAttribute(EXPORT_ASSIGNMENT_ID, a.getId()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(true)); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); // we are changing the view, so start with first page again. resetPaging(state); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } // doGrade_assignment /** * Action is to show the View Students assignment screen */ public void doView_students_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); } // doView_students_Assignment /** * Action is to show the student submissions */ public void doShow_student_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); ParameterParser params = data.getParameters(); String id = params.getString("studentId"); // add the student id into the table t.add(id); state.setAttribute(STUDENT_LIST_SHOW_TABLE, t); } // doShow_student_submission /** * Action is to hide the student submissions */ public void doHide_student_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); ParameterParser params = data.getParameters(); String id = params.getString("studentId"); // remove the student id from the table t.remove(id); state.setAttribute(STUDENT_LIST_SHOW_TABLE, t); } // doHide_student_submission /** * Action is to show the graded assignment submission */ public void doView_grade(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.setAttribute(VIEW_GRADE_SUBMISSION_ID, params.getString("submissionId")); state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_GRADE); } // doView_grade /** * Action is to show the student submissions */ public void doReport_submissions(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REPORT_SUBMISSIONS); state.setAttribute(SORTED_BY, SORTED_SUBMISSION_BY_LASTNAME); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doReport_submissions /** * * */ public void doAssignment_form(RunData data) { ParameterParser params = data.getParameters(); String option = (String) params.getString("option"); if (option != null) { if (option.equals("post")) { // post assignment doPost_assignment(data); } else if (option.equals("save")) { // save assignment doSave_assignment(data); } else if (option.equals("preview")) { // preview assignment doPreview_assignment(data); } else if (option.equals("cancel")) { // cancel creating assignment doCancel_new_assignment(data); } else if (option.equals("canceledit")) { // cancel editing assignment doCancel_edit_assignment(data); } else if (option.equals("attach")) { // attachments doAttachments(data); } else if (option.equals("view")) { // view doView(data); } else if (option.equals("permissions")) { // permissions doPermissions(data); } else if (option.equals("returngrade")) { // return grading doReturn_grade_submission(data); } else if (option.equals("savegrade")) { // save grading doSave_grade_submission(data); } else if (option.equals("previewgrade")) { // preview grading doPreview_grade_submission(data); } else if (option.equals("cancelgrade")) { // cancel grading doCancel_grade_submission(data); } else if (option.equals("sortbygrouptitle")) { // read input data setNewAssignmentParameters(data, true); // sort by group title doSortbygrouptitle(data); } else if (option.equals("sortbygroupdescription")) { // read input data setNewAssignmentParameters(data, true); // sort group by description doSortbygroupdescription(data); } else if (option.equals("hide_instruction")) { // hide the assignment instruction doHide_submission_assignment_instruction(data); } else if (option.equals("show_instruction")) { // show the assignment instruction doShow_submission_assignment_instruction(data); } else if (option.equals("sortbygroupdescription")) { // show the assignment instruction doShow_submission_assignment_instruction(data); } } } /** * Action is to use when doAattchmentsadding requested, corresponding to chef_Assignments-new "eventSubmit_doAattchmentsadding" when "add attachments" is clicked */ public void doAttachments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String mode = (String) state.getAttribute(STATE_MODE); if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION)) { // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(VIEW_SUBMISSION_TEXT, text); if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null) { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true"); } // TODO: file picker to save in dropbox? -ggolden // User[] users = { UserDirectoryService.getCurrentUser() }; // state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users); } else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT)) { setNewAssignmentParameters(data, false); } else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION)) { readGradeForm(data, state, "read"); } if (state.getAttribute(STATE_MESSAGE) == null) { // get into helper mode with this helper tool startHelper(data.getRequest(), "sakai.filepicker"); state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatttoassig")); state.setAttribute(FilePickerHelper.FILE_PICKER_INSTRUCTION_TEXT, rb.getString("gen.addatttoassiginstr")); // use the real attachment list state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, state.getAttribute(ATTACHMENTS)); } } /** * readGradeForm */ public void readGradeForm(RunData data, SessionState state, String gradeOption) { ParameterParser params = data.getParameters(); boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue() : false; boolean checkForFormattingErrors = false; // so that grading isn't held up by formatting errors String feedbackComment = processFormattedTextFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_COMMENT), checkForFormattingErrors); if (feedbackComment != null) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, feedbackComment); } String feedbackText = processAssignmentFeedbackFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_TEXT)); if (feedbackText != null) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, feedbackText); } state.setAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT, state.getAttribute(ATTACHMENTS)); String g = params.getCleanString(GRADE_SUBMISSION_GRADE); if (g != null) { state.setAttribute(GRADE_SUBMISSION_GRADE, g); } String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID); try { // for points grading, one have to enter number as the points String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); Assignment a = AssignmentService.getSubmission(sId).getAssignment(); int typeOfGrade = a.getContent().getTypeOfGrade(); if (withGrade) { // do grade validation only for Assignment with Grade tool if (typeOfGrade == 3) { if ((grade.length() == 0)) { if (gradeOption.equals("release") || gradeOption.equals("return")) { // in case of releasing grade, user must specify a grade addAlert(state, rb.getString("plespethe2")); } } else { // the preview grade process might already scaled up the grade by 10 if (!((String) state.getAttribute(STATE_MODE)).equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION)) { validPointGrade(state, grade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getString("grad2")); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, grade); } } if (state.getAttribute(STATE_MESSAGE) == null) { grade = scalePointGrade(state, grade); } state.setAttribute(GRADE_SUBMISSION_GRADE, grade); } } } // if ungraded and grade type is not "ungraded" type if ((grade == null || grade.equals("ungraded")) && (typeOfGrade != 1) && gradeOption.equals("release")) { addAlert(state, rb.getString("plespethe2")); } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } // allow resubmit number and due time if (params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { String allowResubmitNumberString = params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); if (Integer.parseInt(allowResubmitNumberString) != 0) { int closeMonth = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEMONTH))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEMONTH, new Integer(closeMonth)); int closeDay = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEDAY))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEDAY, new Integer(closeDay)); int closeYear = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEYEAR))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEYEAR, new Integer(closeYear)); int closeHour = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEHOUR))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEHOUR, new Integer(closeHour)); int closeMin = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEMIN))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEMIN, new Integer(closeMin)); String closeAMPM = params.getString(ALLOW_RESUBMIT_CLOSEAMPM); state.setAttribute(ALLOW_RESUBMIT_CLOSEAMPM, closeAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime())); // validate date if (closeTime.before(TimeService.newTime())) { addAlert(state, rb.getString("assig4")); } if (!Validator.checkDate(closeDay, closeMonth, closeYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.closedate") + "."); } } else { // reset the state attributes state.removeAttribute(ALLOW_RESUBMIT_CLOSEMONTH); state.removeAttribute(ALLOW_RESUBMIT_CLOSEDAY); state.removeAttribute(ALLOW_RESUBMIT_CLOSEYEAR); state.removeAttribute(ALLOW_RESUBMIT_CLOSEHOUR); state.removeAttribute(ALLOW_RESUBMIT_CLOSEMIN); state.removeAttribute(ALLOW_RESUBMIT_CLOSEAMPM); state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } } } /** * Populate the state object, if needed - override to do something! */ protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData data) { super.initState(state, portlet, data); String siteId = ToolManager.getCurrentPlacement().getContext(); // show the list of assignment view first if (state.getAttribute(STATE_SELECTED_VIEW) == null) { state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS); } if (state.getAttribute(STATE_USER) == null) { state.setAttribute(STATE_USER, UserDirectoryService.getCurrentUser()); } /** The content type image lookup service in the State. */ ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE); if (iService == null) { iService = org.sakaiproject.content.cover.ContentTypeImageService.getInstance(); state.setAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE, iService); } // if /** The calendar service in the State. */ CalendarService cService = (CalendarService) state.getAttribute(STATE_CALENDAR_SERVICE); if (cService == null) { cService = org.sakaiproject.calendar.cover.CalendarService.getInstance(); state.setAttribute(STATE_CALENDAR_SERVICE, cService); String calendarId = ServerConfigurationService.getString("calendar", null); if (calendarId == null) { calendarId = cService.calendarReference(siteId, SiteService.MAIN_CONTAINER); try { state.setAttribute(CALENDAR, cService.getCalendar(calendarId)); } catch (IdUnusedException e) { Log.info("chef", "No calendar found for site " + siteId); state.removeAttribute(CALENDAR); } catch (PermissionException e) { Log.info("chef", "No permission to get the calender. "); state.removeAttribute(CALENDAR); } catch (Exception ex) { Log.info("chef", "Assignment : Action : init state : calendar exception : " + ex); state.removeAttribute(CALENDAR); } } } // if /** The announcement service in the State. */ AnnouncementService aService = (AnnouncementService) state.getAttribute(STATE_ANNOUNCEMENT_SERVICE); if (aService == null) { aService = org.sakaiproject.announcement.cover.AnnouncementService.getInstance(); state.setAttribute(STATE_ANNOUNCEMENT_SERVICE, aService); String channelId = ServerConfigurationService.getString("channel", null); if (channelId == null) { channelId = aService.channelReference(siteId, SiteService.MAIN_CONTAINER); try { state.setAttribute(ANNOUNCEMENT_CHANNEL, aService.getAnnouncementChannel(channelId)); } catch (IdUnusedException e) { Log.warn("chef", "No announcement channel found. "); state.removeAttribute(ANNOUNCEMENT_CHANNEL); } catch (PermissionException e) { Log.warn("chef", "No permission to annoucement channel. "); } catch (Exception ex) { Log.warn("chef", "Assignment : Action : init state : calendar exception : " + ex); } } } // if if (state.getAttribute(STATE_CONTEXT_STRING) == null) { state.setAttribute(STATE_CONTEXT_STRING, siteId); } // if context string is null if (state.getAttribute(SORTED_BY) == null) { state.setAttribute(SORTED_BY, SORTED_BY_DUEDATE); } if (state.getAttribute(SORTED_ASC) == null) { state.setAttribute(SORTED_ASC, Boolean.FALSE.toString()); } if (state.getAttribute(SORTED_GRADE_SUBMISSION_BY) == null) { state.setAttribute(SORTED_GRADE_SUBMISSION_BY, SORTED_GRADE_SUBMISSION_BY_LASTNAME); } if (state.getAttribute(SORTED_GRADE_SUBMISSION_ASC) == null) { state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, Boolean.TRUE.toString()); } if (state.getAttribute(SORTED_SUBMISSION_BY) == null) { state.setAttribute(SORTED_SUBMISSION_BY, SORTED_SUBMISSION_BY_LASTNAME); } if (state.getAttribute(SORTED_SUBMISSION_ASC) == null) { state.setAttribute(SORTED_SUBMISSION_ASC, Boolean.TRUE.toString()); } if (state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG) == null) { resetAssignment(state); } if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) == null) { state.setAttribute(STUDENT_LIST_SHOW_TABLE, new HashSet()); } if (state.getAttribute(ATTACHMENTS_MODIFIED) == null) { state.setAttribute(ATTACHMENTS_MODIFIED, new Boolean(false)); } // SECTION MOD if (state.getAttribute(STATE_SECTION_STRING) == null) { state.setAttribute(STATE_SECTION_STRING, "001"); } // // setup the observer to notify the Main panel // if (state.getAttribute(STATE_OBSERVER) == null) // { // // the delivery location for this tool // String deliveryId = clientWindowId(state, portlet.getID()); // // // the html element to update on delivery // String elementId = mainPanelUpdateId(portlet.getID()); // // // the event resource reference pattern to watch for // String pattern = AssignmentService.assignmentReference((String) state.getAttribute (STATE_CONTEXT_STRING), ""); // // state.setAttribute(STATE_OBSERVER, new MultipleEventsObservingCourier(deliveryId, elementId, pattern)); // } if (state.getAttribute(STATE_MODE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null) { state.setAttribute(STATE_TOP_PAGE_MESSAGE, new Integer(0)); } if (state.getAttribute(WITH_GRADES) == null) { PortletConfig config = portlet.getPortletConfig(); String withGrades = StringUtil.trimToNull(config.getInitParameter("withGrades")); if (withGrades == null) { withGrades = Boolean.FALSE.toString(); } state.setAttribute(WITH_GRADES, new Boolean(withGrades)); } // whether the choice of emails instructor submission notification is available in the installation if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS) == null) { state.setAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS, Boolean.valueOf(ServerConfigurationService.getBoolean(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS, true))); } // whether or how the instructor receive submission notification emails, none(default)|each|digest if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT) == null) { state.setAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT, ServerConfigurationService.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT, Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE)); } if (state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM) == null) { state.setAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM, new Integer(2002)); } if (state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO) == null) { state.setAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO, new Integer(2012)); } } // initState /** * reset the attributes for view submission */ private void resetViewSubmission(SessionState state) { state.removeAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); state.removeAttribute(VIEW_SUBMISSION_TEXT); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false"); state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } // resetViewSubmission /** * reset the attributes for view submission */ private void resetAssignment(SessionState state) { // put the input value into the state attributes state.setAttribute(NEW_ASSIGNMENT_TITLE, ""); // get current time Time t = TimeService.newTime(); TimeBreakdown tB = t.breakdownLocal(); int month = tB.getMonth(); int day = tB.getDay(); int year = tB.getYear(); // set the open time to be 12:00 PM state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(month)); state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(day)); state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(year)); state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer(12)); state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(0)); state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "PM"); // due date is shifted forward by 7 days t.setTime(t.getTime() + 7 * 24 * 60 * 60 * 1000); tB = t.breakdownLocal(); month = tB.getMonth(); day = tB.getDay(); year = tB.getYear(); // set the due time to be 5:00pm state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(month)); state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(day)); state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(year)); state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer(5)); state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(0)); state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "PM"); // enable the close date by default state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true)); // set the close time to be 5:00 pm, same as the due time by default state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(month)); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(day)); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(year)); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer(5)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(0)); state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "PM"); state.setAttribute(NEW_ASSIGNMENT_SECTION, "001"); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION)); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(Assignment.UNGRADED_GRADE_TYPE)); state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, ""); state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, ""); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString()); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString()); // make the honor pledge not include as the default state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, (new Integer(Assignment.HONOR_PLEDGE_NONE)).toString()); state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO); state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, EntityManager.newReferenceList()); state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(false)); state.setAttribute(NEW_ASSIGNMENT_FOCUS, NEW_ASSIGNMENT_TITLE); state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } state.setAttribute(NEW_ASSIGNMENT_RANGE, "site"); state.removeAttribute(NEW_ASSIGNMENT_GROUPS); // remove the edit assignment id if any state.removeAttribute(EDIT_ASSIGNMENT_ID); } // resetNewAssignment /** * construct a Hashtable using integer as the key and three character string of the month as the value */ private Hashtable monthTable() { Hashtable n = new Hashtable(); n.put(new Integer(1), rb.getString("jan")); n.put(new Integer(2), rb.getString("feb")); n.put(new Integer(3), rb.getString("mar")); n.put(new Integer(4), rb.getString("apr")); n.put(new Integer(5), rb.getString("may")); n.put(new Integer(6), rb.getString("jun")); n.put(new Integer(7), rb.getString("jul")); n.put(new Integer(8), rb.getString("aug")); n.put(new Integer(9), rb.getString("sep")); n.put(new Integer(10), rb.getString("oct")); n.put(new Integer(11), rb.getString("nov")); n.put(new Integer(12), rb.getString("dec")); return n; } // monthTable /** * construct a Hashtable using the integer as the key and grade type String as the value */ private Hashtable gradeTypeTable() { Hashtable n = new Hashtable(); n.put(new Integer(2), rb.getString("letter")); n.put(new Integer(3), rb.getString("points")); n.put(new Integer(4), rb.getString("pass")); n.put(new Integer(5), rb.getString("check")); n.put(new Integer(1), rb.getString("ungra")); return n; } // gradeTypeTable /** * construct a Hashtable using the integer as the key and submission type String as the value */ private Hashtable submissionTypeTable() { Hashtable n = new Hashtable(); n.put(new Integer(1), rb.getString("inlin")); n.put(new Integer(2), rb.getString("attaonly")); n.put(new Integer(3), rb.getString("inlinatt")); n.put(new Integer(4), rb.getString("nonelec")); return n; } // submissionTypeTable /** * Sort based on the given property */ public void doSort(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); setupSort(data, data.getParameters().getString("criteria")); } /** * setup sorting parameters * * @param criteria * String for sortedBy */ private void setupSort(RunData data, String criteria) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_BY))) { state.setAttribute(SORTED_BY, criteria); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, asc); } else { // current sorting sequence asc = (String) state.getAttribute(SORTED_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_ASC, asc); } } // doSort /** * Do sort by group title */ public void doSortbygrouptitle(RunData data) { setupSort(data, SORTED_BY_GROUP_TITLE); } // doSortbygrouptitle /** * Do sort by group description */ public void doSortbygroupdescription(RunData data) { setupSort(data, SORTED_BY_GROUP_DESCRIPTION); } // doSortbygroupdescription /** * Sort submission based on the given property */ public void doSort_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); // get the ParameterParser from RunData ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_SUBMISSION_BY))) { state.setAttribute(SORTED_SUBMISSION_BY, criteria); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_SUBMISSION_ASC, asc); } else { // current sorting sequence state.setAttribute(SORTED_SUBMISSION_BY, criteria); asc = (String) state.getAttribute(SORTED_SUBMISSION_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_SUBMISSION_ASC, asc); } } // doSort_submission /** * Sort submission based on the given property in instructor grade view */ public void doSort_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); // get the ParameterParser from RunData ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_GRADE_SUBMISSION_BY))) { state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc); } else { // current sorting sequence state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria); asc = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc); } } // doSort_grade_submission public void doSort_tags(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); String providerId = params.getString(PROVIDER_ID); String savedText = params.getString("savedText"); state.setAttribute(VIEW_SUBMISSION_TEXT, savedText); String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); for (DecoratedTaggingProvider dtp : providers) { if (dtp.getProvider().getId().equals(providerId)) { Sort sort = dtp.getSort(); if (sort.getSort().equals(criteria)) { sort.setAscending(sort.isAscending() ? false : true); } else { sort.setSort(criteria); sort.setAscending(true); } break; } } } public void doPage_tags(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String page = params.getString("page"); String pageSize = params.getString("pageSize"); String providerId = params.getString(PROVIDER_ID); String savedText = params.getString("savedText"); state.setAttribute(VIEW_SUBMISSION_TEXT, savedText); String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); for (DecoratedTaggingProvider dtp : providers) { if (dtp.getProvider().getId().equals(providerId)) { Pager pager = dtp.getPager(); pager.setPageSize(Integer.valueOf(pageSize)); if (Pager.FIRST.equals(page)) { pager.setFirstItem(0); } else if (Pager.PREVIOUS.equals(page)) { pager.setFirstItem(pager.getFirstItem() - pager.getPageSize()); } else if (Pager.NEXT.equals(page)) { pager.setFirstItem(pager.getFirstItem() + pager.getPageSize()); } else if (Pager.LAST.equals(page)) { pager.setFirstItem((pager.getTotalItems() / pager .getPageSize()) * pager.getPageSize()); } break; } } } /** * the UserSubmission clas */ public class UserSubmission { /** * the User object */ User m_user = null; /** * the AssignmentSubmission object */ AssignmentSubmission m_submission = null; public UserSubmission(User u, AssignmentSubmission s) { m_user = u; m_submission = s; } /** * Returns the AssignmentSubmission object */ public AssignmentSubmission getSubmission() { return m_submission; } /** * Returns the User object */ public User getUser() { return m_user; } } /** * the AssignmentComparator clas */ private class AssignmentComparator implements Comparator { /** * the SessionState object */ SessionState m_state = null; /** * the criteria */ String m_criteria = null; /** * the criteria */ String m_asc = null; /** * the user */ User m_user = null; /** * constructor * * @param state * The state object * @param criteria * The sort criteria string * @param asc * The sort order string. TRUE_STRING if ascending; "false" otherwise. */ public AssignmentComparator(SessionState state, String criteria, String asc) { m_state = state; m_criteria = criteria; m_asc = asc; } // constructor /** * constructor * * @param state * The state object * @param criteria * The sort criteria string * @param asc * The sort order string. TRUE_STRING if ascending; "false" otherwise. * @param user * The user object */ public AssignmentComparator(SessionState state, String criteria, String asc, User user) { m_state = state; m_criteria = criteria; m_asc = asc; m_user = user; } // constructor /** * caculate the range string for an assignment */ private String getAssignmentRange(Assignment a) { String rv = ""; if (a.getAccess().equals(Assignment.AssignmentAccess.SITE)) { // site assignment rv = rb.getString("range.allgroups"); } else { try { // get current site Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext()); for (Iterator k = a.getGroups().iterator(); k.hasNext();) { // announcement by group rv = rv.concat(site.getGroup((String) k.next()).getTitle()); } } catch (Exception ignore) { } } return rv; } // getAssignmentRange /** * implementing the compare function * * @param o1 * The first object * @param o2 * The second object * @return The compare result. 1 is o1 < o2; -1 otherwise */ public int compare(Object o1, Object o2) { int result = -1; /** *********** fo sorting assignments ****************** */ if (m_criteria.equals(SORTED_BY_TITLE)) { // sorted by the assignment title String s1 = ((Assignment) o1).getTitle(); String s2 = ((Assignment) o2).getTitle(); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_SECTION)) { // sorted by the assignment section String s1 = ((Assignment) o1).getSection(); String s2 = ((Assignment) o2).getSection(); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_DUEDATE)) { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_OPENDATE)) { // sorted by the assignment open Time t1 = ((Assignment) o1).getOpenTime(); Time t2 = ((Assignment) o2).getOpenTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS)) { String s1 = getAssignmentStatus((Assignment) o1); String s2 = getAssignmentStatus((Assignment) o2); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS)) { // sort by numbers of submissions // initialize int subNum1 = 0; int subNum2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator(); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted()) subNum1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator(); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted()) subNum2++; } result = (subNum1 > subNum2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED)) { // sort by numbers of ungraded submissions // initialize int ungraded1 = 0; int ungraded2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator(); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator(); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++; } result = (ungraded1 > ungraded2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_SUBMISSION_STATUS)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String status1 = getSubmissionStatus(submission1, (Assignment) o1); AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String status2 = getSubmissionStatus(submission2, (Assignment) o2); result = status1.compareTo(status2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_GRADE)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String grade1 = " "; if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased()) { grade1 = submission1.getGrade(); } AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String grade2 = " "; if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased()) { grade2 = submission2.getGrade(); } result = grade1.compareTo(grade2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_MAX_GRADE)) { String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1); String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } // group related sorting else if (m_criteria.equals(SORTED_BY_FOR)) { // sorted by the public view attribute String factor1 = getAssignmentRange((Assignment) o1); String factor2 = getAssignmentRange((Assignment) o2); result = factor1.compareToIgnoreCase(factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_TITLE)) { // sorted by the group title String factor1 = ((Group) o1).getTitle(); String factor2 = ((Group) o2).getTitle(); result = factor1.compareToIgnoreCase(factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION)) { // sorted by the group description String factor1 = ((Group) o1).getDescription(); String factor2 = ((Group) o2).getDescription(); if (factor1 == null) { factor1 = ""; } if (factor2 == null) { factor2 = ""; } result = factor1.compareToIgnoreCase(factor2); } /** ***************** for sorting submissions in instructor grade assignment view ************* */ else if(m_criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW)) { UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null ) { result = 1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null ) { result = 1; } else { int score1 = u1.getSubmission().getReviewScore(); int score2 = u2.getSubmission().getReviewScore(); result = (new Integer(score1)).intValue() > (new Integer(score2)).intValue() ? 1 : -1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null ) { result = 1; } else { String lName1 = u1.getUser().getSortName(); String lName2 = u2.getUser().getSortName(); result = lName1.toLowerCase().compareTo(lName2.toLowerCase()); } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null || s1.getTimeSubmitted() == null) { result = -1; } else if (s2 == null || s2.getTimeSubmitted() == null) { result = 1; } else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted())) { result = -1; } else { result = 1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; String status1 = ""; String status2 = ""; if (u1 == null) { status1 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s1 = u1.getSubmission(); if (s1 == null) { status1 = rb.getString("listsub.nosub"); } else { status1 = getSubmissionStatus(m_state, (AssignmentSubmission) s1); } } if (u2 == null) { status2 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s2 = u2.getSubmission(); if (s2 == null) { status2 = rb.getString("listsub.nosub"); } else { status2 = getSubmissionStatus(m_state, (AssignmentSubmission) s2); } } result = status1.toLowerCase().compareTo(status2.toLowerCase()); } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); //sort by submission grade if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { String grade1 = s1.getGrade(); String grade2 = s2.getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((s1.getAssignment().getContent().getTypeOfGrade() == 3) && ((s2.getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { - result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; + result = (new Double(grade1)).doubleValue() > (new Double(grade2)).doubleValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { // sort by submission released String released1 = (new Boolean(s1.getGradeReleased())).toString(); String released2 = (new Boolean(s2.getGradeReleased())).toString(); result = released1.compareTo(released2); } } } /****** for other sort on submissions **/ else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name User[] u1 = ((AssignmentSubmission) o1).getSubmitters(); User[] u2 = ((AssignmentSubmission) o2).getSubmitters(); if (u1 == null || u2 == null) { return 1; } else { String submitters1 = ""; String submitters2 = ""; for (int j = 0; j < u1.length; j++) { if (u1[j] != null && u1[j].getLastName() != null) { if (j > 0) { submitters1 = submitters1.concat("; "); } submitters1 = submitters1.concat("" + u1[j].getLastName()); } } for (int j = 0; j < u2.length; j++) { if (u2[j] != null && u2[j].getLastName() != null) { if (j > 0) { submitters2 = submitters2.concat("; "); } submitters2 = submitters2.concat(u2[j].getLastName()); } } result = submitters1.toLowerCase().compareTo(submitters2.toLowerCase()); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted(); Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS)) { // sort by submission status String status1 = getSubmissionStatus(m_state, (AssignmentSubmission) o1); String status2 = getSubmissionStatus(m_state, (AssignmentSubmission) o2); result = status1.compareTo(status2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE)) { Assignment a1 = ((AssignmentSubmission) o1).getAssignment(); Assignment a2 = ((AssignmentSubmission) o2).getAssignment(); String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1); String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED)) { // sort by submission released String released1 = (new Boolean(((AssignmentSubmission) o1).getGradeReleased())).toString(); String released2 = (new Boolean(((AssignmentSubmission) o2).getGradeReleased())).toString(); result = released1.compareTo(released2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT)) { // sort by submission's assignment String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle(); String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle(); result = title1.toLowerCase().compareTo(title2.toLowerCase()); } // sort ascending or descending if (m_asc.equals(Boolean.FALSE.toString())) { result = -result; } return result; } // compare /** * get the submissin status */ private String getSubmissionStatus(SessionState state, AssignmentSubmission s) { String status = ""; if (s.getReturned()) { if (s.getTimeReturned() != null && s.getTimeSubmitted() != null && s.getTimeReturned().before(s.getTimeSubmitted())) { status = rb.getString("listsub.resubmi"); } else { status = rb.getString("gen.returned"); } } else if (s.getGraded()) { if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()) { status = rb.getString("grad3"); } else { status = rb.getString("gen.commented"); } } else { status = rb.getString("gen.ung1"); } return status; } // getSubmissionStatus /** * get the status string of assignment */ private String getAssignmentStatus(Assignment a) { String status = ""; Time currentTime = TimeService.newTime(); if (a.getDraft()) status = rb.getString("draft2"); else if (a.getOpenTime().after(currentTime)) status = rb.getString("notope"); else if (a.getDueTime().after(currentTime)) status = rb.getString("ope"); else if ((a.getCloseTime() != null) && (a.getCloseTime().before(currentTime))) status = rb.getString("clos"); else status = rb.getString("due2"); return status; } // getAssignmentStatus /** * get submission status */ private String getSubmissionStatus(AssignmentSubmission submission, Assignment assignment) { String status = ""; if (submission != null) if (submission.getSubmitted()) if (submission.getGraded() && submission.getGradeReleased()) status = rb.getString("grad3"); else if (submission.getReturned()) status = rb.getString("return") + " " + submission.getTimeReturned().toStringLocalFull(); else { status = rb.getString("submitt") + submission.getTimeSubmitted().toStringLocalFull(); if (submission.getTimeSubmitted().after(assignment.getDueTime())) status = status + rb.getString("late"); } else status = rb.getString("inpro"); else status = rb.getString("notsta"); return status; } // getSubmissionStatus /** * get assignment maximun grade available based on the assignment grade type * * @param gradeType * The int value of grade type * @param a * The assignment object * @return The max grade String */ private String maxGrade(int gradeType, Assignment a) { String maxGrade = ""; if (gradeType == -1) { // Grade type not set maxGrade = rb.getString("granotset"); } else if (gradeType == 1) { // Ungraded grade type maxGrade = rb.getString("nogra"); } else if (gradeType == 2) { // Letter grade type maxGrade = "A"; } else if (gradeType == 3) { // Score based grade type maxGrade = Integer.toString(a.getContent().getMaxGradePoint()); } else if (gradeType == 4) { // Pass/fail grade type maxGrade = rb.getString("pass2"); } else if (gradeType == 5) { // Grade type that only requires a check maxGrade = rb.getString("check2"); } return maxGrade; } // maxGrade } // DiscussionComparator /** * Fire up the permissions editor */ public void doPermissions(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { // we are changing the view, so start with first page again. resetPaging(state); // clear search form doSearch_clear(data, null); if (SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING))) { // get into helper mode with this helper tool startHelper(data.getRequest(), "sakai.permissions.helper"); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String siteRef = SiteService.siteReference(contextString); // setup for editing the permissions of the site for this tool, using the roles of this site, too state.setAttribute(PermissionsHelper.TARGET_REF, siteRef); // ... with this description state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setperfor") + " " + SiteService.getSiteDisplay(contextString)); // ... showing only locks that are prpefixed with this state.setAttribute(PermissionsHelper.PREFIX, "asn."); // disable auto-updates while leaving the list view justDelivered(state); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } // switching back to assignment list view state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS); doList_assignments(data); } } // doPermissions /** * transforms the Iterator to Vector */ private Vector iterator_to_vector(Iterator l) { Vector v = new Vector(); while (l.hasNext()) { v.add(l.next()); } return v; } // iterator_to_vector /** * Implement this to return alist of all the resources that there are to page. Sort them as appropriate. */ protected List readResourcesPage(SessionState state, int first, int last) { List returnResources = (List) state.getAttribute(STATE_PAGEING_TOTAL_ITEMS); PagingPosition page = new PagingPosition(first, last); page.validate(returnResources.size()); returnResources = returnResources.subList(page.getFirst() - 1, page.getLast()); return returnResources; } // readAllResources /* * (non-Javadoc) * * @see org.sakaiproject.cheftool.PagedResourceActionII#sizeResources(org.sakaiproject.service.framework.session.SessionState) */ protected int sizeResources(SessionState state) { String mode = (String) state.getAttribute(STATE_MODE); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // all the resources for paging List returnResources = new Vector(); boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString); if (mode.equalsIgnoreCase(MODE_LIST_ASSIGNMENTS)) { String view = ""; if (state.getAttribute(STATE_SELECTED_VIEW) != null) { view = (String) state.getAttribute(STATE_SELECTED_VIEW); } if (allowAddAssignment && view.equals(MODE_LIST_ASSIGNMENTS)) { // read all Assignments returnResources = AssignmentService.getListAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING)); } else if (allowAddAssignment && view.equals(MODE_STUDENT_VIEW) || !allowAddAssignment) { // in the student list view of assignments Iterator assignments = AssignmentService .getAssignmentsForContext(contextString); Time currentTime = TimeService.newTime(); while (assignments.hasNext()) { Assignment a = (Assignment) assignments.next(); try { String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED); if (deleted == null || deleted.equals("")) { // show not deleted assignments Time openTime = a.getOpenTime(); if (openTime != null && currentTime.after(openTime) && !a.getDraft()) { returnResources.add(a); } } else if (deleted.equalsIgnoreCase(Boolean.TRUE.toString()) && AssignmentService.getSubmission(a.getReference(), (User) state .getAttribute(STATE_USER)) != null) { // and those deleted assignments but the user has made submissions to them returnResources.add(a); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } } } else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REPORT_SUBMISSIONS)) { Vector submissions = new Vector(); Vector assignments = iterator_to_vector(AssignmentService.getAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING))); if (assignments.size() > 0) { // users = AssignmentService.allowAddSubmissionUsers (((Assignment)assignments.get(0)).getReference ()); } for (int j = 0; j < assignments.size(); j++) { Assignment a = (Assignment) assignments.get(j); String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED); if ((deleted == null || deleted.equals("")) && (!a.getDraft())) { try { List assignmentSubmissions = AssignmentService.getSubmissions(a); for (int k = 0; k < assignmentSubmissions.size(); k++) { AssignmentSubmission s = (AssignmentSubmission) assignmentSubmissions.get(k); if (s != null && (s.getSubmitted() || (s.getReturned() && (s.getTimeLastModified().before(s .getTimeReturned()))))) { // has been subitted or has been returned and not work on it yet submissions.add(s); } // if-else } } catch (Exception e) { } } } returnResources = submissions; } else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_GRADE_ASSIGNMENT)) { try { Assignment a = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); Iterator submissionsIterator = AssignmentService.getSubmissions(a).iterator(); List submissions = new Vector(); while (submissionsIterator.hasNext()) { submissions.add(submissionsIterator.next()); } // get all active site users String authzGroupId = SiteService.siteReference(contextString); // all users that can submit List allowAddSubmissionUsers = AssignmentService.allowAddSubmissionUsers((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); try { AuthzGroup group = AuthzGroupService.getAuthzGroup(authzGroupId); Set grants = group.getUsers(); for (Iterator iUserIds = grants.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); try { User u = UserDirectoryService.getUser(userId); // only include those users that can submit to this assignment if (u != null && allowAddSubmissionUsers.contains(u)) { boolean found = false; for (int i = 0; !found && i<submissions.size();i++) { AssignmentSubmission s = (AssignmentSubmission) submissions.get(i); if (s.getSubmitterIds().contains(userId)) { returnResources.add(new UserSubmission(u, s)); found = true; } } // add those users who haven't made any submissions if (!found) { // construct fake submissions for grading purpose AssignmentSubmissionEdit s = AssignmentService.addSubmission(contextString, a.getId()); s.removeSubmitter(UserDirectoryService.getCurrentUser()); s.addSubmitter(u); s.setSubmitted(true); s.setAssignment(a); AssignmentService.commitEdit(s); // update the UserSubmission list by adding newly created Submission object AssignmentSubmission sub = AssignmentService.getSubmission(s.getReference()); returnResources.add(new UserSubmission(u, sub)); } } } catch (Exception e) { Log.warn("chef", this + e.toString() + " here userId = " + userId); } } } catch (Exception e) { Log.warn("chef", e.getMessage() + " authGroupId=" + authzGroupId); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } // sort them all String ascending = "true"; String sort = ""; ascending = (String) state.getAttribute(SORTED_ASC); sort = (String) state.getAttribute(SORTED_BY); if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_GRADE_ASSIGNMENT) && !sort.startsWith("sorted_grade_submission_by")) { ascending = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC); sort = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_BY); } else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REPORT_SUBMISSIONS) && sort.startsWith("sorted_submission_by")) { ascending = (String) state.getAttribute(SORTED_SUBMISSION_ASC); sort = (String) state.getAttribute(SORTED_SUBMISSION_BY); } else { ascending = (String) state.getAttribute(SORTED_ASC); sort = (String) state.getAttribute(SORTED_BY); } if ((returnResources.size() > 1) && !mode.equalsIgnoreCase(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT)) { Collections.sort(returnResources, new AssignmentComparator(state, sort, ascending)); } // record the total item number state.setAttribute(STATE_PAGEING_TOTAL_ITEMS, returnResources); return returnResources.size(); } public void doView(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { // we are changing the view, so start with first page again. resetPaging(state); // clear search form doSearch_clear(data, null); String viewMode = data.getParameters().getString("view"); state.setAttribute(STATE_SELECTED_VIEW, viewMode); if (viewMode.equals(MODE_LIST_ASSIGNMENTS)) { doList_assignments(data); } else if (viewMode.equals(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT)) { doView_students_assignment(data); } else if (viewMode.equals(MODE_INSTRUCTOR_REPORT_SUBMISSIONS)) { doReport_submissions(data); } else if (viewMode.equals(MODE_STUDENT_VIEW)) { doView_student(data); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } } } // doView /** * put those variables related to 2ndToolbar into context */ private void add2ndToolbarFields(RunData data, Context context) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); context.put("totalPageNumber", new Integer(totalPageNumber(state))); context.put("form_search", FORM_SEARCH); context.put("formPageNumber", FORM_PAGE_NUMBER); context.put("prev_page_exists", state.getAttribute(STATE_PREV_PAGE_EXISTS)); context.put("next_page_exists", state.getAttribute(STATE_NEXT_PAGE_EXISTS)); context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE)); context.put("selectedView", state.getAttribute(STATE_MODE)); } // add2ndToolbarFields /** * valid grade? */ private void validPointGrade(SessionState state, String grade) { if (grade != null && !grade.equals("")) { if (grade.startsWith("-")) { // check for negative sign addAlert(state, rb.getString("plesuse3")); } else { int index = grade.indexOf("."); if (index != -1) { // when there is decimal points inside the grade, scale the number by 10 // but only one decimal place is supported // for example, change 100.0 to 1000 if (!grade.equals(".")) { if (grade.length() > index + 2) { // if there are more than one decimal point addAlert(state, rb.getString("plesuse2")); } else { // decimal points is the only allowed character inside grade // replace it with '1', and try to parse the new String into int String gradeString = (grade.endsWith(".")) ? grade.substring(0, index).concat("0") : grade.substring(0, index).concat(grade.substring(index + 1)); try { Integer.parseInt(gradeString); } catch (NumberFormatException e) { alertInvalidPoint(state, gradeString); } } } else { // grade is "." addAlert(state, rb.getString("plesuse1")); } } else { // There is no decimal point; should be int number String gradeString = grade + "0"; try { Integer.parseInt(gradeString); } catch (NumberFormatException e) { alertInvalidPoint(state, gradeString); } } } } } // validPointGrade private void alertInvalidPoint(SessionState state, String grade) { String VALID_CHARS_FOR_INT = "-01234567890"; boolean invalid = false; // case 1: contains invalid char for int for (int i = 0; i < grade.length() && !invalid; i++) { char c = grade.charAt(i); if (VALID_CHARS_FOR_INT.indexOf(c) == -1) { invalid = true; } } if (invalid) { addAlert(state, rb.getString("plesuse1")); } else { int maxInt = Integer.MAX_VALUE / 10; int maxDec = Integer.MAX_VALUE - maxInt * 10; // case 2: Due to our internal scaling, input String is larger than Integer.MAX_VALUE/10 addAlert(state, rb.getString("plesuse4") + maxInt + "." + maxDec + "."); } } /** * display grade properly */ private String displayGrade(SessionState state, String grade) { if (state.getAttribute(STATE_MESSAGE) == null) { if (grade != null && (grade.length() >= 1)) { if (grade.indexOf(".") != -1) { if (grade.startsWith(".")) { grade = "0".concat(grade); } else if (grade.endsWith(".")) { grade = grade.concat("0"); } } else { try { Integer.parseInt(grade); grade = grade.substring(0, grade.length() - 1) + "." + grade.substring(grade.length() - 1); } catch (NumberFormatException e) { alertInvalidPoint(state, grade); } } } else { grade = ""; } } return grade; } // displayGrade /** * scale the point value by 10 if there is a valid point grade */ private String scalePointGrade(SessionState state, String point) { validPointGrade(state, point); if (state.getAttribute(STATE_MESSAGE) == null) { if (point != null && (point.length() >= 1)) { // when there is decimal points inside the grade, scale the number by 10 // but only one decimal place is supported // for example, change 100.0 to 1000 int index = point.indexOf("."); if (index != -1) { if (index == 0) { // if the point is the first char, add a 0 for the integer part point = "0".concat(point.substring(1)); } else if (index < point.length() - 1) { // use scale integer for gradePoint point = point.substring(0, index) + point.substring(index + 1); } else { // decimal point is the last char point = point.substring(0, index) + "0"; } } else { // if there is no decimal place, scale up the integer by 10 point = point + "0"; } // filter out the "zero grade" if (point.equals("00")) { point = "0"; } } } return point; } // scalePointGrade /** * Processes formatted text that is coming back from the browser (from the formatted text editing widget). * * @param state * Used to pass in any user-visible alerts or errors when processing the text * @param strFromBrowser * The string from the browser * @param checkForFormattingErrors * Whether to check for formatted text errors - if true, look for errors in the formatted text. If false, accept the formatted text without looking for errors. * @return The formatted text */ private String processFormattedTextFromBrowser(SessionState state, String strFromBrowser, boolean checkForFormattingErrors) { StringBuffer alertMsg = new StringBuffer(); try { boolean replaceWhitespaceTags = true; String text = FormattedText.processFormattedText(strFromBrowser, alertMsg, checkForFormattingErrors, replaceWhitespaceTags); if (alertMsg.length() > 0) addAlert(state, alertMsg.toString()); return text; } catch (Exception e) { Log.warn("chef", this + ": ", e); return strFromBrowser; } } /** * Processes the given assignmnent feedback text, as returned from the user's browser. Makes sure that the Chef-style markup {{like this}} is properly balanced. */ private String processAssignmentFeedbackFromBrowser(SessionState state, String strFromBrowser) { if (strFromBrowser == null || strFromBrowser.length() == 0) return strFromBrowser; StringBuffer buf = new StringBuffer(strFromBrowser); int pos = -1; int numopentags = 0; while ((pos = buf.indexOf("{{")) != -1) { buf.replace(pos, pos + "{{".length(), "<ins>"); numopentags++; } while ((pos = buf.indexOf("}}")) != -1) { buf.replace(pos, pos + "}}".length(), "</ins>"); numopentags--; } while (numopentags > 0) { buf.append("</ins>"); numopentags--; } boolean checkForFormattingErrors = false; // so that grading isn't held up by formatting errors buf = new StringBuffer(processFormattedTextFromBrowser(state, buf.toString(), checkForFormattingErrors)); while ((pos = buf.indexOf("<ins>")) != -1) { buf.replace(pos, pos + "<ins>".length(), "{{"); } while ((pos = buf.indexOf("</ins>")) != -1) { buf.replace(pos, pos + "</ins>".length(), "}}"); } return buf.toString(); } /** * Called to deal with old Chef-style assignment feedback annotation, {{like this}}. * * @param value * A formatted text string that may contain {{}} style markup * @return HTML ready to for display on a browser */ public static String escapeAssignmentFeedback(String value) { if (value == null || value.length() == 0) return value; value = fixAssignmentFeedback(value); StringBuffer buf = new StringBuffer(value); int pos = -1; while ((pos = buf.indexOf("{{")) != -1) { buf.replace(pos, pos + "{{".length(), "<span class='highlight'>"); } while ((pos = buf.indexOf("}}")) != -1) { buf.replace(pos, pos + "}}".length(), "</span>"); } return FormattedText.escapeHtmlFormattedText(buf.toString()); } /** * Escapes the given assignment feedback text, to be edited as formatted text (perhaps using the formatted text widget) */ public static String escapeAssignmentFeedbackTextarea(String value) { if (value == null || value.length() == 0) return value; value = fixAssignmentFeedback(value); return FormattedText.escapeHtmlFormattedTextarea(value); } /** * Apply the fix to pre 1.1.05 assignments submissions feedback. */ private static String fixAssignmentFeedback(String value) { if (value == null || value.length() == 0) return value; StringBuffer buf = new StringBuffer(value); int pos = -1; // <br/> -> \n while ((pos = buf.indexOf("<br/>")) != -1) { buf.replace(pos, pos + "<br/>".length(), "\n"); } // <span class='chefAlert'>( -> {{ while ((pos = buf.indexOf("<span class='chefAlert'>(")) != -1) { buf.replace(pos, pos + "<span class='chefAlert'>(".length(), "{{"); } // )</span> -> }} while ((pos = buf.indexOf(")</span>")) != -1) { buf.replace(pos, pos + ")</span>".length(), "}}"); } while ((pos = buf.indexOf("<ins>")) != -1) { buf.replace(pos, pos + "<ins>".length(), "{{"); } while ((pos = buf.indexOf("</ins>")) != -1) { buf.replace(pos, pos + "</ins>".length(), "}}"); } return buf.toString(); } // fixAssignmentFeedback /** * Apply the fix to pre 1.1.05 assignments submissions feedback. */ public static String showPrevFeedback(String value) { if (value == null || value.length() == 0) return value; StringBuffer buf = new StringBuffer(value); int pos = -1; // <br/> -> \n while ((pos = buf.indexOf("\n")) != -1) { buf.replace(pos, pos + "\n".length(), "<br />"); } return buf.toString(); } // showPrevFeedback private boolean alertGlobalNavigation(SessionState state, RunData data) { String mode = (String) state.getAttribute(STATE_MODE); ParameterParser params = data.getParameters(); if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION) || mode.equals(MODE_STUDENT_PREVIEW_SUBMISSION) || mode.equals(MODE_STUDENT_VIEW_GRADE) || mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_DELETE_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION) || mode.equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION) || mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_VIEW_ASSIGNMENT)) { if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) == null) { addAlert(state, rb.getString("alert.globalNavi")); state.setAttribute(ALERT_GLOBAL_NAVIGATION, Boolean.TRUE); if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION)) { // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(VIEW_SUBMISSION_TEXT, text); if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null) { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true"); } state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatt")); // TODO: file picker to save in dropbox? -ggolden // User[] users = { UserDirectoryService.getCurrentUser() }; // state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users); } else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT)) { setNewAssignmentParameters(data, false); } else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION)) { readGradeForm(data, state, "read"); } return true; } } return false; } // alertGlobalNavigation /** * Dispatch function inside add submission page */ public void doRead_add_submission_form(RunData data) { String option = data.getParameters().getString("option"); if (option.equals("cancel")) { // cancel doCancel_show_submission(data); } else if (option.equals("preview")) { // preview doPreview_submission(data); } else if (option.equals("save")) { // save draft doSave_submission(data); } else if (option.equals("post")) { // post doPost_submission(data); } else if (option.equals("revise")) { // done preview doDone_preview_submission(data); } else if (option.equals("attach")) { // attach doAttachments(data); } } /** * */ public void doSet_defaultNoSubmissionScore(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters(); String grade = StringUtil.trimToNull(params.getString("defaultGrade")); if (grade == null) { addAlert(state, rb.getString("plespethe2")); } String assignmentId = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); try { // record the default grade setting for no-submission AssignmentEdit aEdit = AssignmentService.editAssignment(assignmentId); aEdit.getPropertiesEdit().addProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE, grade); AssignmentService.commitEdit(aEdit); Assignment a = AssignmentService.getAssignment(assignmentId); if (a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { //for point-based grades validPointGrade(state, grade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getString("grad2")); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, grade); } } if (state.getAttribute(STATE_MESSAGE) == null) { grade = scalePointGrade(state, grade); } } if (grade != null && state.getAttribute(STATE_MESSAGE) == null) { // get the user list List userSubmissions = new Vector(); if (state.getAttribute(USER_SUBMISSIONS) != null) { userSubmissions = (List) state.getAttribute(USER_SUBMISSIONS); } // constructor a new UserSubmissions list List userSubmissionsNew = new Vector(); for (int i = 0; i<userSubmissions.size(); i++) { // get the UserSubmission object UserSubmission us = (UserSubmission) userSubmissions.get(i); User u = us.getUser(); AssignmentSubmission submission = us.getSubmission(); // check whether there is a submission associated if (submission == null) { AssignmentSubmissionEdit s = AssignmentService.addSubmission((String) state.getAttribute(STATE_CONTEXT_STRING), assignmentId); s.removeSubmitter(UserDirectoryService.getCurrentUser()); s.addSubmitter(u); // submitted by without submit time s.setSubmitted(true); s.setGrade(grade); s.setGraded(true); s.setAssignment(a); AssignmentService.commitEdit(s); // update the UserSubmission list by adding newly created Submission object AssignmentSubmission sub = AssignmentService.getSubmission(s.getReference()); userSubmissionsNew.add(new UserSubmission(u, sub)); } else if (submission.getTimeSubmitted() == null) { // update the grades for those existing non-submissions AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference()); sEdit.setGrade(grade); sEdit.setSubmitted(true); sEdit.setGraded(true); sEdit.setAssignment(a); AssignmentService.commitEdit(sEdit); userSubmissionsNew.add(new UserSubmission(u, AssignmentService.getSubmission(sEdit.getReference()))); } else { // no change for this user userSubmissionsNew.add(us); } } state.setAttribute(USER_SUBMISSIONS, userSubmissionsNew); } } catch (Exception e) { Log.warn("chef", e.toString()); } } /** * * @return */ public void doUpload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String flow = params.getString("flow"); if (flow.equals("upload")) { // upload doUpload_all_upload(data); } else if (flow.equals("cancel")) { // cancel doCancel_upload_all(data); } } public void doUpload_all_upload(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String contextString = ToolManager.getCurrentPlacement().getContext(); String toolTitle = ToolManager.getTool("sakai.assignment").getTitle(); boolean hasSubmissions = false; boolean hasGradeFile = false; boolean hasComments = false; boolean releaseGrades = false; // check against the content elements selection if (params.getString("studentSubmission") != null) { // should contain student submission information hasSubmissions = true; } if (params.getString("gradeFile") != null) { // should contain grade file hasGradeFile = true; } if (params.getString("instructorComments") != null) { // comments.xml should be available hasComments = true; } if (params.getString("release") != null) { // comments.xml should be available releaseGrades = params.getBoolean("release"); } state.setAttribute(UPLOAD_ALL_HAS_SUBMISSIONS, Boolean.valueOf(hasSubmissions)); state.setAttribute(UPLOAD_ALL_HAS_GRADEFILE, Boolean.valueOf(hasGradeFile)); state.setAttribute(UPLOAD_ALL_HAS_COMMENTS, Boolean.valueOf(hasComments)); state.setAttribute(UPLOAD_ALL_RELEASE_GRADES, Boolean.valueOf(releaseGrades)); if (!hasSubmissions && !hasGradeFile && !hasComments) { // has to choose one upload feature addAlert(state, rb.getString("uploadall.alert.choose.element")); } else { // constructor the hashtable for all submission objects Hashtable submissionTable = new Hashtable(); Assignment assignment = null; try { assignment = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); Iterator sIterator = AssignmentService.getSubmissions(assignment).iterator(); while (sIterator.hasNext()) { AssignmentSubmission s = (AssignmentSubmission) sIterator.next(); User[] users = s.getSubmitters(); String uName = users[0].getSortName(); submissionTable.put(uName, new UploadGradeWrapper("", "", "", new Vector())); } } catch (Exception e) { Log.warn("chef", e.toString()); } // see if the user uploaded a file FileItem fileFromUpload = null; String fileName = null; fileFromUpload = params.getFileItem("file"); String max_file_size_mb = ServerConfigurationService.getString("content.upload.max", "1"); int max_bytes = 1024 * 1024; try { max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024; } catch(Exception e) { // if unable to parse an integer from the value // in the properties file, use 1 MB as a default max_file_size_mb = "1"; max_bytes = 1024 * 1024; } if(fileFromUpload == null) { // "The user submitted a file to upload but it was too big!" addAlert(state, rb.getString("uploadall.size") + " " + max_file_size_mb + "MB " + rb.getString("uploadall.exceeded")); } else if (fileFromUpload.getFileName() == null || fileFromUpload.getFileName().length() == 0) { // no file addAlert(state, rb.getString("uploadall.alert.zipFile")); } else { byte[] fileData = fileFromUpload.get(); if(fileData.length >= max_bytes) { addAlert(state, rb.getString("uploadall.size") + " " + max_file_size_mb + "MB " + rb.getString("uploadall.exceeded")); } else if(fileData.length > 0) { ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(fileData)); ZipEntry entry; try { while ((entry=zin.getNextEntry()) != null) { if (!entry.isDirectory()) { String entryName = entry.getName(); if (entryName.endsWith("grades.csv")) { if (hasGradeFile) { // read grades.cvs from zip String result = StringUtil.trimToZero(readIntoString(zin)); String[] lines=null; if (result.indexOf("\r") != -1) lines = result.split("\r"); else if (result.indexOf("\n") != -1) lines = result.split("\n"); for (int i = 3; i<lines.length; i++) { // escape the first three header lines String[] items = lines[i].split(","); if (items.length > 3) { // has grade information try { User u = UserDirectoryService.getUserByEid(items[0]/*user id*/); UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(u.getSortName()); if (w != null) { w.setGrade(assignment.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE?scalePointGrade(state, items[3]):items[3]); submissionTable.put(u.getSortName(), w); } } catch (Exception e ) { Log.warn("chef", e.toString()); } } } } } else { // get user sort name String userName = ""; if (entryName.indexOf("/") != -1) { userName = entryName.substring(0, entryName.lastIndexOf("/")); if (userName.indexOf("/") != -1) { userName = userName.substring(userName.lastIndexOf("/")+1, userName.length()); } } if (hasComments && entryName.endsWith("comments.txt")) { // read the comments file String comment = StringUtil.trimToNull(readIntoString(zin)); if (submissionTable.containsKey(userName) && comment != null) { UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userName); r.setComment(comment); submissionTable.put(userName, r); } } else if (hasSubmissions) { if (entryName.endsWith("_submissionText.html")) { // upload the student submission text along with the feedback text String text = StringUtil.trimToNull(readIntoString(zin)); if (submissionTable.containsKey(userName) && text != null) { UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userName); r.setText(text); submissionTable.put(userName, r); } } else { // upload all the files as instuctor attachments to the submission for grading purpose String fName = entryName.substring(entryName.lastIndexOf("/") + 1, entryName.length()); ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE); try { if (submissionTable.containsKey(userName)) { // add the file as attachment ResourceProperties properties = ContentHostingService.newResourceProperties(); properties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, fName); ContentResource attachment = ContentHostingService.addAttachmentResource( fName, contextString, toolTitle, iService.getContentType(fName.substring(fName.lastIndexOf(".") + 1)), readIntoString(zin).getBytes(), properties); UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userName); List attachments = r.getAttachments(); attachments.add(EntityManager.newReference(attachment.getReference())); r.setAttachments(attachments); } } catch (Exception ee) { Log.warn("chef", ee.toString()); } } } } } } } catch (IOException e) { // uploaded file is not a valid archive addAlert(state, rb.getString("uploadall.alert.zipFile")); } } } if (state.getAttribute(STATE_MESSAGE) == null) { // update related submissions if (assignment != null) { Iterator sIterator = AssignmentService.getSubmissions(assignment).iterator(); while (sIterator.hasNext()) { AssignmentSubmission s = (AssignmentSubmission) sIterator.next(); User[] users = s.getSubmitters(); String uName = users[0].getSortName(); if (submissionTable.containsKey(uName)) { // update the AssignmetnSubmission record try { AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(s.getReference()); UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(uName); // add all attachment if (hasSubmissions) { sEdit.clearFeedbackAttachments(); for (Iterator attachments = w.getAttachments().iterator(); attachments.hasNext();) { sEdit.addFeedbackAttachment((Reference) attachments.next()); } sEdit.setFeedbackText(w.getText()); } if (hasComments) { // add comment sEdit.setFeedbackComment(w.getComment()); } if (hasGradeFile) { // set grade sEdit.setGrade(w.getGrade()); sEdit.setGraded(true); } // release or not sEdit.setGradeReleased(releaseGrades); sEdit.setReturned(releaseGrades); // commit AssignmentService.commitEdit(sEdit); } catch (Exception ee) { Log.debug("chef", ee.toString()); } } } } } } if (state.getAttribute(STATE_MESSAGE) == null) { // go back to the list of submissions view cleanUploadAllContext(state); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } } private String readIntoString(ZipInputStream zin) throws IOException { byte[] buf = new byte[1024]; int len; StringBuffer b = new StringBuffer(); while ((len = zin.read(buf)) > 0) { b.append(new String(buf)); } return b.toString(); } /** * * @return */ public void doCancel_upload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); cleanUploadAllContext(state); } /** * clean the state variabled used by upload all process */ private void cleanUploadAllContext(SessionState state) { state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSIONS); state.removeAttribute(UPLOAD_ALL_HAS_GRADEFILE); state.removeAttribute(UPLOAD_ALL_HAS_COMMENTS); state.removeAttribute(UPLOAD_ALL_RELEASE_GRADES); } /** * Action is to preparing to go to the upload files */ public void doPrep_upload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_UPLOAD_ALL); } // doPrep_upload_all /** * the UploadGradeWrapper class to be used for the "upload all" feature */ public class UploadGradeWrapper { /** * the grade */ String m_grade = null; /** * the text */ String m_text = null; /** * the comment */ String m_comment = ""; /** * the attachment list */ List m_attachments = EntityManager.newReferenceList(); public UploadGradeWrapper(String grade, String text, String comment, List attachments) { m_grade = grade; m_text = text; m_comment = comment; m_attachments = attachments; } /** * Returns grade string */ public String getGrade() { return m_grade; } /** * Returns the text */ public String getText() { return m_text; } /** * Returns the comment string */ public String getComment() { return m_comment; } /** * Returns the attachment list */ public List getAttachments() { return m_attachments; } /** * set the grade string */ public void setGrade(String grade) { m_grade = grade; } /** * set the text */ public void setText(String text) { m_text = text; } /** * set the comment string */ public void setComment(String comment) { m_comment = comment; } /** * set the attachment list */ public void setAttachments(List attachments) { m_attachments = attachments; } } private List<DecoratedTaggingProvider> initDecoratedProviders() { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); List<DecoratedTaggingProvider> providers = new ArrayList<DecoratedTaggingProvider>(); for (TaggingProvider provider : taggingManager.getProviders()) { providers.add(new DecoratedTaggingProvider(provider)); } return providers; } private List<DecoratedTaggingProvider> addProviders(Context context, SessionState state) { String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); if (providers == null) { providers = initDecoratedProviders(); state.setAttribute(mode + PROVIDER_LIST, providers); } context.put("providers", providers); return providers; } private void addActivity(Context context, Assignment assignment) { AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); context.put("activity", assignmentActivityProducer .getActivity(assignment)); } private void addItem(Context context, AssignmentSubmission submission, String userId) { AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); context.put("item", assignmentActivityProducer .getItem(submission, userId)); } private ContentReviewService contentReviewService; public String getReportURL(Long score) { if (contentReviewService == null) { contentReviewService = (ContentReviewService) ComponentManager.get(ContentReviewService.class.getName()); } return contentReviewService.getIconUrlforScore(score); } }
true
true
public int compare(Object o1, Object o2) { int result = -1; /** *********** fo sorting assignments ****************** */ if (m_criteria.equals(SORTED_BY_TITLE)) { // sorted by the assignment title String s1 = ((Assignment) o1).getTitle(); String s2 = ((Assignment) o2).getTitle(); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_SECTION)) { // sorted by the assignment section String s1 = ((Assignment) o1).getSection(); String s2 = ((Assignment) o2).getSection(); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_DUEDATE)) { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_OPENDATE)) { // sorted by the assignment open Time t1 = ((Assignment) o1).getOpenTime(); Time t2 = ((Assignment) o2).getOpenTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS)) { String s1 = getAssignmentStatus((Assignment) o1); String s2 = getAssignmentStatus((Assignment) o2); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS)) { // sort by numbers of submissions // initialize int subNum1 = 0; int subNum2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator(); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted()) subNum1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator(); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted()) subNum2++; } result = (subNum1 > subNum2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED)) { // sort by numbers of ungraded submissions // initialize int ungraded1 = 0; int ungraded2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator(); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator(); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++; } result = (ungraded1 > ungraded2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_SUBMISSION_STATUS)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String status1 = getSubmissionStatus(submission1, (Assignment) o1); AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String status2 = getSubmissionStatus(submission2, (Assignment) o2); result = status1.compareTo(status2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_GRADE)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String grade1 = " "; if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased()) { grade1 = submission1.getGrade(); } AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String grade2 = " "; if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased()) { grade2 = submission2.getGrade(); } result = grade1.compareTo(grade2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_MAX_GRADE)) { String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1); String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } // group related sorting else if (m_criteria.equals(SORTED_BY_FOR)) { // sorted by the public view attribute String factor1 = getAssignmentRange((Assignment) o1); String factor2 = getAssignmentRange((Assignment) o2); result = factor1.compareToIgnoreCase(factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_TITLE)) { // sorted by the group title String factor1 = ((Group) o1).getTitle(); String factor2 = ((Group) o2).getTitle(); result = factor1.compareToIgnoreCase(factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION)) { // sorted by the group description String factor1 = ((Group) o1).getDescription(); String factor2 = ((Group) o2).getDescription(); if (factor1 == null) { factor1 = ""; } if (factor2 == null) { factor2 = ""; } result = factor1.compareToIgnoreCase(factor2); } /** ***************** for sorting submissions in instructor grade assignment view ************* */ else if(m_criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW)) { UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null ) { result = 1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null ) { result = 1; } else { int score1 = u1.getSubmission().getReviewScore(); int score2 = u2.getSubmission().getReviewScore(); result = (new Integer(score1)).intValue() > (new Integer(score2)).intValue() ? 1 : -1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null ) { result = 1; } else { String lName1 = u1.getUser().getSortName(); String lName2 = u2.getUser().getSortName(); result = lName1.toLowerCase().compareTo(lName2.toLowerCase()); } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null || s1.getTimeSubmitted() == null) { result = -1; } else if (s2 == null || s2.getTimeSubmitted() == null) { result = 1; } else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted())) { result = -1; } else { result = 1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; String status1 = ""; String status2 = ""; if (u1 == null) { status1 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s1 = u1.getSubmission(); if (s1 == null) { status1 = rb.getString("listsub.nosub"); } else { status1 = getSubmissionStatus(m_state, (AssignmentSubmission) s1); } } if (u2 == null) { status2 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s2 = u2.getSubmission(); if (s2 == null) { status2 = rb.getString("listsub.nosub"); } else { status2 = getSubmissionStatus(m_state, (AssignmentSubmission) s2); } } result = status1.toLowerCase().compareTo(status2.toLowerCase()); } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); //sort by submission grade if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { String grade1 = s1.getGrade(); String grade2 = s2.getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((s1.getAssignment().getContent().getTypeOfGrade() == 3) && ((s2.getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { // sort by submission released String released1 = (new Boolean(s1.getGradeReleased())).toString(); String released2 = (new Boolean(s2.getGradeReleased())).toString(); result = released1.compareTo(released2); } } } /****** for other sort on submissions **/ else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name User[] u1 = ((AssignmentSubmission) o1).getSubmitters(); User[] u2 = ((AssignmentSubmission) o2).getSubmitters(); if (u1 == null || u2 == null) { return 1; } else { String submitters1 = ""; String submitters2 = ""; for (int j = 0; j < u1.length; j++) { if (u1[j] != null && u1[j].getLastName() != null) { if (j > 0) { submitters1 = submitters1.concat("; "); } submitters1 = submitters1.concat("" + u1[j].getLastName()); } } for (int j = 0; j < u2.length; j++) { if (u2[j] != null && u2[j].getLastName() != null) { if (j > 0) { submitters2 = submitters2.concat("; "); } submitters2 = submitters2.concat(u2[j].getLastName()); } } result = submitters1.toLowerCase().compareTo(submitters2.toLowerCase()); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted(); Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS)) { // sort by submission status String status1 = getSubmissionStatus(m_state, (AssignmentSubmission) o1); String status2 = getSubmissionStatus(m_state, (AssignmentSubmission) o2); result = status1.compareTo(status2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE)) { Assignment a1 = ((AssignmentSubmission) o1).getAssignment(); Assignment a2 = ((AssignmentSubmission) o2).getAssignment(); String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1); String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED)) { // sort by submission released String released1 = (new Boolean(((AssignmentSubmission) o1).getGradeReleased())).toString(); String released2 = (new Boolean(((AssignmentSubmission) o2).getGradeReleased())).toString(); result = released1.compareTo(released2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT)) { // sort by submission's assignment String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle(); String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle(); result = title1.toLowerCase().compareTo(title2.toLowerCase()); } // sort ascending or descending if (m_asc.equals(Boolean.FALSE.toString())) { result = -result; } return result; } // compare
public int compare(Object o1, Object o2) { int result = -1; /** *********** fo sorting assignments ****************** */ if (m_criteria.equals(SORTED_BY_TITLE)) { // sorted by the assignment title String s1 = ((Assignment) o1).getTitle(); String s2 = ((Assignment) o2).getTitle(); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_SECTION)) { // sorted by the assignment section String s1 = ((Assignment) o1).getSection(); String s2 = ((Assignment) o2).getSection(); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_DUEDATE)) { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_OPENDATE)) { // sorted by the assignment open Time t1 = ((Assignment) o1).getOpenTime(); Time t2 = ((Assignment) o2).getOpenTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS)) { String s1 = getAssignmentStatus((Assignment) o1); String s2 = getAssignmentStatus((Assignment) o2); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS)) { // sort by numbers of submissions // initialize int subNum1 = 0; int subNum2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator(); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted()) subNum1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator(); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted()) subNum2++; } result = (subNum1 > subNum2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED)) { // sort by numbers of ungraded submissions // initialize int ungraded1 = 0; int ungraded2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator(); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator(); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++; } result = (ungraded1 > ungraded2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_SUBMISSION_STATUS)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String status1 = getSubmissionStatus(submission1, (Assignment) o1); AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String status2 = getSubmissionStatus(submission2, (Assignment) o2); result = status1.compareTo(status2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_GRADE)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String grade1 = " "; if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased()) { grade1 = submission1.getGrade(); } AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String grade2 = " "; if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased()) { grade2 = submission2.getGrade(); } result = grade1.compareTo(grade2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_MAX_GRADE)) { String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1); String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } // group related sorting else if (m_criteria.equals(SORTED_BY_FOR)) { // sorted by the public view attribute String factor1 = getAssignmentRange((Assignment) o1); String factor2 = getAssignmentRange((Assignment) o2); result = factor1.compareToIgnoreCase(factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_TITLE)) { // sorted by the group title String factor1 = ((Group) o1).getTitle(); String factor2 = ((Group) o2).getTitle(); result = factor1.compareToIgnoreCase(factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION)) { // sorted by the group description String factor1 = ((Group) o1).getDescription(); String factor2 = ((Group) o2).getDescription(); if (factor1 == null) { factor1 = ""; } if (factor2 == null) { factor2 = ""; } result = factor1.compareToIgnoreCase(factor2); } /** ***************** for sorting submissions in instructor grade assignment view ************* */ else if(m_criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW)) { UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null ) { result = 1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null ) { result = 1; } else { int score1 = u1.getSubmission().getReviewScore(); int score2 = u2.getSubmission().getReviewScore(); result = (new Integer(score1)).intValue() > (new Integer(score2)).intValue() ? 1 : -1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null ) { result = 1; } else { String lName1 = u1.getUser().getSortName(); String lName2 = u2.getUser().getSortName(); result = lName1.toLowerCase().compareTo(lName2.toLowerCase()); } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null || s1.getTimeSubmitted() == null) { result = -1; } else if (s2 == null || s2.getTimeSubmitted() == null) { result = 1; } else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted())) { result = -1; } else { result = 1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; String status1 = ""; String status2 = ""; if (u1 == null) { status1 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s1 = u1.getSubmission(); if (s1 == null) { status1 = rb.getString("listsub.nosub"); } else { status1 = getSubmissionStatus(m_state, (AssignmentSubmission) s1); } } if (u2 == null) { status2 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s2 = u2.getSubmission(); if (s2 == null) { status2 = rb.getString("listsub.nosub"); } else { status2 = getSubmissionStatus(m_state, (AssignmentSubmission) s2); } } result = status1.toLowerCase().compareTo(status2.toLowerCase()); } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); //sort by submission grade if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { String grade1 = s1.getGrade(); String grade2 = s2.getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((s1.getAssignment().getContent().getTypeOfGrade() == 3) && ((s2.getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Double(grade1)).doubleValue() > (new Double(grade2)).doubleValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { // sort by submission released String released1 = (new Boolean(s1.getGradeReleased())).toString(); String released2 = (new Boolean(s2.getGradeReleased())).toString(); result = released1.compareTo(released2); } } } /****** for other sort on submissions **/ else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name User[] u1 = ((AssignmentSubmission) o1).getSubmitters(); User[] u2 = ((AssignmentSubmission) o2).getSubmitters(); if (u1 == null || u2 == null) { return 1; } else { String submitters1 = ""; String submitters2 = ""; for (int j = 0; j < u1.length; j++) { if (u1[j] != null && u1[j].getLastName() != null) { if (j > 0) { submitters1 = submitters1.concat("; "); } submitters1 = submitters1.concat("" + u1[j].getLastName()); } } for (int j = 0; j < u2.length; j++) { if (u2[j] != null && u2[j].getLastName() != null) { if (j > 0) { submitters2 = submitters2.concat("; "); } submitters2 = submitters2.concat(u2[j].getLastName()); } } result = submitters1.toLowerCase().compareTo(submitters2.toLowerCase()); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted(); Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS)) { // sort by submission status String status1 = getSubmissionStatus(m_state, (AssignmentSubmission) o1); String status2 = getSubmissionStatus(m_state, (AssignmentSubmission) o2); result = status1.compareTo(status2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE)) { Assignment a1 = ((AssignmentSubmission) o1).getAssignment(); Assignment a2 = ((AssignmentSubmission) o2).getAssignment(); String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1); String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED)) { // sort by submission released String released1 = (new Boolean(((AssignmentSubmission) o1).getGradeReleased())).toString(); String released2 = (new Boolean(((AssignmentSubmission) o2).getGradeReleased())).toString(); result = released1.compareTo(released2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT)) { // sort by submission's assignment String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle(); String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle(); result = title1.toLowerCase().compareTo(title2.toLowerCase()); } // sort ascending or descending if (m_asc.equals(Boolean.FALSE.toString())) { result = -result; } return result; } // compare
diff --git a/src/main/java/org/easy/scrum/controller/day/GraphHelper.java b/src/main/java/org/easy/scrum/controller/day/GraphHelper.java index 93804d8..40b08ff 100644 --- a/src/main/java/org/easy/scrum/controller/day/GraphHelper.java +++ b/src/main/java/org/easy/scrum/controller/day/GraphHelper.java @@ -1,49 +1,49 @@ package org.easy.scrum.controller.day; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.easy.jsf.d3js.burndown.IterationBurndown; import org.easy.scrum.model.BurnDownType; import org.easy.scrum.model.SprintBE; import org.easy.scrum.model.SprintDayBE; import org.joda.time.LocalDate; public class GraphHelper { public IterationBurndown recalcualteBurndown( final SprintBE sprint, final List<SprintDayBE> days, final BurnDownType burnDownType) { IterationBurndown burnDown = null; if (sprint != null && days != null) { burnDown = new IterationBurndown( new LocalDate(sprint.getStart()), new LocalDate(sprint.getEnd()), - sprint.getPlannedHours()); + sprint.getPlannedHours(), false); List<SprintDayBE> elements = new ArrayList<SprintDayBE>(days); Collections.reverse(elements); for (SprintDayBE day : elements) { if (burnDownType == BurnDownType.UP_SCALING_BEFORE_BURN_DOWN) { addUpscaling(day, burnDown); } burnDown.addDay( new LocalDate(day.getDay()), day.getBurnDown(), day.getComment()); if (burnDownType == BurnDownType.BURN_DOWN_BEFORE_UP_SCALING) { addUpscaling(day, burnDown); } } } return burnDown; } private void addUpscaling(SprintDayBE day, IterationBurndown burnDown) { if (day.getUpscaling() > 0) { burnDown.addDay( new LocalDate(day.getDay()), day.getUpscaling() * (-1), day.getReasonForUpscaling()); } } }
true
true
public IterationBurndown recalcualteBurndown( final SprintBE sprint, final List<SprintDayBE> days, final BurnDownType burnDownType) { IterationBurndown burnDown = null; if (sprint != null && days != null) { burnDown = new IterationBurndown( new LocalDate(sprint.getStart()), new LocalDate(sprint.getEnd()), sprint.getPlannedHours()); List<SprintDayBE> elements = new ArrayList<SprintDayBE>(days); Collections.reverse(elements); for (SprintDayBE day : elements) { if (burnDownType == BurnDownType.UP_SCALING_BEFORE_BURN_DOWN) { addUpscaling(day, burnDown); } burnDown.addDay( new LocalDate(day.getDay()), day.getBurnDown(), day.getComment()); if (burnDownType == BurnDownType.BURN_DOWN_BEFORE_UP_SCALING) { addUpscaling(day, burnDown); } } } return burnDown; }
public IterationBurndown recalcualteBurndown( final SprintBE sprint, final List<SprintDayBE> days, final BurnDownType burnDownType) { IterationBurndown burnDown = null; if (sprint != null && days != null) { burnDown = new IterationBurndown( new LocalDate(sprint.getStart()), new LocalDate(sprint.getEnd()), sprint.getPlannedHours(), false); List<SprintDayBE> elements = new ArrayList<SprintDayBE>(days); Collections.reverse(elements); for (SprintDayBE day : elements) { if (burnDownType == BurnDownType.UP_SCALING_BEFORE_BURN_DOWN) { addUpscaling(day, burnDown); } burnDown.addDay( new LocalDate(day.getDay()), day.getBurnDown(), day.getComment()); if (burnDownType == BurnDownType.BURN_DOWN_BEFORE_UP_SCALING) { addUpscaling(day, burnDown); } } } return burnDown; }
diff --git a/src/test/java/org/atlasapi/application/v3/ApplicationConfigurationTranslatorTest.java b/src/test/java/org/atlasapi/application/v3/ApplicationConfigurationTranslatorTest.java index 14c29ef..7bab816 100644 --- a/src/test/java/org/atlasapi/application/v3/ApplicationConfigurationTranslatorTest.java +++ b/src/test/java/org/atlasapi/application/v3/ApplicationConfigurationTranslatorTest.java @@ -1,42 +1,43 @@ package org.atlasapi.application.v3; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import org.atlasapi.application.v3.ApplicationConfiguration; import org.atlasapi.application.v3.ApplicationConfigurationTranslator; import org.atlasapi.media.entity.Publisher; import org.junit.Test; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.mongodb.DBObject; public class ApplicationConfigurationTranslatorTest { private final ApplicationConfigurationTranslator codec = new ApplicationConfigurationTranslator(); @Test public void testEncodesAndDecodesApplicationConfiguration() { ApplicationConfiguration config = ApplicationConfiguration.defaultConfiguration() - .request(Publisher.PA) - .approve(Publisher.PA) - .enable(Publisher.PA) - .copyWithPrecedence(ImmutableList.of(Publisher.PA, Publisher.BBC)) + .enable(Publisher.BBC) + .request(Publisher.ITV) + .approve(Publisher.ITV) + .enable(Publisher.ITV) + .copyWithPrecedence(ImmutableList.of(Publisher.ITV, Publisher.BBC)) .copyWithWritableSources(ImmutableSet.of(Publisher.ITV)); DBObject dbo = codec.toDBObject(config); ApplicationConfiguration decoded = codec.fromDBObject(dbo); - assertTrue(decoded.isEnabled(Publisher.PA)); + assertTrue(decoded.isEnabled(Publisher.ITV)); assertTrue(decoded.isEnabled(Publisher.BBC)); - assertThat(decoded.orderdPublishers().get(0), is(Publisher.PA)); + assertThat(decoded.orderdPublishers().get(0), is(Publisher.ITV)); assertThat(decoded.orderdPublishers().get(1), is(Publisher.BBC)); assertTrue(decoded.canWrite(Publisher.ITV)); } }
false
true
public void testEncodesAndDecodesApplicationConfiguration() { ApplicationConfiguration config = ApplicationConfiguration.defaultConfiguration() .request(Publisher.PA) .approve(Publisher.PA) .enable(Publisher.PA) .copyWithPrecedence(ImmutableList.of(Publisher.PA, Publisher.BBC)) .copyWithWritableSources(ImmutableSet.of(Publisher.ITV)); DBObject dbo = codec.toDBObject(config); ApplicationConfiguration decoded = codec.fromDBObject(dbo); assertTrue(decoded.isEnabled(Publisher.PA)); assertTrue(decoded.isEnabled(Publisher.BBC)); assertThat(decoded.orderdPublishers().get(0), is(Publisher.PA)); assertThat(decoded.orderdPublishers().get(1), is(Publisher.BBC)); assertTrue(decoded.canWrite(Publisher.ITV)); }
public void testEncodesAndDecodesApplicationConfiguration() { ApplicationConfiguration config = ApplicationConfiguration.defaultConfiguration() .enable(Publisher.BBC) .request(Publisher.ITV) .approve(Publisher.ITV) .enable(Publisher.ITV) .copyWithPrecedence(ImmutableList.of(Publisher.ITV, Publisher.BBC)) .copyWithWritableSources(ImmutableSet.of(Publisher.ITV)); DBObject dbo = codec.toDBObject(config); ApplicationConfiguration decoded = codec.fromDBObject(dbo); assertTrue(decoded.isEnabled(Publisher.ITV)); assertTrue(decoded.isEnabled(Publisher.BBC)); assertThat(decoded.orderdPublishers().get(0), is(Publisher.ITV)); assertThat(decoded.orderdPublishers().get(1), is(Publisher.BBC)); assertTrue(decoded.canWrite(Publisher.ITV)); }
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java index a48e4117..d5279ae6 100755 --- a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java +++ b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java @@ -1,4765 +1,4765 @@ /* * * 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.internal.policy.impl; import android.app.ActivityManager; import android.app.ActivityManagerNative; import android.app.ProgressDialog; import android.app.SearchManager; import android.app.UiModeManager; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.res.CompatibilityInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.database.ContentObserver; import android.graphics.PixelFormat; import android.graphics.Rect; import android.media.AudioManager; import android.media.IAudioService; import android.media.Ringtone; import android.media.RingtoneManager; import android.os.Bundle; import android.os.FactoryTest; import android.os.Handler; import android.os.IBinder; import android.os.IRemoteCallback; import android.os.Looper; import android.os.Message; import android.os.Messenger; import android.os.PowerManager; import android.os.RemoteException; import android.os.ServiceManager; import android.os.SystemClock; import android.os.SystemProperties; import android.os.UEventObserver; import android.os.UserHandle; import android.os.Vibrator; import android.provider.Settings; import com.android.internal.R; import com.android.internal.policy.PolicyManager; import com.android.internal.policy.impl.keyguard.KeyguardViewManager; import com.android.internal.policy.impl.keyguard.KeyguardViewMediator; import com.android.internal.statusbar.IStatusBarService; import com.android.internal.telephony.ITelephony; import com.android.internal.widget.PointerLocationView; import android.util.DisplayMetrics; import android.util.EventLog; import android.util.Log; import android.util.Slog; import android.util.SparseArray; import android.view.Display; import android.view.Gravity; import android.view.HapticFeedbackConstants; import android.view.IApplicationToken; import android.view.IWindowManager; import android.view.InputChannel; import android.view.InputDevice; import android.view.InputEvent; import android.view.InputEventReceiver; import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.WindowManagerGlobal; import android.view.WindowOrientationListener; import android.view.Surface; import android.view.View; import android.view.ViewConfiguration; import android.view.Window; import android.view.WindowManager; import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW; import static android.view.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN; import static android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN; import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN; import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR; import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS; import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED; import static android.view.WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD; import static android.view.WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON; import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS; import static android.view.WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST; import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE; import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING; import static android.view.WindowManager.LayoutParams.LAST_APPLICATION_WINDOW; import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA; import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA_OVERLAY; import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_PANEL; import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING; import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL; import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; import static android.view.WindowManager.LayoutParams.TYPE_DISPLAY_OVERLAY; import static android.view.WindowManager.LayoutParams.TYPE_DRAG; import static android.view.WindowManager.LayoutParams.TYPE_DREAM; import static android.view.WindowManager.LayoutParams.TYPE_HIDDEN_NAV_CONSUMER; import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD; import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG; import static android.view.WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY; import static android.view.WindowManager.LayoutParams.TYPE_PHONE; import static android.view.WindowManager.LayoutParams.TYPE_PRIORITY_PHONE; import static android.view.WindowManager.LayoutParams.TYPE_RECENTS_OVERLAY; import static android.view.WindowManager.LayoutParams.TYPE_SEARCH_BAR; import static android.view.WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY; import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR; import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL; import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL; import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG; import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ERROR; import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD; import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG; import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY; import static android.view.WindowManager.LayoutParams.TYPE_TOAST; import static android.view.WindowManager.LayoutParams.TYPE_UNIVERSE_BACKGROUND; import static android.view.WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY; import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER; import static android.view.WindowManager.LayoutParams.TYPE_POINTER; import static android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR; import static android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR_PANEL; import static android.view.WindowManager.LayoutParams.TYPE_BOOT_PROGRESS; import android.view.WindowManagerPolicy; import static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_ABSENT; import static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_OPEN; import static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_CLOSED; import android.view.KeyCharacterMap.FallbackAction; import android.view.accessibility.AccessibilityEvent; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; /** * WindowManagerPolicy implementation for the Android phone UI. This * introduces a new method suffix, Lp, for an internal lock of the * PhoneWindowManager. This is used to protect some internal state, and * can be acquired with either thw Lw and Li lock held, so has the restrictions * of both of those when held. */ public class PhoneWindowManager implements WindowManagerPolicy { static final String TAG = "WindowManager"; static final boolean DEBUG = false; static final boolean localLOGV = false; static final boolean DEBUG_LAYOUT = false; static final boolean DEBUG_INPUT = false; static final boolean DEBUG_STARTING_WINDOW = false; static final boolean SHOW_STARTING_ANIMATIONS = true; static final boolean SHOW_PROCESSES_ON_ALT_MENU = false; static final int LONG_PRESS_POWER_NOTHING = 0; static final int LONG_PRESS_POWER_GLOBAL_ACTIONS = 1; static final int LONG_PRESS_POWER_SHUT_OFF = 2; static final int LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM = 3; // These need to match the documentation/constant in // core/res/res/values/config.xml static final int LONG_PRESS_HOME_NOTHING = 0; static final int LONG_PRESS_HOME_RECENT_DIALOG = 1; static final int LONG_PRESS_HOME_RECENT_SYSTEM_UI = 2; static final int APPLICATION_MEDIA_SUBLAYER = -2; static final int APPLICATION_MEDIA_OVERLAY_SUBLAYER = -1; static final int APPLICATION_PANEL_SUBLAYER = 1; static final int APPLICATION_SUB_PANEL_SUBLAYER = 2; static public final String SYSTEM_DIALOG_REASON_KEY = "reason"; static public final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions"; static public final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps"; static public final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey"; static public final String SYSTEM_DIALOG_REASON_ASSIST = "assist"; /** * These are the system UI flags that, when changing, can cause the layout * of the screen to change. */ static final int SYSTEM_UI_CHANGING_LAYOUT = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN; /* Table of Application Launch keys. Maps from key codes to intent categories. * * These are special keys that are used to launch particular kinds of applications, * such as a web browser. HID defines nearly a hundred of them in the Consumer (0x0C) * usage page. We don't support quite that many yet... */ static SparseArray<String> sApplicationLaunchKeyCategories; static { sApplicationLaunchKeyCategories = new SparseArray<String>(); sApplicationLaunchKeyCategories.append( KeyEvent.KEYCODE_EXPLORER, Intent.CATEGORY_APP_BROWSER); sApplicationLaunchKeyCategories.append( KeyEvent.KEYCODE_ENVELOPE, Intent.CATEGORY_APP_EMAIL); sApplicationLaunchKeyCategories.append( KeyEvent.KEYCODE_CONTACTS, Intent.CATEGORY_APP_CONTACTS); sApplicationLaunchKeyCategories.append( KeyEvent.KEYCODE_CALENDAR, Intent.CATEGORY_APP_CALENDAR); sApplicationLaunchKeyCategories.append( KeyEvent.KEYCODE_MUSIC, Intent.CATEGORY_APP_MUSIC); sApplicationLaunchKeyCategories.append( KeyEvent.KEYCODE_CALCULATOR, Intent.CATEGORY_APP_CALCULATOR); } /** * Lock protecting internal state. Must not call out into window * manager with lock held. (This lock will be acquired in places * where the window manager is calling in with its own lock held.) */ final Object mLock = new Object(); Context mContext; IWindowManager mWindowManager; WindowManagerFuncs mWindowManagerFuncs; PowerManager mPowerManager; IStatusBarService mStatusBarService; final Object mServiceAquireLock = new Object(); Vibrator mVibrator; // Vibrator for giving feedback of orientation changes SearchManager mSearchManager; // Vibrator pattern for haptic feedback of a long press. long[] mLongPressVibePattern; // Vibrator pattern for haptic feedback of virtual key press. long[] mVirtualKeyVibePattern; // Vibrator pattern for a short vibration. long[] mKeyboardTapVibePattern; // Vibrator pattern for haptic feedback during boot when safe mode is disabled. long[] mSafeModeDisabledVibePattern; // Vibrator pattern for haptic feedback during boot when safe mode is enabled. long[] mSafeModeEnabledVibePattern; /** If true, hitting shift & menu will broadcast Intent.ACTION_BUG_REPORT */ boolean mEnableShiftMenuBugReports = false; boolean mHeadless; boolean mSafeMode; WindowState mStatusBar = null; boolean mHasSystemNavBar; int mStatusBarHeight; WindowState mNavigationBar = null; boolean mHasNavigationBar = false; boolean mCanHideNavigationBar = false; boolean mNavigationBarCanMove = false; // can the navigation bar ever move to the side? boolean mNavigationBarOnBottom = true; // is the navigation bar on the bottom *right now*? int[] mNavigationBarHeightForRotation = new int[4]; int[] mNavigationBarWidthForRotation = new int[4]; WindowState mKeyguard = null; KeyguardViewMediator mKeyguardMediator; GlobalActions mGlobalActions; volatile boolean mPowerKeyHandled; // accessed from input reader and handler thread boolean mPendingPowerKeyUpCanceled; Handler mHandler; WindowState mLastInputMethodWindow = null; WindowState mLastInputMethodTargetWindow = null; static final int RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS = 0; static final int RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW = 1; static final int RECENT_APPS_BEHAVIOR_DISMISS = 2; static final int RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH = 3; RecentApplicationsDialog mRecentAppsDialog; int mRecentAppsDialogHeldModifiers; boolean mLanguageSwitchKeyPressed; int mLidState = LID_ABSENT; boolean mHaveBuiltInKeyboard; boolean mSystemReady; boolean mSystemBooted; boolean mHdmiPlugged; int mDockMode = Intent.EXTRA_DOCK_STATE_UNDOCKED; int mLidOpenRotation; int mCarDockRotation; int mDeskDockRotation; int mHdmiRotation; boolean mHdmiRotationLock; int mUserRotationMode = WindowManagerPolicy.USER_ROTATION_FREE; int mUserRotation = Surface.ROTATION_0; boolean mAccelerometerDefault; int mAllowAllRotations = -1; boolean mCarDockEnablesAccelerometer; boolean mDeskDockEnablesAccelerometer; int mLidKeyboardAccessibility; int mLidNavigationAccessibility; boolean mLidControlsSleep; int mLongPressOnPowerBehavior = -1; boolean mScreenOnEarly = false; boolean mScreenOnFully = false; boolean mOrientationSensorEnabled = false; int mCurrentAppOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; boolean mHasSoftInput = false; int mPointerLocationMode = 0; // guarded by mLock // The last window we were told about in focusChanged. WindowState mFocusedWindow; IApplicationToken mFocusedApp; // Behavior of volume wake boolean mVolumeWakeScreen; // Behavior of volbtn music controls boolean mVolBtnMusicControls; boolean mIsLongPress; private static final class PointerLocationInputEventReceiver extends InputEventReceiver { private final PointerLocationView mView; public PointerLocationInputEventReceiver(InputChannel inputChannel, Looper looper, PointerLocationView view) { super(inputChannel, looper); mView = view; } @Override public void onInputEvent(InputEvent event) { boolean handled = false; try { if (event instanceof MotionEvent && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { final MotionEvent motionEvent = (MotionEvent)event; mView.addPointerEvent(motionEvent); handled = true; } } finally { finishInputEvent(event, handled); } } } // Pointer location view state, only modified on the mHandler Looper. PointerLocationInputEventReceiver mPointerLocationInputEventReceiver; PointerLocationView mPointerLocationView; InputChannel mPointerLocationInputChannel; // The current size of the screen; really; (ir)regardless of whether the status // bar can be hidden or not int mUnrestrictedScreenLeft, mUnrestrictedScreenTop; int mUnrestrictedScreenWidth, mUnrestrictedScreenHeight; // The current size of the screen; these may be different than (0,0)-(dw,dh) // if the status bar can't be hidden; in that case it effectively carves out // that area of the display from all other windows. int mRestrictedScreenLeft, mRestrictedScreenTop; int mRestrictedScreenWidth, mRestrictedScreenHeight; // During layout, the current screen borders accounting for any currently // visible system UI elements. int mSystemLeft, mSystemTop, mSystemRight, mSystemBottom; // For applications requesting stable content insets, these are them. int mStableLeft, mStableTop, mStableRight, mStableBottom; // For applications requesting stable content insets but have also set the // fullscreen window flag, these are the stable dimensions without the status bar. int mStableFullscreenLeft, mStableFullscreenTop; int mStableFullscreenRight, mStableFullscreenBottom; // During layout, the current screen borders with all outer decoration // (status bar, input method dock) accounted for. int mCurLeft, mCurTop, mCurRight, mCurBottom; // During layout, the frame in which content should be displayed // to the user, accounting for all screen decoration except for any // space they deem as available for other content. This is usually // the same as mCur*, but may be larger if the screen decor has supplied // content insets. int mContentLeft, mContentTop, mContentRight, mContentBottom; // During layout, the current screen borders along which input method // windows are placed. int mDockLeft, mDockTop, mDockRight, mDockBottom; // During layout, the layer at which the doc window is placed. int mDockLayer; // During layout, this is the layer of the status bar. int mStatusBarLayer; int mLastSystemUiFlags; // Bits that we are in the process of clearing, so we want to prevent // them from being set by applications until everything has been updated // to have them clear. int mResettingSystemUiFlags = 0; // Bits that we are currently always keeping cleared. int mForceClearedSystemUiFlags = 0; // What we last reported to system UI about whether the compatibility // menu needs to be displayed. boolean mLastFocusNeedsMenu = false; FakeWindow mHideNavFakeWindow = null; static final Rect mTmpParentFrame = new Rect(); static final Rect mTmpDisplayFrame = new Rect(); static final Rect mTmpContentFrame = new Rect(); static final Rect mTmpVisibleFrame = new Rect(); static final Rect mTmpNavigationFrame = new Rect(); WindowState mTopFullscreenOpaqueWindowState; boolean mTopIsFullscreen; boolean mForceStatusBar; boolean mForceStatusBarFromKeyguard; boolean mHideLockScreen; // States of keyguard dismiss. private static final int DISMISS_KEYGUARD_NONE = 0; // Keyguard not being dismissed. private static final int DISMISS_KEYGUARD_START = 1; // Keyguard needs to be dismissed. private static final int DISMISS_KEYGUARD_CONTINUE = 2; // Keyguard has been dismissed. int mDismissKeyguard = DISMISS_KEYGUARD_NONE; /** The window that is currently dismissing the keyguard. Dismissing the keyguard must only * be done once per window. */ private WindowState mWinDismissingKeyguard; boolean mShowingLockscreen; boolean mShowingDream; boolean mDreamingLockscreen; boolean mHomePressed; boolean mHomeLongPressed; Intent mHomeIntent; Intent mCarDockIntent; Intent mDeskDockIntent; boolean mSearchKeyShortcutPending; boolean mConsumeSearchKeyUp; boolean mAssistKeyLongPressed; // support for activating the lock screen while the screen is on boolean mAllowLockscreenWhenOn; int mLockScreenTimeout; boolean mLockScreenTimerActive; // Behavior of ENDCALL Button. (See Settings.System.END_BUTTON_BEHAVIOR.) int mEndcallBehavior; // Behavior of POWER button while in-call and screen on. // (See Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR.) int mIncallPowerBehavior; Display mDisplay; int mLandscapeRotation = 0; // default landscape rotation int mSeascapeRotation = 0; // "other" landscape rotation, 180 degrees from mLandscapeRotation int mPortraitRotation = 0; // default portrait rotation int mUpsideDownRotation = 0; // "other" portrait rotation // What we do when the user long presses on home private int mLongPressOnHomeBehavior = -1; // Screenshot trigger states // Time to volume and power must be pressed within this interval of each other. private static final long SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS = 150; // Increase the chord delay when taking a screenshot from the keyguard private static final float KEYGUARD_SCREENSHOT_CHORD_DELAY_MULTIPLIER = 2.5f; private boolean mScreenshotChordEnabled; private boolean mVolumeDownKeyTriggered; private long mVolumeDownKeyTime; private boolean mVolumeDownKeyConsumedByScreenshotChord; private boolean mVolumeUpKeyTriggered; private boolean mPowerKeyTriggered; private long mPowerKeyTime; SettingsObserver mSettingsObserver; ShortcutManager mShortcutManager; PowerManager.WakeLock mBroadcastWakeLock; boolean mHavePendingMediaKeyRepeatWithWakeLock; // Fallback actions by key code. private final SparseArray<KeyCharacterMap.FallbackAction> mFallbackActions = new SparseArray<KeyCharacterMap.FallbackAction>(); private static final int MSG_ENABLE_POINTER_LOCATION = 1; private static final int MSG_DISABLE_POINTER_LOCATION = 2; private static final int MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK = 3; private static final int MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK = 4; private class PolicyHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_ENABLE_POINTER_LOCATION: enablePointerLocation(); break; case MSG_DISABLE_POINTER_LOCATION: disablePointerLocation(); break; case MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK: dispatchMediaKeyWithWakeLock((KeyEvent)msg.obj); break; case MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK: dispatchMediaKeyRepeatWithWakeLock((KeyEvent)msg.obj); break; } } } private UEventObserver mHDMIObserver = new UEventObserver() { @Override public void onUEvent(UEventObserver.UEvent event) { setHdmiPlugged("1".equals(event.get("SWITCH_STATE"))); } }; class SettingsObserver extends ContentObserver { SettingsObserver(Handler handler) { super(handler); } void observe() { // Observe all users' changes ContentResolver resolver = mContext.getContentResolver(); resolver.registerContentObserver(Settings.System.getUriFor( Settings.System.END_BUTTON_BEHAVIOR), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Secure.getUriFor( Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.System.getUriFor( Settings.System.VOLUME_WAKE_SCREEN), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.System.getUriFor( Settings.System.VOLBTN_MUSIC_CONTROLS), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.System.getUriFor( Settings.System.ACCELEROMETER_ROTATION), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.System.getUriFor( Settings.System.USER_ROTATION), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.System.getUriFor( Settings.System.SCREEN_OFF_TIMEOUT), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.System.getUriFor( Settings.System.POINTER_LOCATION), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Secure.getUriFor( Settings.Secure.DEFAULT_INPUT_METHOD), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.System.getUriFor( "fancy_rotation_anim"), false, this, UserHandle.USER_ALL); updateSettings(); } @Override public void onChange(boolean selfChange) { updateSettings(); updateRotation(false); } } class MyOrientationListener extends WindowOrientationListener { MyOrientationListener(Context context) { super(context); } @Override public void onProposedRotationChanged(int rotation) { if (localLOGV) Log.v(TAG, "onProposedRotationChanged, rotation=" + rotation); updateRotation(false); } } MyOrientationListener mOrientationListener; IStatusBarService getStatusBarService() { synchronized (mServiceAquireLock) { if (mStatusBarService == null) { mStatusBarService = IStatusBarService.Stub.asInterface( ServiceManager.getService("statusbar")); } return mStatusBarService; } } /* * We always let the sensor be switched on by default except when * the user has explicitly disabled sensor based rotation or when the * screen is switched off. */ boolean needSensorRunningLp() { if (mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) { // If the application has explicitly requested to follow the // orientation, then we need to turn the sensor or. return true; } if ((mCarDockEnablesAccelerometer && mDockMode == Intent.EXTRA_DOCK_STATE_CAR) || (mDeskDockEnablesAccelerometer && (mDockMode == Intent.EXTRA_DOCK_STATE_DESK || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK))) { // enable accelerometer if we are docked in a dock that enables accelerometer // orientation management, return true; } if (mUserRotationMode == USER_ROTATION_LOCKED) { // If the setting for using the sensor by default is enabled, then // we will always leave it on. Note that the user could go to // a window that forces an orientation that does not use the // sensor and in theory we could turn it off... however, when next // turning it on we won't have a good value for the current // orientation for a little bit, which can cause orientation // changes to lag, so we'd like to keep it always on. (It will // still be turned off when the screen is off.) return false; } return true; } /* * Various use cases for invoking this function * screen turning off, should always disable listeners if already enabled * screen turned on and current app has sensor based orientation, enable listeners * if not already enabled * screen turned on and current app does not have sensor orientation, disable listeners if * already enabled * screen turning on and current app has sensor based orientation, enable listeners if needed * screen turning on and current app has nosensor based orientation, do nothing */ void updateOrientationListenerLp() { if (!mOrientationListener.canDetectOrientation()) { // If sensor is turned off or nonexistent for some reason return; } //Could have been invoked due to screen turning on or off or //change of the currently visible window's orientation if (localLOGV) Log.v(TAG, "Screen status="+mScreenOnEarly+ ", current orientation="+mCurrentAppOrientation+ ", SensorEnabled="+mOrientationSensorEnabled); boolean disable = true; if (mScreenOnEarly) { if (needSensorRunningLp()) { disable = false; //enable listener if not already enabled if (!mOrientationSensorEnabled) { mOrientationListener.enable(); if(localLOGV) Log.v(TAG, "Enabling listeners"); mOrientationSensorEnabled = true; } } } //check if sensors need to be disabled if (disable && mOrientationSensorEnabled) { mOrientationListener.disable(); if(localLOGV) Log.v(TAG, "Disabling listeners"); mOrientationSensorEnabled = false; } } private void interceptPowerKeyDown(boolean handled) { mPowerKeyHandled = handled; if (!handled) { mHandler.postDelayed(mPowerLongPress, ViewConfiguration.getGlobalActionKeyTimeout()); } } private boolean interceptPowerKeyUp(boolean canceled) { if (!mPowerKeyHandled) { mHandler.removeCallbacks(mPowerLongPress); return !canceled; } return false; } private void cancelPendingPowerKeyAction() { if (!mPowerKeyHandled) { mHandler.removeCallbacks(mPowerLongPress); } if (mPowerKeyTriggered) { mPendingPowerKeyUpCanceled = true; } } /** * When a volumeup-key longpress expires, skip songs based on key press */ Runnable mVolumeUpLongPress = new Runnable() { public void run() { // set the long press flag to true mIsLongPress = true; // Shamelessly copied from Kmobs LockScreen controls, works for Pandora, etc... sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_NEXT); }; }; /** * When a volumedown-key longpress expires, skip songs based on key press */ Runnable mVolumeDownLongPress = new Runnable() { public void run() { // set the long press flag to true mIsLongPress = true; // Shamelessly copied from Kmobs LockScreen controls, works for Pandora, etc... sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_PREVIOUS); }; }; private void sendMediaButtonEvent(int code) { long eventtime = SystemClock.uptimeMillis(); Intent keyIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null); KeyEvent keyEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, code, 0); keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent); mContext.sendOrderedBroadcast(keyIntent, null); keyEvent = KeyEvent.changeAction(keyEvent, KeyEvent.ACTION_UP); keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent); mContext.sendOrderedBroadcast(keyIntent, null); } void handleVolumeLongPress(int keycode) { mHandler.postDelayed(keycode == KeyEvent.KEYCODE_VOLUME_UP ? mVolumeUpLongPress : mVolumeDownLongPress, ViewConfiguration.getLongPressTimeout()); } void handleVolumeLongPressAbort() { mHandler.removeCallbacks(mVolumeUpLongPress); mHandler.removeCallbacks(mVolumeDownLongPress); } private void interceptScreenshotChord() { if (mScreenshotChordEnabled && mVolumeDownKeyTriggered && mPowerKeyTriggered && !mVolumeUpKeyTriggered) { final long now = SystemClock.uptimeMillis(); if (now <= mVolumeDownKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS && now <= mPowerKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS) { mVolumeDownKeyConsumedByScreenshotChord = true; cancelPendingPowerKeyAction(); mHandler.postDelayed(mScreenshotChordLongPress, getScreenshotChordLongPressDelay()); } } } private long getScreenshotChordLongPressDelay() { if (mKeyguardMediator.isShowing()) { // Double the time it takes to take a screenshot from the keyguard return (long) (KEYGUARD_SCREENSHOT_CHORD_DELAY_MULTIPLIER * ViewConfiguration.getGlobalActionKeyTimeout()); } else { return ViewConfiguration.getGlobalActionKeyTimeout(); } } private void cancelPendingScreenshotChordAction() { mHandler.removeCallbacks(mScreenshotChordLongPress); } private final Runnable mPowerLongPress = new Runnable() { @Override public void run() { // The context isn't read if (mLongPressOnPowerBehavior < 0) { mLongPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnPowerBehavior); } int resolvedBehavior = mLongPressOnPowerBehavior; if (FactoryTest.isLongPressOnPowerOffEnabled()) { resolvedBehavior = LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM; } switch (resolvedBehavior) { case LONG_PRESS_POWER_NOTHING: break; case LONG_PRESS_POWER_GLOBAL_ACTIONS: mPowerKeyHandled = true; if (!performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false)) { performAuditoryFeedbackForAccessibilityIfNeed(); } sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS); showGlobalActionsDialog(); break; case LONG_PRESS_POWER_SHUT_OFF: case LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM: mPowerKeyHandled = true; performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false); sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS); mWindowManagerFuncs.shutdown(resolvedBehavior == LONG_PRESS_POWER_SHUT_OFF); break; } } }; private final Runnable mScreenshotChordLongPress = new Runnable() { public void run() { takeScreenshot(); } }; void showGlobalActionsDialog() { if (mGlobalActions == null) { mGlobalActions = new GlobalActions(mContext, mWindowManagerFuncs); } final boolean keyguardShowing = keyguardIsShowingTq(); mGlobalActions.showDialog(keyguardShowing, isDeviceProvisioned()); if (keyguardShowing) { // since it took two seconds of long press to bring this up, // poke the wake lock so they have some time to see the dialog. mKeyguardMediator.userActivity(); } } boolean isDeviceProvisioned() { return Settings.Global.getInt( mContext.getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 0) != 0; } private void handleLongPressOnHome() { // We can't initialize this in init() since the configuration hasn't been loaded yet. if (mLongPressOnHomeBehavior < 0) { mLongPressOnHomeBehavior = mContext.getResources().getInteger(R.integer.config_longPressOnHomeBehavior); if (mLongPressOnHomeBehavior < LONG_PRESS_HOME_NOTHING || mLongPressOnHomeBehavior > LONG_PRESS_HOME_RECENT_SYSTEM_UI) { mLongPressOnHomeBehavior = LONG_PRESS_HOME_NOTHING; } } if (mLongPressOnHomeBehavior != LONG_PRESS_HOME_NOTHING) { performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false); sendCloseSystemWindows(SYSTEM_DIALOG_REASON_RECENT_APPS); // Eat the longpress so it won't dismiss the recent apps dialog when // the user lets go of the home key mHomeLongPressed = true; } if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_DIALOG) { showOrHideRecentAppsDialog(RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS); } else if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI) { try { IStatusBarService statusbar = getStatusBarService(); if (statusbar != null) { statusbar.toggleRecentApps(); } } catch (RemoteException e) { Slog.e(TAG, "RemoteException when showing recent apps", e); // re-acquire status bar service next time it is needed. mStatusBarService = null; } } } /** * Create (if necessary) and show or dismiss the recent apps dialog according * according to the requested behavior. */ void showOrHideRecentAppsDialog(final int behavior) { mHandler.post(new Runnable() { @Override public void run() { if (mRecentAppsDialog == null) { mRecentAppsDialog = new RecentApplicationsDialog(mContext); } if (mRecentAppsDialog.isShowing()) { switch (behavior) { case RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS: case RECENT_APPS_BEHAVIOR_DISMISS: mRecentAppsDialog.dismiss(); break; case RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH: mRecentAppsDialog.dismissAndSwitch(); break; case RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW: default: break; } } else { switch (behavior) { case RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS: mRecentAppsDialog.show(); break; case RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW: try { mWindowManager.setInTouchMode(false); } catch (RemoteException e) { } mRecentAppsDialog.show(); break; case RECENT_APPS_BEHAVIOR_DISMISS: case RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH: default: break; } } } }); } /** {@inheritDoc} */ public void init(Context context, IWindowManager windowManager, WindowManagerFuncs windowManagerFuncs) { mContext = context; mWindowManager = windowManager; mWindowManagerFuncs = windowManagerFuncs; mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0")); if (!mHeadless) { // don't create KeyguardViewMediator if headless mKeyguardMediator = new KeyguardViewMediator(context, null); } mHandler = new PolicyHandler(); mOrientationListener = new MyOrientationListener(mContext); try { mOrientationListener.setCurrentRotation(windowManager.getRotation()); } catch (RemoteException ex) { } mSettingsObserver = new SettingsObserver(mHandler); mSettingsObserver.observe(); mShortcutManager = new ShortcutManager(context, mHandler); mShortcutManager.observe(); mHomeIntent = new Intent(Intent.ACTION_MAIN, null); mHomeIntent.addCategory(Intent.CATEGORY_HOME); mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mCarDockIntent = new Intent(Intent.ACTION_MAIN, null); mCarDockIntent.addCategory(Intent.CATEGORY_CAR_DOCK); mCarDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mDeskDockIntent = new Intent(Intent.ACTION_MAIN, null); mDeskDockIntent.addCategory(Intent.CATEGORY_DESK_DOCK); mDeskDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE); mBroadcastWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "PhoneWindowManager.mBroadcastWakeLock"); mEnableShiftMenuBugReports = "1".equals(SystemProperties.get("ro.debuggable")); mLidOpenRotation = readRotation( com.android.internal.R.integer.config_lidOpenRotation); mCarDockRotation = readRotation( com.android.internal.R.integer.config_carDockRotation); mDeskDockRotation = readRotation( com.android.internal.R.integer.config_deskDockRotation); mCarDockEnablesAccelerometer = mContext.getResources().getBoolean( com.android.internal.R.bool.config_carDockEnablesAccelerometer); mDeskDockEnablesAccelerometer = mContext.getResources().getBoolean( com.android.internal.R.bool.config_deskDockEnablesAccelerometer); mLidKeyboardAccessibility = mContext.getResources().getInteger( com.android.internal.R.integer.config_lidKeyboardAccessibility); mLidNavigationAccessibility = mContext.getResources().getInteger( com.android.internal.R.integer.config_lidNavigationAccessibility); mLidControlsSleep = mContext.getResources().getBoolean( com.android.internal.R.bool.config_lidControlsSleep); // register for dock events IntentFilter filter = new IntentFilter(); filter.addAction(UiModeManager.ACTION_ENTER_CAR_MODE); filter.addAction(UiModeManager.ACTION_EXIT_CAR_MODE); filter.addAction(UiModeManager.ACTION_ENTER_DESK_MODE); filter.addAction(UiModeManager.ACTION_EXIT_DESK_MODE); filter.addAction(Intent.ACTION_DOCK_EVENT); Intent intent = context.registerReceiver(mDockReceiver, filter); if (intent != null) { // Retrieve current sticky dock event broadcast. mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED); } // register for dream-related broadcasts filter = new IntentFilter(); filter.addAction(Intent.ACTION_DREAMING_STARTED); filter.addAction(Intent.ACTION_DREAMING_STOPPED); context.registerReceiver(mDreamReceiver, filter); // register for multiuser-relevant broadcasts filter = new IntentFilter(Intent.ACTION_USER_SWITCHED); context.registerReceiver(mMultiuserReceiver, filter); mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE); mLongPressVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_longPressVibePattern); mVirtualKeyVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_virtualKeyVibePattern); mKeyboardTapVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_keyboardTapVibePattern); mSafeModeDisabledVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_safeModeDisabledVibePattern); mSafeModeEnabledVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_safeModeEnabledVibePattern); mScreenshotChordEnabled = mContext.getResources().getBoolean( com.android.internal.R.bool.config_enableScreenshotChord); // Controls rotation and the like. initializeHdmiState(); // Match current screen state. if (mPowerManager.isScreenOn()) { screenTurningOn(null); } else { screenTurnedOff(WindowManagerPolicy.OFF_BECAUSE_OF_USER); } } public void setInitialDisplaySize(Display display, int width, int height, int density) { mDisplay = display; int shortSize, longSize; if (width > height) { shortSize = height; longSize = width; mLandscapeRotation = Surface.ROTATION_0; mSeascapeRotation = Surface.ROTATION_180; if (mContext.getResources().getBoolean( com.android.internal.R.bool.config_reverseDefaultRotation)) { mPortraitRotation = Surface.ROTATION_90; mUpsideDownRotation = Surface.ROTATION_270; } else { mPortraitRotation = Surface.ROTATION_270; mUpsideDownRotation = Surface.ROTATION_90; } } else { shortSize = width; longSize = height; mPortraitRotation = Surface.ROTATION_0; mUpsideDownRotation = Surface.ROTATION_180; if (mContext.getResources().getBoolean( com.android.internal.R.bool.config_reverseDefaultRotation)) { mLandscapeRotation = Surface.ROTATION_270; mSeascapeRotation = Surface.ROTATION_90; } else { mLandscapeRotation = Surface.ROTATION_90; mSeascapeRotation = Surface.ROTATION_270; } } mStatusBarHeight = mContext.getResources().getDimensionPixelSize( com.android.internal.R.dimen.status_bar_height); // Height of the navigation bar when presented horizontally at bottom mNavigationBarHeightForRotation[mPortraitRotation] = mNavigationBarHeightForRotation[mUpsideDownRotation] = mContext.getResources().getDimensionPixelSize( com.android.internal.R.dimen.navigation_bar_height); mNavigationBarHeightForRotation[mLandscapeRotation] = mNavigationBarHeightForRotation[mSeascapeRotation] = mContext.getResources().getDimensionPixelSize( com.android.internal.R.dimen.navigation_bar_height_landscape); // Width of the navigation bar when presented vertically along one side mNavigationBarWidthForRotation[mPortraitRotation] = mNavigationBarWidthForRotation[mUpsideDownRotation] = mNavigationBarWidthForRotation[mLandscapeRotation] = mNavigationBarWidthForRotation[mSeascapeRotation] = mContext.getResources().getDimensionPixelSize( com.android.internal.R.dimen.navigation_bar_width); // SystemUI (status bar) layout policy int shortSizeDp = shortSize * DisplayMetrics.DENSITY_DEFAULT / density; if (shortSizeDp < 600) { // 0-599dp: "phone" UI with a separate status & navigation bar mHasSystemNavBar = false; mNavigationBarCanMove = true; } else if (shortSizeDp < 720) { // 600+dp: "phone" UI with modifications for larger screens mHasSystemNavBar = false; mNavigationBarCanMove = false; } if (!mHasSystemNavBar) { mHasNavigationBar = mContext.getResources().getBoolean( com.android.internal.R.bool.config_showNavigationBar); // Allow a system property to override this. Used by the emulator. // See also hasNavigationBar(). String navBarOverride = SystemProperties.get("qemu.hw.mainkeys"); if (! "".equals(navBarOverride)) { if (navBarOverride.equals("1")) mHasNavigationBar = false; else if (navBarOverride.equals("0")) mHasNavigationBar = true; } } else { mHasNavigationBar = false; } if (mHasSystemNavBar) { // The system bar is always at the bottom. If you are watching // a video in landscape, we don't need to hide it if we can still // show a 16:9 aspect ratio with it. int longSizeDp = longSize * DisplayMetrics.DENSITY_DEFAULT / density; int barHeightDp = mNavigationBarHeightForRotation[mLandscapeRotation] * DisplayMetrics.DENSITY_DEFAULT / density; int aspect = ((shortSizeDp-barHeightDp) * 16) / longSizeDp; // We have computed the aspect ratio with the bar height taken // out to be 16:aspect. If this is less than 9, then hiding // the navigation bar will provide more useful space for wide // screen movies. mCanHideNavigationBar = aspect < 9; } else if (mHasNavigationBar) { // The navigation bar is at the right in landscape; it seems always // useful to hide it for showing a video. mCanHideNavigationBar = true; } else { mCanHideNavigationBar = false; } // For demo purposes, allow the rotation of the HDMI display to be controlled. // By default, HDMI locks rotation to landscape. if ("portrait".equals(SystemProperties.get("persist.demo.hdmirotation"))) { mHdmiRotation = mPortraitRotation; } else { mHdmiRotation = mLandscapeRotation; } mHdmiRotationLock = SystemProperties.getBoolean("persist.demo.hdmirotationlock", true); } public void updateSettings() { ContentResolver resolver = mContext.getContentResolver(); boolean updateRotation = false; synchronized (mLock) { mEndcallBehavior = Settings.System.getIntForUser(resolver, Settings.System.END_BUTTON_BEHAVIOR, Settings.System.END_BUTTON_BEHAVIOR_DEFAULT, UserHandle.USER_CURRENT); mIncallPowerBehavior = Settings.Secure.getIntForUser(resolver, Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR, Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_DEFAULT, UserHandle.USER_CURRENT); mVolumeWakeScreen = (Settings.System.getIntForUser(resolver, Settings.System.VOLUME_WAKE_SCREEN, 0, UserHandle.USER_CURRENT) == 1); mVolBtnMusicControls = (Settings.System.getIntForUser(resolver, Settings.System.VOLBTN_MUSIC_CONTROLS, 1, UserHandle.USER_CURRENT) == 1); // Configure rotation lock. int userRotation = Settings.System.getIntForUser(resolver, Settings.System.USER_ROTATION, Surface.ROTATION_0, UserHandle.USER_CURRENT); if (mUserRotation != userRotation) { mUserRotation = userRotation; updateRotation = true; } int userRotationMode = Settings.System.getIntForUser(resolver, Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) != 0 ? WindowManagerPolicy.USER_ROTATION_FREE : WindowManagerPolicy.USER_ROTATION_LOCKED; if (mUserRotationMode != userRotationMode) { mUserRotationMode = userRotationMode; updateRotation = true; updateOrientationListenerLp(); } if (mSystemReady) { int pointerLocation = Settings.System.getIntForUser(resolver, Settings.System.POINTER_LOCATION, 0, UserHandle.USER_CURRENT); if (mPointerLocationMode != pointerLocation) { mPointerLocationMode = pointerLocation; mHandler.sendEmptyMessage(pointerLocation != 0 ? MSG_ENABLE_POINTER_LOCATION : MSG_DISABLE_POINTER_LOCATION); } } // use screen off timeout setting as the timeout for the lockscreen mLockScreenTimeout = Settings.System.getIntForUser(resolver, Settings.System.SCREEN_OFF_TIMEOUT, 0, UserHandle.USER_CURRENT); String imId = Settings.Secure.getStringForUser(resolver, Settings.Secure.DEFAULT_INPUT_METHOD, UserHandle.USER_CURRENT); boolean hasSoftInput = imId != null && imId.length() > 0; if (mHasSoftInput != hasSoftInput) { mHasSoftInput = hasSoftInput; updateRotation = true; } } if (updateRotation) { updateRotation(true); } } private void enablePointerLocation() { if (mPointerLocationView == null) { mPointerLocationView = new PointerLocationView(mContext); mPointerLocationView.setPrintCoords(false); WindowManager.LayoutParams lp = new WindowManager.LayoutParams( WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT); lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY; lp.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN; if (ActivityManager.isHighEndGfx()) { lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED; lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED; } lp.format = PixelFormat.TRANSLUCENT; lp.setTitle("PointerLocation"); WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); lp.inputFeatures |= WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL; wm.addView(mPointerLocationView, lp); mPointerLocationInputChannel = mWindowManagerFuncs.monitorInput("PointerLocationView"); mPointerLocationInputEventReceiver = new PointerLocationInputEventReceiver(mPointerLocationInputChannel, Looper.myLooper(), mPointerLocationView); } } private void disablePointerLocation() { if (mPointerLocationInputEventReceiver != null) { mPointerLocationInputEventReceiver.dispose(); mPointerLocationInputEventReceiver = null; } if (mPointerLocationInputChannel != null) { mPointerLocationInputChannel.dispose(); mPointerLocationInputChannel = null; } if (mPointerLocationView != null) { WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); wm.removeView(mPointerLocationView); mPointerLocationView = null; } } private int readRotation(int resID) { try { int rotation = mContext.getResources().getInteger(resID); switch (rotation) { case 0: return Surface.ROTATION_0; case 90: return Surface.ROTATION_90; case 180: return Surface.ROTATION_180; case 270: return Surface.ROTATION_270; } } catch (Resources.NotFoundException e) { // fall through } return -1; } /** {@inheritDoc} */ @Override public int checkAddPermission(WindowManager.LayoutParams attrs) { int type = attrs.type; if (type < WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW || type > WindowManager.LayoutParams.LAST_SYSTEM_WINDOW) { return WindowManagerGlobal.ADD_OKAY; } String permission = null; switch (type) { case TYPE_TOAST: // XXX right now the app process has complete control over // this... should introduce a token to let the system // monitor/control what they are doing. break; case TYPE_DREAM: case TYPE_INPUT_METHOD: case TYPE_WALLPAPER: // The window manager will check these. break; case TYPE_PHONE: case TYPE_PRIORITY_PHONE: case TYPE_SYSTEM_ALERT: case TYPE_SYSTEM_ERROR: case TYPE_SYSTEM_OVERLAY: permission = android.Manifest.permission.SYSTEM_ALERT_WINDOW; break; default: permission = android.Manifest.permission.INTERNAL_SYSTEM_WINDOW; } if (permission != null) { if (mContext.checkCallingOrSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { return WindowManagerGlobal.ADD_PERMISSION_DENIED; } } return WindowManagerGlobal.ADD_OKAY; } @Override public boolean checkShowToOwnerOnly(WindowManager.LayoutParams attrs) { // If this switch statement is modified, modify the comment in the declarations of // the type in {@link WindowManager.LayoutParams} as well. switch (attrs.type) { default: // These are the windows that by default are shown only to the user that created // them. If this needs to be overridden, set // {@link WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS} in // {@link WindowManager.LayoutParams}. Note that permission // {@link android.Manifest.permission.INTERNAL_SYSTEM_WINDOW} is required as well. if ((attrs.privateFlags & PRIVATE_FLAG_SHOW_FOR_ALL_USERS) == 0) { return true; } break; // These are the windows that by default are shown to all users. However, to // protect against spoofing, check permissions below. case TYPE_APPLICATION_STARTING: case TYPE_BOOT_PROGRESS: case TYPE_DISPLAY_OVERLAY: case TYPE_HIDDEN_NAV_CONSUMER: case TYPE_KEYGUARD: case TYPE_KEYGUARD_DIALOG: case TYPE_MAGNIFICATION_OVERLAY: case TYPE_NAVIGATION_BAR: case TYPE_NAVIGATION_BAR_PANEL: case TYPE_PHONE: case TYPE_POINTER: case TYPE_PRIORITY_PHONE: case TYPE_RECENTS_OVERLAY: case TYPE_SEARCH_BAR: case TYPE_STATUS_BAR: case TYPE_STATUS_BAR_PANEL: case TYPE_STATUS_BAR_SUB_PANEL: case TYPE_SYSTEM_DIALOG: case TYPE_UNIVERSE_BACKGROUND: case TYPE_VOLUME_OVERLAY: break; } // Check if third party app has set window to system window type. return mContext.checkCallingOrSelfPermission( android.Manifest.permission.INTERNAL_SYSTEM_WINDOW) != PackageManager.PERMISSION_GRANTED; } public void adjustWindowParamsLw(WindowManager.LayoutParams attrs) { switch (attrs.type) { case TYPE_SYSTEM_OVERLAY: case TYPE_SECURE_SYSTEM_OVERLAY: case TYPE_TOAST: // These types of windows can't receive input events. attrs.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; attrs.flags &= ~WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH; break; } } void readLidState() { mLidState = mWindowManagerFuncs.getLidState(); } private boolean isHidden(int accessibilityMode) { switch (accessibilityMode) { case 1: return mLidState == LID_CLOSED; case 2: return mLidState == LID_OPEN; default: return false; } } private boolean isBuiltInKeyboardVisible() { return mHaveBuiltInKeyboard && !isHidden(mLidKeyboardAccessibility); } /** {@inheritDoc} */ public void adjustConfigurationLw(Configuration config, int keyboardPresence, int navigationPresence) { mHaveBuiltInKeyboard = (keyboardPresence & PRESENCE_INTERNAL) != 0; readLidState(); applyLidSwitchState(); if (config.keyboard == Configuration.KEYBOARD_NOKEYS || (keyboardPresence == PRESENCE_INTERNAL && isHidden(mLidKeyboardAccessibility))) { config.hardKeyboardHidden = Configuration.HARDKEYBOARDHIDDEN_YES; if (!mHasSoftInput) { config.keyboardHidden = Configuration.KEYBOARDHIDDEN_YES; } } if (config.navigation == Configuration.NAVIGATION_NONAV || (navigationPresence == PRESENCE_INTERNAL && isHidden(mLidNavigationAccessibility))) { config.navigationHidden = Configuration.NAVIGATIONHIDDEN_YES; } } /** {@inheritDoc} */ public int windowTypeToLayerLw(int type) { if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) { return 2; } switch (type) { case TYPE_UNIVERSE_BACKGROUND: return 1; case TYPE_WALLPAPER: // wallpaper is at the bottom, though the window manager may move it. return 2; case TYPE_PHONE: return 3; case TYPE_SEARCH_BAR: return 4; case TYPE_RECENTS_OVERLAY: case TYPE_SYSTEM_DIALOG: return 5; case TYPE_TOAST: // toasts and the plugged-in battery thing return 6; case TYPE_PRIORITY_PHONE: // SIM errors and unlock. Not sure if this really should be in a high layer. return 7; case TYPE_DREAM: // used for Dreams (screensavers with TYPE_DREAM windows) return 8; case TYPE_SYSTEM_ALERT: // like the ANR / app crashed dialogs return 9; case TYPE_INPUT_METHOD: // on-screen keyboards and other such input method user interfaces go here. return 10; case TYPE_INPUT_METHOD_DIALOG: // on-screen keyboards and other such input method user interfaces go here. return 11; case TYPE_KEYGUARD: // the keyguard; nothing on top of these can take focus, since they are // responsible for power management when displayed. return 12; case TYPE_KEYGUARD_DIALOG: return 13; case TYPE_STATUS_BAR_SUB_PANEL: return 14; case TYPE_STATUS_BAR: return 15; case TYPE_STATUS_BAR_PANEL: return 16; case TYPE_VOLUME_OVERLAY: // the on-screen volume indicator and controller shown when the user // changes the device volume return 17; case TYPE_SYSTEM_OVERLAY: // the on-screen volume indicator and controller shown when the user // changes the device volume return 18; case TYPE_NAVIGATION_BAR: // the navigation bar, if available, shows atop most things return 19; case TYPE_NAVIGATION_BAR_PANEL: // some panels (e.g. search) need to show on top of the navigation bar return 20; case TYPE_SYSTEM_ERROR: // system-level error dialogs return 21; case TYPE_MAGNIFICATION_OVERLAY: // used to highlight the magnified portion of a display return 22; case TYPE_DISPLAY_OVERLAY: // used to simulate secondary display devices return 23; case TYPE_DRAG: // the drag layer: input for drag-and-drop is associated with this window, // which sits above all other focusable windows return 24; case TYPE_SECURE_SYSTEM_OVERLAY: return 25; case TYPE_BOOT_PROGRESS: return 26; case TYPE_POINTER: // the (mouse) pointer layer return 27; case TYPE_HIDDEN_NAV_CONSUMER: return 28; } Log.e(TAG, "Unknown window type: " + type); return 2; } /** {@inheritDoc} */ public int subWindowTypeToLayerLw(int type) { switch (type) { case TYPE_APPLICATION_PANEL: case TYPE_APPLICATION_ATTACHED_DIALOG: return APPLICATION_PANEL_SUBLAYER; case TYPE_APPLICATION_MEDIA: return APPLICATION_MEDIA_SUBLAYER; case TYPE_APPLICATION_MEDIA_OVERLAY: return APPLICATION_MEDIA_OVERLAY_SUBLAYER; case TYPE_APPLICATION_SUB_PANEL: return APPLICATION_SUB_PANEL_SUBLAYER; } Log.e(TAG, "Unknown sub-window type: " + type); return 0; } public int getMaxWallpaperLayer() { return windowTypeToLayerLw(TYPE_STATUS_BAR); } public int getAboveUniverseLayer() { return windowTypeToLayerLw(TYPE_SYSTEM_ERROR); } public boolean hasSystemNavBar() { return mHasSystemNavBar; } public int getNonDecorDisplayWidth(int fullWidth, int fullHeight, int rotation) { if (mHasNavigationBar) { // For a basic navigation bar, when we are in landscape mode we place // the navigation bar to the side. if (mNavigationBarCanMove && fullWidth > fullHeight) { return fullWidth - mNavigationBarWidthForRotation[rotation]; } } return fullWidth; } public int getNonDecorDisplayHeight(int fullWidth, int fullHeight, int rotation) { if (mHasSystemNavBar) { // For the system navigation bar, we always place it at the bottom. return fullHeight - mNavigationBarHeightForRotation[rotation]; } if (mHasNavigationBar) { // For a basic navigation bar, when we are in portrait mode we place // the navigation bar to the bottom. if (!mNavigationBarCanMove || fullWidth < fullHeight) { return fullHeight - mNavigationBarHeightForRotation[rotation]; } } return fullHeight; } public int getConfigDisplayWidth(int fullWidth, int fullHeight, int rotation) { return getNonDecorDisplayWidth(fullWidth, fullHeight, rotation); } public int getConfigDisplayHeight(int fullWidth, int fullHeight, int rotation) { // If we don't have a system nav bar, then there is a separate status // bar at the top of the display. We don't count that as part of the // fixed decor, since it can hide; however, for purposes of configurations, // we do want to exclude it since applications can't generally use that part // of the screen. if (!mHasSystemNavBar) { return getNonDecorDisplayHeight(fullWidth, fullHeight, rotation) - mStatusBarHeight; } return getNonDecorDisplayHeight(fullWidth, fullHeight, rotation); } @Override public boolean doesForceHide(WindowState win, WindowManager.LayoutParams attrs) { return attrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD; } @Override public boolean canBeForceHidden(WindowState win, WindowManager.LayoutParams attrs) { switch (attrs.type) { case TYPE_STATUS_BAR: case TYPE_NAVIGATION_BAR: case TYPE_WALLPAPER: case TYPE_DREAM: case TYPE_UNIVERSE_BACKGROUND: case TYPE_KEYGUARD: return false; default: return true; } } /** {@inheritDoc} */ @Override public View addStartingWindow(IBinder appToken, String packageName, int theme, CompatibilityInfo compatInfo, CharSequence nonLocalizedLabel, int labelRes, int icon, int windowFlags) { if (!SHOW_STARTING_ANIMATIONS) { return null; } if (packageName == null) { return null; } try { Context context = mContext; if (DEBUG_STARTING_WINDOW) Slog.d(TAG, "addStartingWindow " + packageName + ": nonLocalizedLabel=" + nonLocalizedLabel + " theme=" + Integer.toHexString(theme)); if (theme != context.getThemeResId() || labelRes != 0) { try { context = context.createPackageContext(packageName, 0); context.setTheme(theme); } catch (PackageManager.NameNotFoundException e) { // Ignore } } Window win = PolicyManager.makeNewWindow(context); final TypedArray ta = win.getWindowStyle(); if (ta.getBoolean( com.android.internal.R.styleable.Window_windowDisablePreview, false) || ta.getBoolean( com.android.internal.R.styleable.Window_windowShowWallpaper,false)) { return null; } Resources r = context.getResources(); win.setTitle(r.getText(labelRes, nonLocalizedLabel)); win.setType( WindowManager.LayoutParams.TYPE_APPLICATION_STARTING); // Force the window flags: this is a fake window, so it is not really // touchable or focusable by the user. We also add in the ALT_FOCUSABLE_IM // flag because we do know that the next window will take input // focus, so we want to get the IME window up on top of us right away. win.setFlags( windowFlags| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, windowFlags| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); if (!compatInfo.supportsScreen()) { win.addFlags(WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW); } win.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT); final WindowManager.LayoutParams params = win.getAttributes(); params.token = appToken; params.packageName = packageName; params.windowAnimations = win.getWindowStyle().getResourceId( com.android.internal.R.styleable.Window_windowAnimationStyle, 0); params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED; params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS; params.setTitle("Starting " + packageName); WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); View view = win.getDecorView(); if (win.isFloating()) { // Whoops, there is no way to display an animation/preview // of such a thing! After all that work... let's skip it. // (Note that we must do this here because it is in // getDecorView() where the theme is evaluated... maybe // we should peek the floating attribute from the theme // earlier.) return null; } if (DEBUG_STARTING_WINDOW) Slog.d( TAG, "Adding starting window for " + packageName + " / " + appToken + ": " + (view.getParent() != null ? view : null)); wm.addView(view, params); // Only return the view if it was successfully added to the // window manager... which we can tell by it having a parent. return view.getParent() != null ? view : null; } catch (WindowManager.BadTokenException e) { // ignore Log.w(TAG, appToken + " already running, starting window not displayed"); } catch (RuntimeException e) { // don't crash if something else bad happens, for example a // failure loading resources because we are loading from an app // on external storage that has been unmounted. Log.w(TAG, appToken + " failed creating starting window", e); } return null; } /** {@inheritDoc} */ public void removeStartingWindow(IBinder appToken, View window) { if (DEBUG_STARTING_WINDOW) { RuntimeException e = new RuntimeException("here"); e.fillInStackTrace(); Log.v(TAG, "Removing starting window for " + appToken + ": " + window, e); } if (window != null) { WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE); wm.removeView(window); } } /** * Preflight adding a window to the system. * * Currently enforces that three window types are singletons: * <ul> * <li>STATUS_BAR_TYPE</li> * <li>KEYGUARD_TYPE</li> * </ul> * * @param win The window to be added * @param attrs Information about the window to be added * * @return If ok, WindowManagerImpl.ADD_OKAY. If too many singletons, * WindowManagerImpl.ADD_MULTIPLE_SINGLETON */ public int prepareAddWindowLw(WindowState win, WindowManager.LayoutParams attrs) { switch (attrs.type) { case TYPE_STATUS_BAR: mContext.enforceCallingOrSelfPermission( android.Manifest.permission.STATUS_BAR_SERVICE, "PhoneWindowManager"); if (mStatusBar != null) { if (mStatusBar.isAlive()) { return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON; } } mStatusBar = win; break; case TYPE_NAVIGATION_BAR: mContext.enforceCallingOrSelfPermission( android.Manifest.permission.STATUS_BAR_SERVICE, "PhoneWindowManager"); if (mNavigationBar != null) { if (mNavigationBar.isAlive()) { return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON; } } mNavigationBar = win; if (DEBUG_LAYOUT) Log.i(TAG, "NAVIGATION BAR: " + mNavigationBar); break; case TYPE_NAVIGATION_BAR_PANEL: mContext.enforceCallingOrSelfPermission( android.Manifest.permission.STATUS_BAR_SERVICE, "PhoneWindowManager"); break; case TYPE_STATUS_BAR_PANEL: mContext.enforceCallingOrSelfPermission( android.Manifest.permission.STATUS_BAR_SERVICE, "PhoneWindowManager"); break; case TYPE_STATUS_BAR_SUB_PANEL: mContext.enforceCallingOrSelfPermission( android.Manifest.permission.STATUS_BAR_SERVICE, "PhoneWindowManager"); break; case TYPE_KEYGUARD: if (mKeyguard != null) { return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON; } mKeyguard = win; break; } return WindowManagerGlobal.ADD_OKAY; } /** {@inheritDoc} */ public void removeWindowLw(WindowState win) { if (mStatusBar == win) { mStatusBar = null; } else if (mKeyguard == win) { mKeyguard = null; } else if (mNavigationBar == win) { mNavigationBar = null; } } static final boolean PRINT_ANIM = false; /** {@inheritDoc} */ public int selectAnimationLw(WindowState win, int transit) { if (PRINT_ANIM) Log.i(TAG, "selectAnimation in " + win + ": transit=" + transit); if (win == mStatusBar) { if (transit == TRANSIT_EXIT || transit == TRANSIT_HIDE) { return R.anim.dock_top_exit; } else if (transit == TRANSIT_ENTER || transit == TRANSIT_SHOW) { return R.anim.dock_top_enter; } } else if (win == mNavigationBar) { // This can be on either the bottom or the right. if (mNavigationBarOnBottom) { if (transit == TRANSIT_EXIT || transit == TRANSIT_HIDE) { return R.anim.dock_bottom_exit; } else if (transit == TRANSIT_ENTER || transit == TRANSIT_SHOW) { return R.anim.dock_bottom_enter; } } else { if (transit == TRANSIT_EXIT || transit == TRANSIT_HIDE) { return R.anim.dock_right_exit; } else if (transit == TRANSIT_ENTER || transit == TRANSIT_SHOW) { return R.anim.dock_right_enter; } } } if (transit == TRANSIT_PREVIEW_DONE) { if (win.hasAppShownWindows()) { if (PRINT_ANIM) Log.i(TAG, "**** STARTING EXIT"); return com.android.internal.R.anim.app_starting_exit; } } else if (win.getAttrs().type == TYPE_DREAM && mDreamingLockscreen && transit == TRANSIT_ENTER) { // Special case: we are animating in a dream, while the keyguard // is shown. We don't want an animation on the dream, because // we need it shown immediately with the keyguard animating away // to reveal it. return -1; } return 0; } public Animation createForceHideEnterAnimation(boolean onWallpaper) { return AnimationUtils.loadAnimation(mContext, onWallpaper ? com.android.internal.R.anim.lock_screen_wallpaper_behind_enter : com.android.internal.R.anim.lock_screen_behind_enter); } static ITelephony getTelephonyService() { return ITelephony.Stub.asInterface( ServiceManager.checkService(Context.TELEPHONY_SERVICE)); } static IAudioService getAudioService() { IAudioService audioService = IAudioService.Stub.asInterface( ServiceManager.checkService(Context.AUDIO_SERVICE)); if (audioService == null) { Log.w(TAG, "Unable to find IAudioService interface."); } return audioService; } boolean keyguardOn() { return keyguardIsShowingTq() || inKeyguardRestrictedKeyInputMode(); } private static final int[] WINDOW_TYPES_WHERE_HOME_DOESNT_WORK = { WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.TYPE_SYSTEM_ERROR, }; /** {@inheritDoc} */ @Override public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags) { final boolean keyguardOn = keyguardOn(); final int keyCode = event.getKeyCode(); final int repeatCount = event.getRepeatCount(); final int metaState = event.getMetaState(); final int flags = event.getFlags(); final boolean down = event.getAction() == KeyEvent.ACTION_DOWN; final boolean canceled = event.isCanceled(); if (DEBUG_INPUT) { Log.d(TAG, "interceptKeyTi keyCode=" + keyCode + " down=" + down + " repeatCount=" + repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed + " canceled=" + canceled); } // If we think we might have a volume down & power key chord on the way // but we're not sure, then tell the dispatcher to wait a little while and // try again later before dispatching. if (mScreenshotChordEnabled && (flags & KeyEvent.FLAG_FALLBACK) == 0) { if (mVolumeDownKeyTriggered && !mPowerKeyTriggered) { final long now = SystemClock.uptimeMillis(); final long timeoutTime = mVolumeDownKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS; if (now < timeoutTime) { return timeoutTime - now; } } if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN && mVolumeDownKeyConsumedByScreenshotChord) { if (!down) { mVolumeDownKeyConsumedByScreenshotChord = false; } return -1; } } // First we always handle the home key here, so applications // can never break it, although if keyguard is on, we do let // it handle it, because that gives us the correct 5 second // timeout. if (keyCode == KeyEvent.KEYCODE_HOME) { // If we have released the home key, and didn't do anything else // while it was pressed, then it is time to go home! - if (!down) { + if (!down && mHomePressed) { final boolean homeWasLongPressed = mHomeLongPressed; mHomePressed = false; mHomeLongPressed = false; if (!homeWasLongPressed) { if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI) { try { IStatusBarService statusbar = getStatusBarService(); if (statusbar != null) { statusbar.cancelPreloadRecentApps(); } } catch (RemoteException e) { Slog.e(TAG, "RemoteException when showing recent apps", e); // re-acquire status bar service next time it is needed. mStatusBarService = null; } } mHomePressed = false; if (!canceled) { // If an incoming call is ringing, HOME is totally disabled. // (The user is already on the InCallScreen at this point, // and his ONLY options are to answer or reject the call.) boolean incomingRinging = false; try { ITelephony telephonyService = getTelephonyService(); if (telephonyService != null) { incomingRinging = telephonyService.isRinging(); } } catch (RemoteException ex) { Log.w(TAG, "RemoteException from getPhoneInterface()", ex); } if (incomingRinging) { Log.i(TAG, "Ignoring HOME; there's a ringing incoming call."); } else { launchHomeFromHotKey(); } } else { Log.i(TAG, "Ignoring HOME; event canceled."); } return -1; } } // If a system window has focus, then it doesn't make sense // right now to interact with applications. WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null; if (attrs != null) { final int type = attrs.type; if (type == WindowManager.LayoutParams.TYPE_KEYGUARD || type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG) { // the "app" is keyguard, so give it the key return 0; } final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length; for (int i=0; i<typeCount; i++) { if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) { // don't do anything, but also don't pass it to the app return -1; } } } if (down) { if (!mHomePressed && mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI) { try { IStatusBarService statusbar = getStatusBarService(); if (statusbar != null) { statusbar.preloadRecentApps(); } } catch (RemoteException e) { Slog.e(TAG, "RemoteException when preloading recent apps", e); // re-acquire status bar service next time it is needed. mStatusBarService = null; } } if (repeatCount == 0) { mHomePressed = true; } else if ((event.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0) { if (!keyguardOn) { handleLongPressOnHome(); } } } return -1; } else if (keyCode == KeyEvent.KEYCODE_MENU) { // Hijack modified menu keys for debugging features final int chordBug = KeyEvent.META_SHIFT_ON; if (down && repeatCount == 0) { if (mEnableShiftMenuBugReports && (metaState & chordBug) == chordBug) { Intent intent = new Intent(Intent.ACTION_BUG_REPORT); mContext.sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT, null, null, null, 0, null, null); return -1; } else if (SHOW_PROCESSES_ON_ALT_MENU && (metaState & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON) { Intent service = new Intent(); service.setClassName(mContext, "com.android.server.LoadAverageService"); ContentResolver res = mContext.getContentResolver(); boolean shown = Settings.Global.getInt( res, Settings.Global.SHOW_PROCESSES, 0) != 0; if (!shown) { mContext.startService(service); } else { mContext.stopService(service); } Settings.Global.putInt( res, Settings.Global.SHOW_PROCESSES, shown ? 0 : 1); return -1; } } } else if (keyCode == KeyEvent.KEYCODE_SEARCH) { if (down) { if (repeatCount == 0) { mSearchKeyShortcutPending = true; mConsumeSearchKeyUp = false; } } else { mSearchKeyShortcutPending = false; if (mConsumeSearchKeyUp) { mConsumeSearchKeyUp = false; return -1; } } return 0; } else if (keyCode == KeyEvent.KEYCODE_APP_SWITCH) { if (down && repeatCount == 0 && !keyguardOn) { showOrHideRecentAppsDialog(RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS); } return -1; } else if (keyCode == KeyEvent.KEYCODE_ASSIST) { if (down) { if (repeatCount == 0) { mAssistKeyLongPressed = false; } else if (repeatCount == 1) { mAssistKeyLongPressed = true; if (!keyguardOn) { launchAssistLongPressAction(); } } } else { if (mAssistKeyLongPressed) { mAssistKeyLongPressed = false; } else { if (!keyguardOn) { launchAssistAction(); } } } return -1; } // Shortcuts are invoked through Search+key, so intercept those here // Any printing key that is chorded with Search should be consumed // even if no shortcut was invoked. This prevents text from being // inadvertently inserted when using a keyboard that has built-in macro // shortcut keys (that emit Search+x) and some of them are not registered. if (mSearchKeyShortcutPending) { final KeyCharacterMap kcm = event.getKeyCharacterMap(); if (kcm.isPrintingKey(keyCode)) { mConsumeSearchKeyUp = true; mSearchKeyShortcutPending = false; if (down && repeatCount == 0 && !keyguardOn) { Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState); if (shortcutIntent != null) { shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { mContext.startActivity(shortcutIntent); } catch (ActivityNotFoundException ex) { Slog.w(TAG, "Dropping shortcut key combination because " + "the activity to which it is registered was not found: " + "SEARCH+" + KeyEvent.keyCodeToString(keyCode), ex); } } else { Slog.i(TAG, "Dropping unregistered shortcut key combination: " + "SEARCH+" + KeyEvent.keyCodeToString(keyCode)); } } return -1; } } // Invoke shortcuts using Meta. if (down && repeatCount == 0 && !keyguardOn && (metaState & KeyEvent.META_META_ON) != 0) { final KeyCharacterMap kcm = event.getKeyCharacterMap(); if (kcm.isPrintingKey(keyCode)) { Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState & ~(KeyEvent.META_META_ON | KeyEvent.META_META_LEFT_ON | KeyEvent.META_META_RIGHT_ON)); if (shortcutIntent != null) { shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { mContext.startActivity(shortcutIntent); } catch (ActivityNotFoundException ex) { Slog.w(TAG, "Dropping shortcut key combination because " + "the activity to which it is registered was not found: " + "META+" + KeyEvent.keyCodeToString(keyCode), ex); } return -1; } } } // Handle application launch keys. if (down && repeatCount == 0 && !keyguardOn) { String category = sApplicationLaunchKeyCategories.get(keyCode); if (category != null) { Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, category); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { mContext.startActivity(intent); } catch (ActivityNotFoundException ex) { Slog.w(TAG, "Dropping application launch key because " + "the activity to which it is registered was not found: " + "keyCode=" + keyCode + ", category=" + category, ex); } return -1; } } // Display task switcher for ALT-TAB or Meta-TAB. if (down && repeatCount == 0 && keyCode == KeyEvent.KEYCODE_TAB) { if (mRecentAppsDialogHeldModifiers == 0 && !keyguardOn) { final int shiftlessModifiers = event.getModifiers() & ~KeyEvent.META_SHIFT_MASK; if (KeyEvent.metaStateHasModifiers(shiftlessModifiers, KeyEvent.META_ALT_ON) || KeyEvent.metaStateHasModifiers( shiftlessModifiers, KeyEvent.META_META_ON)) { mRecentAppsDialogHeldModifiers = shiftlessModifiers; showOrHideRecentAppsDialog(RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW); return -1; } } } else if (!down && mRecentAppsDialogHeldModifiers != 0 && (metaState & mRecentAppsDialogHeldModifiers) == 0) { mRecentAppsDialogHeldModifiers = 0; showOrHideRecentAppsDialog(keyguardOn ? RECENT_APPS_BEHAVIOR_DISMISS : RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH); } // Handle keyboard language switching. if (down && repeatCount == 0 && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH || (keyCode == KeyEvent.KEYCODE_SPACE && (metaState & KeyEvent.META_CTRL_MASK) != 0))) { int direction = (metaState & KeyEvent.META_SHIFT_MASK) != 0 ? -1 : 1; mWindowManagerFuncs.switchKeyboardLayout(event.getDeviceId(), direction); return -1; } if (mLanguageSwitchKeyPressed && !down && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH || keyCode == KeyEvent.KEYCODE_SPACE)) { mLanguageSwitchKeyPressed = false; return -1; } // Let the application handle the key. return 0; } /** {@inheritDoc} */ @Override public KeyEvent dispatchUnhandledKey(WindowState win, KeyEvent event, int policyFlags) { // Note: This method is only called if the initial down was unhandled. if (DEBUG_INPUT) { Slog.d(TAG, "Unhandled key: win=" + win + ", action=" + event.getAction() + ", flags=" + event.getFlags() + ", keyCode=" + event.getKeyCode() + ", scanCode=" + event.getScanCode() + ", metaState=" + event.getMetaState() + ", repeatCount=" + event.getRepeatCount() + ", policyFlags=" + policyFlags); } KeyEvent fallbackEvent = null; if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) { final KeyCharacterMap kcm = event.getKeyCharacterMap(); final int keyCode = event.getKeyCode(); final int metaState = event.getMetaState(); final boolean initialDown = event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0; // Check for fallback actions specified by the key character map. final FallbackAction fallbackAction; if (initialDown) { fallbackAction = kcm.getFallbackAction(keyCode, metaState); } else { fallbackAction = mFallbackActions.get(keyCode); } if (fallbackAction != null) { if (DEBUG_INPUT) { Slog.d(TAG, "Fallback: keyCode=" + fallbackAction.keyCode + " metaState=" + Integer.toHexString(fallbackAction.metaState)); } final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK; fallbackEvent = KeyEvent.obtain( event.getDownTime(), event.getEventTime(), event.getAction(), fallbackAction.keyCode, event.getRepeatCount(), fallbackAction.metaState, event.getDeviceId(), event.getScanCode(), flags, event.getSource(), null); if (!interceptFallback(win, fallbackEvent, policyFlags)) { fallbackEvent.recycle(); fallbackEvent = null; } if (initialDown) { mFallbackActions.put(keyCode, fallbackAction); } else if (event.getAction() == KeyEvent.ACTION_UP) { mFallbackActions.remove(keyCode); fallbackAction.recycle(); } } } if (DEBUG_INPUT) { if (fallbackEvent == null) { Slog.d(TAG, "No fallback."); } else { Slog.d(TAG, "Performing fallback: " + fallbackEvent); } } return fallbackEvent; } private boolean interceptFallback(WindowState win, KeyEvent fallbackEvent, int policyFlags) { int actions = interceptKeyBeforeQueueing(fallbackEvent, policyFlags, true); if ((actions & ACTION_PASS_TO_USER) != 0) { long delayMillis = interceptKeyBeforeDispatching( win, fallbackEvent, policyFlags); if (delayMillis == 0) { return true; } } return false; } private void launchAssistLongPressAction() { performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false); sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST); // launch the search activity Intent intent = new Intent(Intent.ACTION_SEARCH_LONG_PRESS); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { // TODO: This only stops the factory-installed search manager. // Need to formalize an API to handle others SearchManager searchManager = getSearchManager(); if (searchManager != null) { searchManager.stopSearch(); } mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT)); } catch (ActivityNotFoundException e) { Slog.w(TAG, "No activity to handle assist long press action.", e); } } private void launchAssistAction() { sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST); Intent intent = ((SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE)) .getAssistIntent(mContext, UserHandle.USER_CURRENT); if (intent != null) { intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); try { mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT)); } catch (ActivityNotFoundException e) { Slog.w(TAG, "No activity to handle assist action.", e); } } } private SearchManager getSearchManager() { if (mSearchManager == null) { mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE); } return mSearchManager; } /** * A home key -> launch home action was detected. Take the appropriate action * given the situation with the keyguard. */ void launchHomeFromHotKey() { if (mKeyguardMediator != null && mKeyguardMediator.isShowingAndNotHidden()) { // don't launch home if keyguard showing } else if (!mHideLockScreen && mKeyguardMediator.isInputRestricted()) { // when in keyguard restricted mode, must first verify unlock // before launching home mKeyguardMediator.verifyUnlock(new OnKeyguardExitResult() { public void onKeyguardExitResult(boolean success) { if (success) { try { ActivityManagerNative.getDefault().stopAppSwitches(); } catch (RemoteException e) { } sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY); startDockOrHome(); } } }); } else { // no keyguard stuff to worry about, just launch home! try { ActivityManagerNative.getDefault().stopAppSwitches(); } catch (RemoteException e) { } sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY); startDockOrHome(); } } /** * A delayed callback use to determine when it is okay to re-allow applications * to use certain system UI flags. This is used to prevent applications from * spamming system UI changes that prevent the navigation bar from being shown. */ final Runnable mAllowSystemUiDelay = new Runnable() { @Override public void run() { } }; /** * Input handler used while nav bar is hidden. Captures any touch on the screen, * to determine when the nav bar should be shown and prevent applications from * receiving those touches. */ final class HideNavInputEventReceiver extends InputEventReceiver { public HideNavInputEventReceiver(InputChannel inputChannel, Looper looper) { super(inputChannel, looper); } @Override public void onInputEvent(InputEvent event) { boolean handled = false; try { if (event instanceof MotionEvent && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { final MotionEvent motionEvent = (MotionEvent)event; if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { // When the user taps down, we re-show the nav bar. boolean changed = false; synchronized (mLock) { // Any user activity always causes us to show the // navigation controls, if they had been hidden. // We also clear the low profile and only content // flags so that tapping on the screen will atomically // restore all currently hidden screen decorations. int newVal = mResettingSystemUiFlags | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN; if (mResettingSystemUiFlags != newVal) { mResettingSystemUiFlags = newVal; changed = true; } // We don't allow the system's nav bar to be hidden // again for 1 second, to prevent applications from // spamming us and keeping it from being shown. newVal = mForceClearedSystemUiFlags | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; if (mForceClearedSystemUiFlags != newVal) { mForceClearedSystemUiFlags = newVal; changed = true; mHandler.postDelayed(new Runnable() { @Override public void run() { synchronized (mLock) { // Clear flags. mForceClearedSystemUiFlags &= ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; } mWindowManagerFuncs.reevaluateStatusBarVisibility(); } }, 1000); } } if (changed) { mWindowManagerFuncs.reevaluateStatusBarVisibility(); } } } } finally { finishInputEvent(event, handled); } } } final InputEventReceiver.Factory mHideNavInputEventReceiverFactory = new InputEventReceiver.Factory() { @Override public InputEventReceiver createInputEventReceiver( InputChannel inputChannel, Looper looper) { return new HideNavInputEventReceiver(inputChannel, looper); } }; @Override public int adjustSystemUiVisibilityLw(int visibility) { // Reset any bits in mForceClearingStatusBarVisibility that // are now clear. mResettingSystemUiFlags &= visibility; // Clear any bits in the new visibility that are currently being // force cleared, before reporting it. return visibility & ~mResettingSystemUiFlags & ~mForceClearedSystemUiFlags; } @Override public void getContentInsetHintLw(WindowManager.LayoutParams attrs, Rect contentInset) { final int fl = attrs.flags; final int systemUiVisibility = (attrs.systemUiVisibility|attrs.subtreeSystemUiVisibility); if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) { int availRight, availBottom; if (mCanHideNavigationBar && (systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0) { availRight = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth; availBottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight; } else { availRight = mRestrictedScreenLeft + mRestrictedScreenWidth; availBottom = mRestrictedScreenTop + mRestrictedScreenHeight; } if ((systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) { if ((fl & FLAG_FULLSCREEN) != 0) { contentInset.set(mStableFullscreenLeft, mStableFullscreenTop, availRight - mStableFullscreenRight, availBottom - mStableFullscreenBottom); } else { contentInset.set(mStableLeft, mStableTop, availRight - mStableRight, availBottom - mStableBottom); } } else if ((fl & FLAG_FULLSCREEN) != 0) { contentInset.setEmpty(); } else if ((systemUiVisibility & (View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)) == 0) { contentInset.set(mCurLeft, mCurTop, availRight - mCurRight, availBottom - mCurBottom); } else { contentInset.set(mCurLeft, mCurTop, availRight - mCurRight, availBottom - mCurBottom); } return; } contentInset.setEmpty(); } /** {@inheritDoc} */ @Override public void beginLayoutLw(boolean isDefaultDisplay, int displayWidth, int displayHeight, int displayRotation) { mUnrestrictedScreenLeft = mUnrestrictedScreenTop = 0; mUnrestrictedScreenWidth = displayWidth; mUnrestrictedScreenHeight = displayHeight; mRestrictedScreenLeft = mRestrictedScreenTop = 0; mRestrictedScreenWidth = displayWidth; mRestrictedScreenHeight = displayHeight; mDockLeft = mContentLeft = mStableLeft = mStableFullscreenLeft = mSystemLeft = mCurLeft = 0; mDockTop = mContentTop = mStableTop = mStableFullscreenTop = mSystemTop = mCurTop = 0; mDockRight = mContentRight = mStableRight = mStableFullscreenRight = mSystemRight = mCurRight = displayWidth; mDockBottom = mContentBottom = mStableBottom = mStableFullscreenBottom = mSystemBottom = mCurBottom = displayHeight; mDockLayer = 0x10000000; mStatusBarLayer = -1; // start with the current dock rect, which will be (0,0,displayWidth,displayHeight) final Rect pf = mTmpParentFrame; final Rect df = mTmpDisplayFrame; final Rect vf = mTmpVisibleFrame; pf.left = df.left = vf.left = mDockLeft; pf.top = df.top = vf.top = mDockTop; pf.right = df.right = vf.right = mDockRight; pf.bottom = df.bottom = vf.bottom = mDockBottom; if (isDefaultDisplay) { // For purposes of putting out fake window up to steal focus, we will // drive nav being hidden only by whether it is requested. boolean navVisible = (mLastSystemUiFlags&View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0; // When the navigation bar isn't visible, we put up a fake // input window to catch all touch events. This way we can // detect when the user presses anywhere to bring back the nav // bar and ensure the application doesn't see the event. if (navVisible) { if (mHideNavFakeWindow != null) { mHideNavFakeWindow.dismiss(); mHideNavFakeWindow = null; } } else if (mHideNavFakeWindow == null) { mHideNavFakeWindow = mWindowManagerFuncs.addFakeWindow( mHandler.getLooper(), mHideNavInputEventReceiverFactory, "hidden nav", WindowManager.LayoutParams.TYPE_HIDDEN_NAV_CONSUMER, 0, false, false, true); } // For purposes of positioning and showing the nav bar, if we have // decided that it can't be hidden (because of the screen aspect ratio), // then take that into account. navVisible |= !mCanHideNavigationBar; if (mNavigationBar != null) { // Force the navigation bar to its appropriate place and // size. We need to do this directly, instead of relying on // it to bubble up from the nav bar, because this needs to // change atomically with screen rotations. mNavigationBarOnBottom = (!mNavigationBarCanMove || displayWidth < displayHeight); if (mNavigationBarOnBottom) { // It's a system nav bar or a portrait screen; nav bar goes on bottom. int top = displayHeight - mNavigationBarHeightForRotation[displayRotation]; mTmpNavigationFrame.set(0, top, displayWidth, displayHeight); mStableBottom = mStableFullscreenBottom = mTmpNavigationFrame.top; if (navVisible) { mNavigationBar.showLw(true); mDockBottom = mTmpNavigationFrame.top; mRestrictedScreenHeight = mDockBottom - mDockTop; } else { // We currently want to hide the navigation UI. mNavigationBar.hideLw(true); } if (navVisible && !mNavigationBar.isAnimatingLw()) { // If the nav bar is currently requested to be visible, // and not in the process of animating on or off, then // we can tell the app that it is covered by it. mSystemBottom = mTmpNavigationFrame.top; } } else { // Landscape screen; nav bar goes to the right. int left = displayWidth - mNavigationBarWidthForRotation[displayRotation]; mTmpNavigationFrame.set(left, 0, displayWidth, displayHeight); mStableRight = mStableFullscreenRight = mTmpNavigationFrame.left; if (navVisible) { mNavigationBar.showLw(true); mDockRight = mTmpNavigationFrame.left; mRestrictedScreenWidth = mDockRight - mDockLeft; } else { // We currently want to hide the navigation UI. mNavigationBar.hideLw(true); } if (navVisible && !mNavigationBar.isAnimatingLw()) { // If the nav bar is currently requested to be visible, // and not in the process of animating on or off, then // we can tell the app that it is covered by it. mSystemRight = mTmpNavigationFrame.left; } } // Make sure the content and current rectangles are updated to // account for the restrictions from the navigation bar. mContentTop = mCurTop = mDockTop; mContentBottom = mCurBottom = mDockBottom; mContentLeft = mCurLeft = mDockLeft; mContentRight = mCurRight = mDockRight; mStatusBarLayer = mNavigationBar.getSurfaceLayer(); // And compute the final frame. mNavigationBar.computeFrameLw(mTmpNavigationFrame, mTmpNavigationFrame, mTmpNavigationFrame, mTmpNavigationFrame); if (DEBUG_LAYOUT) Log.i(TAG, "mNavigationBar frame: " + mTmpNavigationFrame); } if (DEBUG_LAYOUT) Log.i(TAG, String.format("mDock rect: (%d,%d - %d,%d)", mDockLeft, mDockTop, mDockRight, mDockBottom)); // decide where the status bar goes ahead of time if (mStatusBar != null) { // apply any navigation bar insets pf.left = df.left = mUnrestrictedScreenLeft; pf.top = df.top = mUnrestrictedScreenTop; pf.right = df.right = mUnrestrictedScreenWidth - mUnrestrictedScreenLeft; pf.bottom = df.bottom = mUnrestrictedScreenHeight - mUnrestrictedScreenTop; vf.left = mStableLeft; vf.top = mStableTop; vf.right = mStableRight; vf.bottom = mStableBottom; mStatusBarLayer = mStatusBar.getSurfaceLayer(); // Let the status bar determine its size. mStatusBar.computeFrameLw(pf, df, vf, vf); // For layout, the status bar is always at the top with our fixed height. mStableTop = mUnrestrictedScreenTop + mStatusBarHeight; // If the status bar is hidden, we don't want to cause // windows behind it to scroll. if (mStatusBar.isVisibleLw()) { // Status bar may go away, so the screen area it occupies // is available to apps but just covering them when the // status bar is visible. mDockTop = mUnrestrictedScreenTop + mStatusBarHeight; mContentTop = mCurTop = mDockTop; mContentBottom = mCurBottom = mDockBottom; mContentLeft = mCurLeft = mDockLeft; mContentRight = mCurRight = mDockRight; if (DEBUG_LAYOUT) Log.v(TAG, "Status bar: " + String.format( "dock=[%d,%d][%d,%d] content=[%d,%d][%d,%d] cur=[%d,%d][%d,%d]", mDockLeft, mDockTop, mDockRight, mDockBottom, mContentLeft, mContentTop, mContentRight, mContentBottom, mCurLeft, mCurTop, mCurRight, mCurBottom)); } if (mStatusBar.isVisibleLw() && !mStatusBar.isAnimatingLw()) { // If the status bar is currently requested to be visible, // and not in the process of animating on or off, then // we can tell the app that it is covered by it. mSystemTop = mUnrestrictedScreenTop + mStatusBarHeight; } } } } /** {@inheritDoc} */ public int getSystemDecorRectLw(Rect systemRect) { systemRect.left = mSystemLeft; systemRect.top = mSystemTop; systemRect.right = mSystemRight; systemRect.bottom = mSystemBottom; if (mStatusBar != null) return mStatusBar.getSurfaceLayer(); if (mNavigationBar != null) return mNavigationBar.getSurfaceLayer(); return 0; } void setAttachedWindowFrames(WindowState win, int fl, int adjust, WindowState attached, boolean insetDecors, Rect pf, Rect df, Rect cf, Rect vf) { if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) { // Here's a special case: if this attached window is a panel that is // above the dock window, and the window it is attached to is below // the dock window, then the frames we computed for the window it is // attached to can not be used because the dock is effectively part // of the underlying window and the attached window is floating on top // of the whole thing. So, we ignore the attached window and explicitly // compute the frames that would be appropriate without the dock. df.left = cf.left = vf.left = mDockLeft; df.top = cf.top = vf.top = mDockTop; df.right = cf.right = vf.right = mDockRight; df.bottom = cf.bottom = vf.bottom = mDockBottom; } else { // The effective display frame of the attached window depends on // whether it is taking care of insetting its content. If not, // we need to use the parent's content frame so that the entire // window is positioned within that content. Otherwise we can use // the display frame and let the attached window take care of // positioning its content appropriately. if (adjust != SOFT_INPUT_ADJUST_RESIZE) { cf.set(attached.getDisplayFrameLw()); } else { // If the window is resizing, then we want to base the content // frame on our attached content frame to resize... however, // things can be tricky if the attached window is NOT in resize // mode, in which case its content frame will be larger. // Ungh. So to deal with that, make sure the content frame // we end up using is not covering the IM dock. cf.set(attached.getContentFrameLw()); if (attached.getSurfaceLayer() < mDockLayer) { if (cf.left < mContentLeft) cf.left = mContentLeft; if (cf.top < mContentTop) cf.top = mContentTop; if (cf.right > mContentRight) cf.right = mContentRight; if (cf.bottom > mContentBottom) cf.bottom = mContentBottom; } } df.set(insetDecors ? attached.getDisplayFrameLw() : cf); vf.set(attached.getVisibleFrameLw()); } // The LAYOUT_IN_SCREEN flag is used to determine whether the attached // window should be positioned relative to its parent or the entire // screen. pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0 ? attached.getFrameLw() : df); } private void applyStableConstraints(int sysui, int fl, Rect r) { if ((sysui & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) { // If app is requesting a stable layout, don't let the // content insets go below the stable values. if ((fl & FLAG_FULLSCREEN) != 0) { if (r.left < mStableFullscreenLeft) r.left = mStableFullscreenLeft; if (r.top < mStableFullscreenTop) r.top = mStableFullscreenTop; if (r.right > mStableFullscreenRight) r.right = mStableFullscreenRight; if (r.bottom > mStableFullscreenBottom) r.bottom = mStableFullscreenBottom; } else { if (r.left < mStableLeft) r.left = mStableLeft; if (r.top < mStableTop) r.top = mStableTop; if (r.right > mStableRight) r.right = mStableRight; if (r.bottom > mStableBottom) r.bottom = mStableBottom; } } } /** {@inheritDoc} */ @Override public void layoutWindowLw(WindowState win, WindowManager.LayoutParams attrs, WindowState attached) { // we've already done the status bar if (win == mStatusBar || win == mNavigationBar) { return; } final boolean isDefaultDisplay = win.isDefaultDisplay(); final boolean needsToOffsetInputMethodTarget = isDefaultDisplay && (win == mLastInputMethodTargetWindow && mLastInputMethodWindow != null); if (needsToOffsetInputMethodTarget) { if (DEBUG_LAYOUT) { Slog.i(TAG, "Offset ime target window by the last ime window state"); } offsetInputMethodWindowLw(mLastInputMethodWindow); } final int fl = attrs.flags; final int sim = attrs.softInputMode; final int sysUiFl = win.getSystemUiVisibility(); final Rect pf = mTmpParentFrame; final Rect df = mTmpDisplayFrame; final Rect cf = mTmpContentFrame; final Rect vf = mTmpVisibleFrame; final boolean hasNavBar = (isDefaultDisplay && mHasNavigationBar && mNavigationBar != null && mNavigationBar.isVisibleLw()); final int adjust = sim & SOFT_INPUT_MASK_ADJUST; if (!isDefaultDisplay) { if (attached != null) { // If this window is attached to another, our display // frame is the same as the one we are attached to. setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, cf, vf); } else { // Give the window full screen. pf.left = df.left = cf.left = mUnrestrictedScreenLeft; pf.top = df.top = cf.top = mUnrestrictedScreenTop; pf.right = df.right = cf.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth; pf.bottom = df.bottom = cf.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight; } } else if (attrs.type == TYPE_INPUT_METHOD) { pf.left = df.left = cf.left = vf.left = mDockLeft; pf.top = df.top = cf.top = vf.top = mDockTop; pf.right = df.right = cf.right = vf.right = mDockRight; pf.bottom = df.bottom = cf.bottom = vf.bottom = mDockBottom; // IM dock windows always go to the bottom of the screen. attrs.gravity = Gravity.BOTTOM; mDockLayer = win.getSurfaceLayer(); } else { if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_FULLSCREEN | FLAG_LAYOUT_INSET_DECOR)) == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR) && (sysUiFl & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) { if (DEBUG_LAYOUT) Log.v(TAG, "layoutWindowLw(" + attrs.getTitle() + "): IN_SCREEN, INSET_DECOR, !FULLSCREEN"); // This is the case for a normal activity window: we want it // to cover all of the screen space, and it can take care of // moving its contents to account for screen decorations that // intrude into that space. if (attached != null) { // If this window is attached to another, our display // frame is the same as the one we are attached to. setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, cf, vf); } else { if (attrs.type == TYPE_STATUS_BAR_PANEL || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) { // Status bar panels are the only windows who can go on top of // the status bar. They are protected by the STATUS_BAR_SERVICE // permission, so they have the same privileges as the status // bar itself. // // However, they should still dodge the navigation bar if it exists. pf.left = df.left = hasNavBar ? mDockLeft : mUnrestrictedScreenLeft; pf.top = df.top = mUnrestrictedScreenTop; pf.right = df.right = hasNavBar ? mRestrictedScreenLeft+mRestrictedScreenWidth : mUnrestrictedScreenLeft+mUnrestrictedScreenWidth; pf.bottom = df.bottom = hasNavBar ? mRestrictedScreenTop+mRestrictedScreenHeight : mUnrestrictedScreenTop+mUnrestrictedScreenHeight; if (DEBUG_LAYOUT) { Log.v(TAG, String.format( "Laying out status bar window: (%d,%d - %d,%d)", pf.left, pf.top, pf.right, pf.bottom)); } } else if (mCanHideNavigationBar && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0 && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) { // Asking for layout as if the nav bar is hidden, lets the // application extend into the unrestricted screen area. We // only do this for application windows to ensure no window that // can be above the nav bar can do this. pf.left = df.left = mUnrestrictedScreenLeft; pf.top = df.top = mUnrestrictedScreenTop; pf.right = df.right = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth; pf.bottom = df.bottom = mUnrestrictedScreenTop+mUnrestrictedScreenHeight; } else { pf.left = df.left = mRestrictedScreenLeft; pf.top = df.top = mRestrictedScreenTop; pf.right = df.right = mRestrictedScreenLeft+mRestrictedScreenWidth; pf.bottom = df.bottom = mRestrictedScreenTop+mRestrictedScreenHeight; } if (adjust != SOFT_INPUT_ADJUST_RESIZE) { cf.left = mDockLeft; cf.top = mDockTop; cf.right = mDockRight; cf.bottom = mDockBottom; } else { cf.left = mContentLeft; cf.top = mContentTop; cf.right = mContentRight; cf.bottom = mContentBottom; } applyStableConstraints(sysUiFl, fl, cf); if (adjust != SOFT_INPUT_ADJUST_NOTHING) { vf.left = mCurLeft; vf.top = mCurTop; vf.right = mCurRight; vf.bottom = mCurBottom; } else { vf.set(cf); } } } else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0 || (sysUiFl & (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)) != 0) { if (DEBUG_LAYOUT) Log.v(TAG, "layoutWindowLw(" + attrs.getTitle() + "): IN_SCREEN"); // A window that has requested to fill the entire screen just // gets everything, period. if (attrs.type == TYPE_STATUS_BAR_PANEL || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) { pf.left = df.left = cf.left = hasNavBar ? mDockLeft : mUnrestrictedScreenLeft; pf.top = df.top = cf.top = mUnrestrictedScreenTop; pf.right = df.right = cf.right = hasNavBar ? mRestrictedScreenLeft+mRestrictedScreenWidth : mUnrestrictedScreenLeft+mUnrestrictedScreenWidth; pf.bottom = df.bottom = cf.bottom = hasNavBar ? mRestrictedScreenTop+mRestrictedScreenHeight : mUnrestrictedScreenTop+mUnrestrictedScreenHeight; if (DEBUG_LAYOUT) { Log.v(TAG, String.format( "Laying out IN_SCREEN status bar window: (%d,%d - %d,%d)", pf.left, pf.top, pf.right, pf.bottom)); } } else if (attrs.type == TYPE_NAVIGATION_BAR || attrs.type == TYPE_NAVIGATION_BAR_PANEL) { // The navigation bar has Real Ultimate Power. pf.left = df.left = mUnrestrictedScreenLeft; pf.top = df.top = mUnrestrictedScreenTop; pf.right = df.right = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth; pf.bottom = df.bottom = mUnrestrictedScreenTop+mUnrestrictedScreenHeight; if (DEBUG_LAYOUT) { Log.v(TAG, String.format( "Laying out navigation bar window: (%d,%d - %d,%d)", pf.left, pf.top, pf.right, pf.bottom)); } } else if ((attrs.type == TYPE_SECURE_SYSTEM_OVERLAY || attrs.type == TYPE_BOOT_PROGRESS) && ((fl & FLAG_FULLSCREEN) != 0)) { // Fullscreen secure system overlays get what they ask for. pf.left = df.left = mUnrestrictedScreenLeft; pf.top = df.top = mUnrestrictedScreenTop; pf.right = df.right = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth; pf.bottom = df.bottom = mUnrestrictedScreenTop+mUnrestrictedScreenHeight; } else if (attrs.type == TYPE_BOOT_PROGRESS || attrs.type == TYPE_UNIVERSE_BACKGROUND) { // Boot progress screen always covers entire display. pf.left = df.left = cf.left = mUnrestrictedScreenLeft; pf.top = df.top = cf.top = mUnrestrictedScreenTop; pf.right = df.right = cf.right = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth; pf.bottom = df.bottom = cf.bottom = mUnrestrictedScreenTop+mUnrestrictedScreenHeight; } else if (mCanHideNavigationBar && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0 && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) { // Asking for layout as if the nav bar is hidden, lets the // application extend into the unrestricted screen area. We // only do this for application windows to ensure no window that // can be above the nav bar can do this. // XXX This assumes that an app asking for this will also // ask for layout in only content. We can't currently figure out // what the screen would be if only laying out to hide the nav bar. pf.left = df.left = cf.left = mUnrestrictedScreenLeft; pf.top = df.top = cf.top = mUnrestrictedScreenTop; pf.right = df.right = cf.right = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth; pf.bottom = df.bottom = cf.bottom = mUnrestrictedScreenTop+mUnrestrictedScreenHeight; } else { pf.left = df.left = cf.left = mRestrictedScreenLeft; pf.top = df.top = cf.top = mRestrictedScreenTop; pf.right = df.right = cf.right = mRestrictedScreenLeft+mRestrictedScreenWidth; pf.bottom = df.bottom = cf.bottom = mRestrictedScreenTop+mRestrictedScreenHeight; } applyStableConstraints(sysUiFl, fl, cf); if (adjust != SOFT_INPUT_ADJUST_NOTHING) { vf.left = mCurLeft; vf.top = mCurTop; vf.right = mCurRight; vf.bottom = mCurBottom; } else { vf.set(cf); } } else if (attached != null) { if (DEBUG_LAYOUT) Log.v(TAG, "layoutWindowLw(" + attrs.getTitle() + "): attached to " + attached); // A child window should be placed inside of the same visible // frame that its parent had. setAttachedWindowFrames(win, fl, adjust, attached, false, pf, df, cf, vf); } else { if (DEBUG_LAYOUT) Log.v(TAG, "layoutWindowLw(" + attrs.getTitle() + "): normal window"); // Otherwise, a normal window must be placed inside the content // of all screen decorations. if (attrs.type == TYPE_STATUS_BAR_PANEL) { // Status bar panels are the only windows who can go on top of // the status bar. They are protected by the STATUS_BAR_SERVICE // permission, so they have the same privileges as the status // bar itself. pf.left = df.left = cf.left = mRestrictedScreenLeft; pf.top = df.top = cf.top = mRestrictedScreenTop; pf.right = df.right = cf.right = mRestrictedScreenLeft+mRestrictedScreenWidth; pf.bottom = df.bottom = cf.bottom = mRestrictedScreenTop+mRestrictedScreenHeight; } else { pf.left = mContentLeft; pf.top = mContentTop; pf.right = mContentRight; pf.bottom = mContentBottom; if (adjust != SOFT_INPUT_ADJUST_RESIZE) { df.left = cf.left = mDockLeft; df.top = cf.top = mDockTop; df.right = cf.right = mDockRight; df.bottom = cf.bottom = mDockBottom; } else { df.left = cf.left = mContentLeft; df.top = cf.top = mContentTop; df.right = cf.right = mContentRight; df.bottom = cf.bottom = mContentBottom; } if (adjust != SOFT_INPUT_ADJUST_NOTHING) { vf.left = mCurLeft; vf.top = mCurTop; vf.right = mCurRight; vf.bottom = mCurBottom; } else { vf.set(cf); } } } } if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0) { df.left = df.top = cf.left = cf.top = vf.left = vf.top = -10000; df.right = df.bottom = cf.right = cf.bottom = vf.right = vf.bottom = 10000; } if (DEBUG_LAYOUT) Log.v(TAG, "Compute frame " + attrs.getTitle() + ": sim=#" + Integer.toHexString(sim) + " attach=" + attached + " type=" + attrs.type + String.format(" flags=0x%08x", fl) + " pf=" + pf.toShortString() + " df=" + df.toShortString() + " cf=" + cf.toShortString() + " vf=" + vf.toShortString()); win.computeFrameLw(pf, df, cf, vf); // Dock windows carve out the bottom of the screen, so normal windows // can't appear underneath them. if (attrs.type == TYPE_INPUT_METHOD && win.isVisibleOrBehindKeyguardLw() && !win.getGivenInsetsPendingLw()) { setLastInputMethodWindowLw(null, null); offsetInputMethodWindowLw(win); } } private void offsetInputMethodWindowLw(WindowState win) { int top = win.getContentFrameLw().top; top += win.getGivenContentInsetsLw().top; if (mContentBottom > top) { mContentBottom = top; } top = win.getVisibleFrameLw().top; top += win.getGivenVisibleInsetsLw().top; if (mCurBottom > top) { mCurBottom = top; } if (DEBUG_LAYOUT) Log.v(TAG, "Input method: mDockBottom=" + mDockBottom + " mContentBottom=" + mContentBottom + " mCurBottom=" + mCurBottom); } /** {@inheritDoc} */ @Override public void finishLayoutLw() { return; } /** {@inheritDoc} */ @Override public void beginPostLayoutPolicyLw(int displayWidth, int displayHeight) { mTopFullscreenOpaqueWindowState = null; mForceStatusBar = false; mForceStatusBarFromKeyguard = false; mHideLockScreen = false; mAllowLockscreenWhenOn = false; mDismissKeyguard = DISMISS_KEYGUARD_NONE; mShowingLockscreen = false; mShowingDream = false; } /** {@inheritDoc} */ @Override public void applyPostLayoutPolicyLw(WindowState win, WindowManager.LayoutParams attrs) { if (DEBUG_LAYOUT) Slog.i(TAG, "Win " + win + ": isVisibleOrBehindKeyguardLw=" + win.isVisibleOrBehindKeyguardLw()); if (mTopFullscreenOpaqueWindowState == null && win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()) { if ((attrs.flags & FLAG_FORCE_NOT_FULLSCREEN) != 0) { if (attrs.type == TYPE_KEYGUARD) { mForceStatusBarFromKeyguard = true; } else { mForceStatusBar = true; } } if (attrs.type == TYPE_KEYGUARD) { mShowingLockscreen = true; } boolean applyWindow = attrs.type >= FIRST_APPLICATION_WINDOW && attrs.type <= LAST_APPLICATION_WINDOW; if (attrs.type == TYPE_DREAM) { // If the lockscreen was showing when the dream started then wait // for the dream to draw before hiding the lockscreen. if (!mDreamingLockscreen || (win.isVisibleLw() && win.hasDrawnLw())) { mShowingDream = true; applyWindow = true; } } if (applyWindow && attrs.x == 0 && attrs.y == 0 && attrs.width == WindowManager.LayoutParams.MATCH_PARENT && attrs.height == WindowManager.LayoutParams.MATCH_PARENT) { if (DEBUG_LAYOUT) Log.v(TAG, "Fullscreen window: " + win); mTopFullscreenOpaqueWindowState = win; if ((attrs.flags & FLAG_SHOW_WHEN_LOCKED) != 0) { if (DEBUG_LAYOUT) Log.v(TAG, "Setting mHideLockScreen to true by win " + win); mHideLockScreen = true; mForceStatusBarFromKeyguard = false; } if ((attrs.flags & FLAG_DISMISS_KEYGUARD) != 0 && mDismissKeyguard == DISMISS_KEYGUARD_NONE) { if (DEBUG_LAYOUT) Log.v(TAG, "Setting mDismissKeyguard to true by win " + win); mDismissKeyguard = mWinDismissingKeyguard == win ? DISMISS_KEYGUARD_CONTINUE : DISMISS_KEYGUARD_START; mWinDismissingKeyguard = win; mForceStatusBarFromKeyguard = false; } if ((attrs.flags & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) { mAllowLockscreenWhenOn = true; } } } } /** {@inheritDoc} */ @Override public int finishPostLayoutPolicyLw() { int changes = 0; boolean topIsFullscreen = false; final WindowManager.LayoutParams lp = (mTopFullscreenOpaqueWindowState != null) ? mTopFullscreenOpaqueWindowState.getAttrs() : null; // If we are not currently showing a dream then remember the current // lockscreen state. We will use this to determine whether the dream // started while the lockscreen was showing and remember this state // while the dream is showing. if (!mShowingDream) { mDreamingLockscreen = mShowingLockscreen; } if (mStatusBar != null) { if (DEBUG_LAYOUT) Log.i(TAG, "force=" + mForceStatusBar + " forcefkg=" + mForceStatusBarFromKeyguard + " top=" + mTopFullscreenOpaqueWindowState); if (mForceStatusBar || mForceStatusBarFromKeyguard) { if (DEBUG_LAYOUT) Log.v(TAG, "Showing status bar: forced"); if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT; } else if (mTopFullscreenOpaqueWindowState != null) { if (localLOGV) { Log.d(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw() + " shown frame: " + mTopFullscreenOpaqueWindowState.getShownFrameLw()); Log.d(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs() + " lp.flags=0x" + Integer.toHexString(lp.flags)); } topIsFullscreen = (lp.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0 || (mLastSystemUiFlags & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0; // The subtle difference between the window for mTopFullscreenOpaqueWindowState // and mTopIsFullscreen is that that mTopIsFullscreen is set only if the window // has the FLAG_FULLSCREEN set. Not sure if there is another way that to be the // case though. if (topIsFullscreen) { if (DEBUG_LAYOUT) Log.v(TAG, "** HIDING status bar"); if (mStatusBar.hideLw(true)) { changes |= FINISH_LAYOUT_REDO_LAYOUT; mHandler.post(new Runnable() { @Override public void run() { try { IStatusBarService statusbar = getStatusBarService(); if (statusbar != null) { statusbar.collapsePanels(); } } catch (RemoteException ex) { // re-acquire status bar service next time it is needed. mStatusBarService = null; } }}); } else if (DEBUG_LAYOUT) { Log.v(TAG, "Preventing status bar from hiding by policy"); } } else { if (DEBUG_LAYOUT) Log.v(TAG, "** SHOWING status bar: top is not fullscreen"); if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT; } } } mTopIsFullscreen = topIsFullscreen; // Hide the key guard if a visible window explicitly specifies that it wants to be // displayed when the screen is locked. if (mKeyguard != null) { if (localLOGV) Log.v(TAG, "finishPostLayoutPolicyLw: mHideKeyguard=" + mHideLockScreen); if (mDismissKeyguard != DISMISS_KEYGUARD_NONE && !mKeyguardMediator.isSecure()) { if (mKeyguard.hideLw(true)) { changes |= FINISH_LAYOUT_REDO_LAYOUT | FINISH_LAYOUT_REDO_CONFIG | FINISH_LAYOUT_REDO_WALLPAPER; } if (mKeyguardMediator.isShowing()) { mHandler.post(new Runnable() { @Override public void run() { mKeyguardMediator.keyguardDone(false, false); } }); } } else if (mHideLockScreen) { if (mKeyguard.hideLw(true)) { changes |= FINISH_LAYOUT_REDO_LAYOUT | FINISH_LAYOUT_REDO_CONFIG | FINISH_LAYOUT_REDO_WALLPAPER; } mKeyguardMediator.setHidden(true); } else if (mDismissKeyguard != DISMISS_KEYGUARD_NONE) { // This is the case of keyguard isSecure() and not mHideLockScreen. if (mDismissKeyguard == DISMISS_KEYGUARD_START) { // Only launch the next keyguard unlock window once per window. if (mKeyguard.showLw(true)) { changes |= FINISH_LAYOUT_REDO_LAYOUT | FINISH_LAYOUT_REDO_CONFIG | FINISH_LAYOUT_REDO_WALLPAPER; } mKeyguardMediator.setHidden(false); mHandler.post(new Runnable() { @Override public void run() { mKeyguardMediator.dismiss(); } }); } } else { mWinDismissingKeyguard = null; if (mKeyguard.showLw(true)) { changes |= FINISH_LAYOUT_REDO_LAYOUT | FINISH_LAYOUT_REDO_CONFIG | FINISH_LAYOUT_REDO_WALLPAPER; } mKeyguardMediator.setHidden(false); } } if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) { // If the navigation bar has been hidden or shown, we need to do another // layout pass to update that window. changes |= FINISH_LAYOUT_REDO_LAYOUT; } // update since mAllowLockscreenWhenOn might have changed updateLockScreenTimeout(); return changes; } public boolean allowAppAnimationsLw() { if (mKeyguard != null && mKeyguard.isVisibleLw() && !mKeyguard.isAnimatingLw()) { // If keyguard is currently visible, no reason to animate // behind it. return false; } return true; } public int focusChangedLw(WindowState lastFocus, WindowState newFocus) { mFocusedWindow = newFocus; if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) { // If the navigation bar has been hidden or shown, we need to do another // layout pass to update that window. return FINISH_LAYOUT_REDO_LAYOUT; } return 0; } /** {@inheritDoc} */ public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) { // do nothing if headless if (mHeadless) return; // lid changed state final int newLidState = lidOpen ? LID_OPEN : LID_CLOSED; if (newLidState == mLidState) { return; } mLidState = newLidState; applyLidSwitchState(); updateRotation(true); if (lidOpen) { if (keyguardIsShowingTq()) { mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(KeyEvent.KEYCODE_POWER); } else { mPowerManager.wakeUp(SystemClock.uptimeMillis()); } } else if (!mLidControlsSleep) { mPowerManager.userActivity(SystemClock.uptimeMillis(), false); } } void setHdmiPlugged(boolean plugged) { if (mHdmiPlugged != plugged) { mHdmiPlugged = plugged; updateRotation(true, true); Intent intent = new Intent(ACTION_HDMI_PLUGGED); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); intent.putExtra(EXTRA_HDMI_PLUGGED_STATE, plugged); mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); } } void initializeHdmiState() { boolean plugged = false; // watch for HDMI plug messages if the hdmi switch exists if (new File("/sys/devices/virtual/switch/hdmi/state").exists()) { mHDMIObserver.startObserving("DEVPATH=/devices/virtual/switch/hdmi"); final String filename = "/sys/class/switch/hdmi/state"; FileReader reader = null; try { reader = new FileReader(filename); char[] buf = new char[15]; int n = reader.read(buf); if (n > 1) { plugged = 0 != Integer.parseInt(new String(buf, 0, n-1)); } } catch (IOException ex) { Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex); } catch (NumberFormatException ex) { Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { } } } } // This dance forces the code in setHdmiPlugged to run. // Always do this so the sticky intent is stuck (to false) if there is no hdmi. mHdmiPlugged = !plugged; setHdmiPlugged(!mHdmiPlugged); } /** * @return Whether music is being played right now. */ boolean isMusicActive() { final AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE); if (am == null) { Log.w(TAG, "isMusicActive: couldn't get AudioManager reference"); return false; } return am.isMusicActive(); } /** * Tell the audio service to adjust the volume appropriate to the event. * @param keycode */ void handleVolumeKey(int stream, int keycode) { IAudioService audioService = getAudioService(); if (audioService == null) { return; } try { // since audio is playing, we shouldn't have to hold a wake lock // during the call, but we do it as a precaution for the rare possibility // that the music stops right before we call this // TODO: Actually handle MUTE. mBroadcastWakeLock.acquire(); audioService.adjustStreamVolume(stream, keycode == KeyEvent.KEYCODE_VOLUME_UP ? AudioManager.ADJUST_RAISE : AudioManager.ADJUST_LOWER, 0); } catch (RemoteException e) { Log.w(TAG, "IAudioService.adjustStreamVolume() threw RemoteException " + e); } finally { mBroadcastWakeLock.release(); } } final Object mScreenshotLock = new Object(); ServiceConnection mScreenshotConnection = null; final Runnable mScreenshotTimeout = new Runnable() { @Override public void run() { synchronized (mScreenshotLock) { if (mScreenshotConnection != null) { mContext.unbindService(mScreenshotConnection); mScreenshotConnection = null; } } } }; // Assume this is called from the Handler thread. private void takeScreenshot() { synchronized (mScreenshotLock) { if (mScreenshotConnection != null) { return; } ComponentName cn = new ComponentName("com.android.systemui", "com.android.systemui.screenshot.TakeScreenshotService"); Intent intent = new Intent(); intent.setComponent(cn); ServiceConnection conn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { synchronized (mScreenshotLock) { if (mScreenshotConnection != this) { return; } Messenger messenger = new Messenger(service); Message msg = Message.obtain(null, 1); final ServiceConnection myConn = this; Handler h = new Handler(mHandler.getLooper()) { @Override public void handleMessage(Message msg) { synchronized (mScreenshotLock) { if (mScreenshotConnection == myConn) { mContext.unbindService(mScreenshotConnection); mScreenshotConnection = null; mHandler.removeCallbacks(mScreenshotTimeout); } } } }; msg.replyTo = new Messenger(h); msg.arg1 = msg.arg2 = 0; if (mStatusBar != null && mStatusBar.isVisibleLw()) msg.arg1 = 1; if (mNavigationBar != null && mNavigationBar.isVisibleLw()) msg.arg2 = 1; try { messenger.send(msg); } catch (RemoteException e) { } } } @Override public void onServiceDisconnected(ComponentName name) {} }; if (mContext.bindService( intent, conn, Context.BIND_AUTO_CREATE, UserHandle.USER_CURRENT)) { mScreenshotConnection = conn; mHandler.postDelayed(mScreenshotTimeout, 10000); } } } /** {@inheritDoc} */ @Override public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) { if (!mSystemBooted) { // If we have not yet booted, don't let key events do anything. return 0; } final boolean down = event.getAction() == KeyEvent.ACTION_DOWN; final boolean canceled = event.isCanceled(); int keyCode = event.getKeyCode(); final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0; // If screen is off then we treat the case where the keyguard is open but hidden // the same as if it were open and in front. // This will prevent any keys other than the power button from waking the screen // when the keyguard is hidden by another activity. final boolean keyguardActive = (mKeyguardMediator == null ? false : (isScreenOn ? mKeyguardMediator.isShowingAndNotHidden() : mKeyguardMediator.isShowing())); if (keyCode == KeyEvent.KEYCODE_POWER) { policyFlags |= WindowManagerPolicy.FLAG_WAKE; } final boolean isWakeKey = (policyFlags & (WindowManagerPolicy.FLAG_WAKE | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0; if (DEBUG_INPUT) { Log.d(TAG, "interceptKeyTq keycode=" + keyCode + " screenIsOn=" + isScreenOn + " keyguardActive=" + keyguardActive + " policyFlags=" + Integer.toHexString(policyFlags) + " isWakeKey=" + isWakeKey); } if (down && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0 && event.getRepeatCount() == 0) { performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false); } // Basic policy based on screen state and keyguard. // FIXME: This policy isn't quite correct. We shouldn't care whether the screen // is on or off, really. We should care about whether the device is in an // interactive state or is in suspend pretending to be "off". // The primary screen might be turned off due to proximity sensor or // because we are presenting media on an auxiliary screen or remotely controlling // the device some other way (which is why we have an exemption here for injected // events). int result; if ((isScreenOn && !mHeadless) || (isInjected && !isWakeKey)) { // When the screen is on or if the key is injected pass the key to the application. result = ACTION_PASS_TO_USER; } else { // When the screen is off and the key is not injected, determine whether // to wake the device but don't pass the key to the application. result = 0; if (down && isWakeKey && isWakeKeyWhenScreenOff(keyCode)) { if (keyguardActive) { // If the keyguard is showing, let it wake the device when ready. mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(keyCode); } else if ((keyCode != KeyEvent.KEYCODE_VOLUME_UP) && (keyCode != KeyEvent.KEYCODE_VOLUME_DOWN)) { // Otherwise, wake the device ourselves. result |= ACTION_WAKE_UP; } } } // Handle special keys. switch (keyCode) { case KeyEvent.KEYCODE_ENDCALL: { result &= ~ACTION_PASS_TO_USER; if (down) { ITelephony telephonyService = getTelephonyService(); boolean hungUp = false; if (telephonyService != null) { try { hungUp = telephonyService.endCall(); } catch (RemoteException ex) { Log.w(TAG, "ITelephony threw RemoteException", ex); } } interceptPowerKeyDown(!isScreenOn || hungUp); } else { if (interceptPowerKeyUp(canceled)) { if ((mEndcallBehavior & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) { if (goHome()) { break; } } if ((mEndcallBehavior & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) { result = (result & ~ACTION_WAKE_UP) | ACTION_GO_TO_SLEEP; } } } break; } case KeyEvent.KEYCODE_VOLUME_DOWN: case KeyEvent.KEYCODE_VOLUME_UP: case KeyEvent.KEYCODE_VOLUME_MUTE: { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { if (down) { if (isScreenOn && !mVolumeDownKeyTriggered && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) { mVolumeDownKeyTriggered = true; mVolumeDownKeyTime = event.getDownTime(); mVolumeDownKeyConsumedByScreenshotChord = false; cancelPendingPowerKeyAction(); interceptScreenshotChord(); } } else { mVolumeDownKeyTriggered = false; cancelPendingScreenshotChordAction(); } } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) { if (down) { if (isScreenOn && !mVolumeUpKeyTriggered && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) { mVolumeUpKeyTriggered = true; cancelPendingPowerKeyAction(); cancelPendingScreenshotChordAction(); } } else { mVolumeUpKeyTriggered = false; cancelPendingScreenshotChordAction(); } } if (down) { ITelephony telephonyService = getTelephonyService(); if (telephonyService != null) { try { if (telephonyService.isRinging()) { // If an incoming call is ringing, either VOLUME key means // "silence ringer". We handle these keys here, rather than // in the InCallScreen, to make sure we'll respond to them // even if the InCallScreen hasn't come to the foreground yet. // Look for the DOWN event here, to agree with the "fallback" // behavior in the InCallScreen. Log.i(TAG, "interceptKeyBeforeQueueing:" + " VOLUME key-down while ringing: Silence ringer!"); // Silence the ringer. (It's safe to call this // even if the ringer has already been silenced.) telephonyService.silenceRinger(); // And *don't* pass this key thru to the current activity // (which is probably the InCallScreen.) result &= ~ACTION_PASS_TO_USER; break; } if (telephonyService.isOffhook() && (result & ACTION_PASS_TO_USER) == 0) { // If we are in call but we decided not to pass the key to // the application, handle the volume change here. handleVolumeKey(AudioManager.STREAM_VOICE_CALL, keyCode); break; } } catch (RemoteException ex) { Log.w(TAG, "ITelephony threw RemoteException", ex); } } } if (isMusicActive() && (result & ACTION_PASS_TO_USER) == 0) { if (mVolBtnMusicControls && down && (keyCode != KeyEvent.KEYCODE_VOLUME_MUTE)) { mIsLongPress = false; handleVolumeLongPress(keyCode); break; } else { if (mVolBtnMusicControls && !down) { handleVolumeLongPressAbort(); if (mIsLongPress) { break; } } if (!isScreenOn && !mVolumeWakeScreen) { handleVolumeKey(AudioManager.STREAM_MUSIC, keyCode); } } } if (isScreenOn || !mVolumeWakeScreen) { break; } else if (keyguardActive) { keyCode = KeyEvent.KEYCODE_POWER; mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(keyCode); } else { result |= ACTION_WAKE_UP; break; } } case KeyEvent.KEYCODE_POWER: { result &= ~ACTION_PASS_TO_USER; if (down) { if (isScreenOn && !mPowerKeyTriggered && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) { mPowerKeyTriggered = true; mPowerKeyTime = event.getDownTime(); interceptScreenshotChord(); } ITelephony telephonyService = getTelephonyService(); boolean hungUp = false; if (telephonyService != null) { try { if (telephonyService.isRinging()) { // Pressing Power while there's a ringing incoming // call should silence the ringer. telephonyService.silenceRinger(); } else if ((mIncallPowerBehavior & Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_HANGUP) != 0 && telephonyService.isOffhook()) { // Otherwise, if "Power button ends call" is enabled, // the Power button will hang up any current active call. hungUp = telephonyService.endCall(); } } catch (RemoteException ex) { Log.w(TAG, "ITelephony threw RemoteException", ex); } } interceptPowerKeyDown(!isScreenOn || hungUp || mVolumeDownKeyTriggered || mVolumeUpKeyTriggered); } else { mPowerKeyTriggered = false; cancelPendingScreenshotChordAction(); if (interceptPowerKeyUp(canceled || mPendingPowerKeyUpCanceled)) { result = (result & ~ACTION_WAKE_UP) | ACTION_GO_TO_SLEEP; } mPendingPowerKeyUpCanceled = false; } break; } case KeyEvent.KEYCODE_MEDIA_PLAY: case KeyEvent.KEYCODE_MEDIA_PAUSE: case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: if (down) { ITelephony telephonyService = getTelephonyService(); if (telephonyService != null) { try { if (!telephonyService.isIdle()) { // Suppress PLAY/PAUSE toggle when phone is ringing or in-call // to avoid music playback. break; } } catch (RemoteException ex) { Log.w(TAG, "ITelephony threw RemoteException", ex); } } } case KeyEvent.KEYCODE_HEADSETHOOK: case KeyEvent.KEYCODE_MUTE: case KeyEvent.KEYCODE_MEDIA_STOP: case KeyEvent.KEYCODE_MEDIA_NEXT: case KeyEvent.KEYCODE_MEDIA_PREVIOUS: case KeyEvent.KEYCODE_MEDIA_REWIND: case KeyEvent.KEYCODE_MEDIA_RECORD: case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: { if ((result & ACTION_PASS_TO_USER) == 0) { // Only do this if we would otherwise not pass it to the user. In that // case, the PhoneWindow class will do the same thing, except it will // only do it if the showing app doesn't process the key on its own. // Note that we need to make a copy of the key event here because the // original key event will be recycled when we return. mBroadcastWakeLock.acquire(); Message msg = mHandler.obtainMessage(MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK, new KeyEvent(event)); msg.setAsynchronous(true); msg.sendToTarget(); } break; } case KeyEvent.KEYCODE_CALL: { if (down) { ITelephony telephonyService = getTelephonyService(); if (telephonyService != null) { try { if (telephonyService.isRinging()) { Log.i(TAG, "interceptKeyBeforeQueueing:" + " CALL key-down while ringing: Answer the call!"); telephonyService.answerRingingCall(); // And *don't* pass this key thru to the current activity // (which is presumably the InCallScreen.) result &= ~ACTION_PASS_TO_USER; } } catch (RemoteException ex) { Log.w(TAG, "ITelephony threw RemoteException", ex); } } } break; } } return result; } /** * When the screen is off we ignore some keys that might otherwise typically * be considered wake keys. We filter them out here. * * {@link KeyEvent#KEYCODE_POWER} is notably absent from this list because it * is always considered a wake key. */ private boolean isWakeKeyWhenScreenOff(int keyCode) { switch (keyCode) { // ignore volume keys unless docked case KeyEvent.KEYCODE_VOLUME_UP: case KeyEvent.KEYCODE_VOLUME_DOWN: case KeyEvent.KEYCODE_VOLUME_MUTE: return mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED; // ignore media and camera keys case KeyEvent.KEYCODE_MUTE: case KeyEvent.KEYCODE_HEADSETHOOK: case KeyEvent.KEYCODE_MEDIA_PLAY: case KeyEvent.KEYCODE_MEDIA_PAUSE: case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: case KeyEvent.KEYCODE_MEDIA_STOP: case KeyEvent.KEYCODE_MEDIA_NEXT: case KeyEvent.KEYCODE_MEDIA_PREVIOUS: case KeyEvent.KEYCODE_MEDIA_REWIND: case KeyEvent.KEYCODE_MEDIA_RECORD: case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: case KeyEvent.KEYCODE_CAMERA: return false; } return true; } /** {@inheritDoc} */ @Override public int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags) { int result = 0; final boolean isWakeMotion = (policyFlags & (WindowManagerPolicy.FLAG_WAKE | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0; if (isWakeMotion) { if (mKeyguardMediator != null && mKeyguardMediator.isShowing()) { // If the keyguard is showing, let it decide what to do with the wake motion. mKeyguardMediator.onWakeMotionWhenKeyguardShowingTq(); } else { // Otherwise, wake the device ourselves. result |= ACTION_WAKE_UP; } } return result; } void dispatchMediaKeyWithWakeLock(KeyEvent event) { if (DEBUG_INPUT) { Slog.d(TAG, "dispatchMediaKeyWithWakeLock: " + event); } if (mHavePendingMediaKeyRepeatWithWakeLock) { if (DEBUG_INPUT) { Slog.d(TAG, "dispatchMediaKeyWithWakeLock: canceled repeat"); } mHandler.removeMessages(MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK); mHavePendingMediaKeyRepeatWithWakeLock = false; mBroadcastWakeLock.release(); // pending repeat was holding onto the wake lock } dispatchMediaKeyWithWakeLockToAudioService(event); if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { mHavePendingMediaKeyRepeatWithWakeLock = true; Message msg = mHandler.obtainMessage( MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK, event); msg.setAsynchronous(true); mHandler.sendMessageDelayed(msg, ViewConfiguration.getKeyRepeatTimeout()); } else { mBroadcastWakeLock.release(); } } void dispatchMediaKeyRepeatWithWakeLock(KeyEvent event) { mHavePendingMediaKeyRepeatWithWakeLock = false; KeyEvent repeatEvent = KeyEvent.changeTimeRepeat(event, SystemClock.uptimeMillis(), 1, event.getFlags() | KeyEvent.FLAG_LONG_PRESS); if (DEBUG_INPUT) { Slog.d(TAG, "dispatchMediaKeyRepeatWithWakeLock: " + repeatEvent); } dispatchMediaKeyWithWakeLockToAudioService(repeatEvent); mBroadcastWakeLock.release(); } void dispatchMediaKeyWithWakeLockToAudioService(KeyEvent event) { if (ActivityManagerNative.isSystemReady()) { IAudioService audioService = getAudioService(); if (audioService != null) { try { audioService.dispatchMediaKeyEventUnderWakelock(event); } catch (RemoteException e) { Log.e(TAG, "dispatchMediaKeyEvent threw exception " + e); } } } } BroadcastReceiver mDockReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) { mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED); } updateRotation(true); updateOrientationListenerLp(); } }; BroadcastReceiver mDreamReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_DREAMING_STARTED.equals(intent.getAction())) { if (mKeyguardMediator != null) { mKeyguardMediator.onDreamingStarted(); } } else if (Intent.ACTION_DREAMING_STOPPED.equals(intent.getAction())) { if (mKeyguardMediator != null) { mKeyguardMediator.onDreamingStopped(); } } } }; BroadcastReceiver mMultiuserReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_USER_SWITCHED.equals(intent.getAction())) { // tickle the settings observer: this first ensures that we're // observing the relevant settings for the newly-active user, // and then updates our own bookkeeping based on the now- // current user. mSettingsObserver.onChange(false); } } }; @Override public void screenTurnedOff(int why) { EventLog.writeEvent(70000, 0); synchronized (mLock) { mScreenOnEarly = false; mScreenOnFully = false; } if (mKeyguardMediator != null) { mKeyguardMediator.onScreenTurnedOff(why); } synchronized (mLock) { updateOrientationListenerLp(); updateLockScreenTimeout(); } } @Override public void screenTurningOn(final ScreenOnListener screenOnListener) { EventLog.writeEvent(70000, 1); if (false) { RuntimeException here = new RuntimeException("here"); here.fillInStackTrace(); Slog.i(TAG, "Screen turning on...", here); } synchronized (mLock) { mScreenOnEarly = true; updateOrientationListenerLp(); updateLockScreenTimeout(); } waitForKeyguard(screenOnListener); } private void waitForKeyguard(final ScreenOnListener screenOnListener) { if (mKeyguardMediator != null) { if (screenOnListener != null) { mKeyguardMediator.onScreenTurnedOn(new KeyguardViewManager.ShowListener() { @Override public void onShown(IBinder windowToken) { waitForKeyguardWindowDrawn(windowToken, screenOnListener); } }); return; } else { mKeyguardMediator.onScreenTurnedOn(null); } } else { Slog.i(TAG, "No keyguard mediator!"); } finishScreenTurningOn(screenOnListener); } private void waitForKeyguardWindowDrawn(IBinder windowToken, final ScreenOnListener screenOnListener) { if (windowToken != null) { try { if (mWindowManager.waitForWindowDrawn( windowToken, new IRemoteCallback.Stub() { @Override public void sendResult(Bundle data) { Slog.i(TAG, "Lock screen displayed!"); finishScreenTurningOn(screenOnListener); } })) { return; } } catch (RemoteException ex) { // Can't happen in system process. } } Slog.i(TAG, "No lock screen!"); finishScreenTurningOn(screenOnListener); } private void finishScreenTurningOn(ScreenOnListener screenOnListener) { synchronized (mLock) { mScreenOnFully = true; } try { mWindowManager.setEventDispatching(true); } catch (RemoteException unhandled) { } if (screenOnListener != null) { screenOnListener.onScreenOn(); } } @Override public boolean isScreenOnEarly() { return mScreenOnEarly; } @Override public boolean isScreenOnFully() { return mScreenOnFully; } /** {@inheritDoc} */ public void enableKeyguard(boolean enabled) { if (mKeyguardMediator != null) { mKeyguardMediator.setKeyguardEnabled(enabled); } } /** {@inheritDoc} */ public void exitKeyguardSecurely(OnKeyguardExitResult callback) { if (mKeyguardMediator != null) { mKeyguardMediator.verifyUnlock(callback); } } private boolean keyguardIsShowingTq() { if (mKeyguardMediator == null) return false; return mKeyguardMediator.isShowingAndNotHidden(); } /** {@inheritDoc} */ public boolean isKeyguardLocked() { return keyguardOn(); } /** {@inheritDoc} */ public boolean isKeyguardSecure() { if (mKeyguardMediator == null) return false; return mKeyguardMediator.isSecure(); } /** {@inheritDoc} */ public boolean inKeyguardRestrictedKeyInputMode() { if (mKeyguardMediator == null) return false; return mKeyguardMediator.isInputRestricted(); } public void dismissKeyguardLw() { if (mKeyguardMediator.isShowing()) { mHandler.post(new Runnable() { public void run() { if (mKeyguardMediator.isDismissable()) { // Can we just finish the keyguard straight away? mKeyguardMediator.keyguardDone(false, true); } else { // ask the keyguard to prompt the user to authenticate if necessary mKeyguardMediator.dismiss(); } } }); } } void sendCloseSystemWindows() { sendCloseSystemWindows(mContext, null); } void sendCloseSystemWindows(String reason) { sendCloseSystemWindows(mContext, reason); } static void sendCloseSystemWindows(Context context, String reason) { if (ActivityManagerNative.isSystemReady()) { try { ActivityManagerNative.getDefault().closeSystemDialogs(reason); } catch (RemoteException e) { } } } @Override public int rotationForOrientationLw(int orientation, int lastRotation) { if (false) { Slog.v(TAG, "rotationForOrientationLw(orient=" + orientation + ", last=" + lastRotation + "); user=" + mUserRotation + " " + ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED) ? "USER_ROTATION_LOCKED" : "") ); } synchronized (mLock) { int sensorRotation = mOrientationListener.getProposedRotation(); // may be -1 if (sensorRotation < 0) { sensorRotation = lastRotation; } final int preferredRotation; if (mLidState == LID_OPEN && mLidOpenRotation >= 0) { // Ignore sensor when lid switch is open and rotation is forced. preferredRotation = mLidOpenRotation; } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR && (mCarDockEnablesAccelerometer || mCarDockRotation >= 0)) { // Ignore sensor when in car dock unless explicitly enabled. // This case can override the behavior of NOSENSOR, and can also // enable 180 degree rotation while docked. preferredRotation = mCarDockEnablesAccelerometer ? sensorRotation : mCarDockRotation; } else if ((mDockMode == Intent.EXTRA_DOCK_STATE_DESK || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK) && (mDeskDockEnablesAccelerometer || mDeskDockRotation >= 0)) { // Ignore sensor when in desk dock unless explicitly enabled. // This case can override the behavior of NOSENSOR, and can also // enable 180 degree rotation while docked. preferredRotation = mDeskDockEnablesAccelerometer ? sensorRotation : mDeskDockRotation; } else if (mHdmiPlugged && mHdmiRotationLock) { // Ignore sensor when plugged into HDMI. // Note that the dock orientation overrides the HDMI orientation. preferredRotation = mHdmiRotation; } else if ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_FREE && (orientation == ActivityInfo.SCREEN_ORIENTATION_USER || orientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)) || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) { // Otherwise, use sensor only if requested by the application or enabled // by default for USER or UNSPECIFIED modes. Does not apply to NOSENSOR. if (mAllowAllRotations < 0) { // Can't read this during init() because the context doesn't // have display metrics at that time so we cannot determine // tablet vs. phone then. mAllowAllRotations = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowAllRotations) ? 1 : 0; } if (sensorRotation != Surface.ROTATION_180 || mAllowAllRotations == 1 || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR) { preferredRotation = sensorRotation; } else { preferredRotation = lastRotation; } } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED && orientation != ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) { // Apply rotation lock. Does not apply to NOSENSOR. // The idea is that the user rotation expresses a weak preference for the direction // of gravity and as NOSENSOR is never affected by gravity, then neither should // NOSENSOR be affected by rotation lock (although it will be affected by docks). preferredRotation = mUserRotation; } else { // No overriding preference. // We will do exactly what the application asked us to do. preferredRotation = -1; } switch (orientation) { case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT: // Return portrait unless overridden. if (isAnyPortrait(preferredRotation)) { return preferredRotation; } return mPortraitRotation; case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE: // Return landscape unless overridden. if (isLandscapeOrSeascape(preferredRotation)) { return preferredRotation; } return mLandscapeRotation; case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT: // Return reverse portrait unless overridden. if (isAnyPortrait(preferredRotation)) { return preferredRotation; } return mUpsideDownRotation; case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE: // Return seascape unless overridden. if (isLandscapeOrSeascape(preferredRotation)) { return preferredRotation; } return mSeascapeRotation; case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE: // Return either landscape rotation. if (isLandscapeOrSeascape(preferredRotation)) { return preferredRotation; } if (isLandscapeOrSeascape(lastRotation)) { return lastRotation; } return mLandscapeRotation; case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT: // Return either portrait rotation. if (isAnyPortrait(preferredRotation)) { return preferredRotation; } if (isAnyPortrait(lastRotation)) { return lastRotation; } return mPortraitRotation; default: // For USER, UNSPECIFIED, NOSENSOR, SENSOR and FULL_SENSOR, // just return the preferred orientation we already calculated. if (preferredRotation >= 0) { return preferredRotation; } return Surface.ROTATION_0; } } } @Override public boolean rotationHasCompatibleMetricsLw(int orientation, int rotation) { switch (orientation) { case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT: case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT: case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT: return isAnyPortrait(rotation); case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE: case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE: case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE: return isLandscapeOrSeascape(rotation); default: return true; } } @Override public void setRotationLw(int rotation) { mOrientationListener.setCurrentRotation(rotation); } private boolean isLandscapeOrSeascape(int rotation) { return rotation == mLandscapeRotation || rotation == mSeascapeRotation; } private boolean isAnyPortrait(int rotation) { return rotation == mPortraitRotation || rotation == mUpsideDownRotation; } // User rotation: to be used when all else fails in assigning an orientation to the device public void setUserRotationMode(int mode, int rot) { ContentResolver res = mContext.getContentResolver(); // mUserRotationMode and mUserRotation will be assigned by the content observer if (mode == WindowManagerPolicy.USER_ROTATION_LOCKED) { Settings.System.putIntForUser(res, Settings.System.USER_ROTATION, rot, UserHandle.USER_CURRENT); Settings.System.putIntForUser(res, Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT); } else { Settings.System.putIntForUser(res, Settings.System.ACCELEROMETER_ROTATION, 1, UserHandle.USER_CURRENT); } } public void setSafeMode(boolean safeMode) { mSafeMode = safeMode; performHapticFeedbackLw(null, safeMode ? HapticFeedbackConstants.SAFE_MODE_ENABLED : HapticFeedbackConstants.SAFE_MODE_DISABLED, true); } static long[] getLongIntArray(Resources r, int resid) { int[] ar = r.getIntArray(resid); if (ar == null) { return null; } long[] out = new long[ar.length]; for (int i=0; i<ar.length; i++) { out[i] = ar[i]; } return out; } /** {@inheritDoc} */ public void systemReady() { if (mKeyguardMediator != null) { // tell the keyguard mKeyguardMediator.onSystemReady(); } synchronized (mLock) { updateOrientationListenerLp(); mSystemReady = true; mHandler.post(new Runnable() { public void run() { updateSettings(); } }); } } /** {@inheritDoc} */ public void systemBooted() { synchronized (mLock) { mSystemBooted = true; } } ProgressDialog mBootMsgDialog = null; /** {@inheritDoc} */ public void showBootMessage(final CharSequence msg, final boolean always) { if (mHeadless) return; mHandler.post(new Runnable() { @Override public void run() { if (mBootMsgDialog == null) { mBootMsgDialog = new ProgressDialog(mContext) { // This dialog will consume all events coming in to // it, to avoid it trying to do things too early in boot. @Override public boolean dispatchKeyEvent(KeyEvent event) { return true; } @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) { return true; } @Override public boolean dispatchTouchEvent(MotionEvent ev) { return true; } @Override public boolean dispatchTrackballEvent(MotionEvent ev) { return true; } @Override public boolean dispatchGenericMotionEvent(MotionEvent ev) { return true; } @Override public boolean dispatchPopulateAccessibilityEvent( AccessibilityEvent event) { return true; } }; mBootMsgDialog.setTitle(R.string.android_upgrading_title); mBootMsgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mBootMsgDialog.setIndeterminate(true); mBootMsgDialog.getWindow().setType( WindowManager.LayoutParams.TYPE_BOOT_PROGRESS); mBootMsgDialog.getWindow().addFlags( WindowManager.LayoutParams.FLAG_DIM_BEHIND | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); mBootMsgDialog.getWindow().setDimAmount(1); WindowManager.LayoutParams lp = mBootMsgDialog.getWindow().getAttributes(); lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR; mBootMsgDialog.getWindow().setAttributes(lp); mBootMsgDialog.setCancelable(false); mBootMsgDialog.show(); } mBootMsgDialog.setMessage(msg); } }); } /** {@inheritDoc} */ public void hideBootMessages() { mHandler.post(new Runnable() { @Override public void run() { if (mBootMsgDialog != null) { mBootMsgDialog.dismiss(); mBootMsgDialog = null; } } }); } /** {@inheritDoc} */ public void userActivity() { // *************************************** // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE // *************************************** // THIS IS CALLED FROM DEEP IN THE POWER MANAGER // WITH ITS LOCKS HELD. // // This code must be VERY careful about the locks // it acquires. // In fact, the current code acquires way too many, // and probably has lurking deadlocks. synchronized (mScreenLockTimeout) { if (mLockScreenTimerActive) { // reset the timer mHandler.removeCallbacks(mScreenLockTimeout); mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout); } } } class ScreenLockTimeout implements Runnable { Bundle options; @Override public void run() { synchronized (this) { if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard"); if (mKeyguardMediator != null) { mKeyguardMediator.doKeyguardTimeout(options); } mLockScreenTimerActive = false; options = null; } } public void setLockOptions(Bundle options) { this.options = options; } } ScreenLockTimeout mScreenLockTimeout = new ScreenLockTimeout(); public void lockNow(Bundle options) { mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); mHandler.removeCallbacks(mScreenLockTimeout); if (options != null) { // In case multiple calls are made to lockNow, we don't wipe out the options // until the runnable actually executes. mScreenLockTimeout.setLockOptions(options); } mHandler.post(mScreenLockTimeout); } private void updateLockScreenTimeout() { synchronized (mScreenLockTimeout) { boolean enable = (mAllowLockscreenWhenOn && mScreenOnEarly && mKeyguardMediator != null && mKeyguardMediator.isSecure()); if (mLockScreenTimerActive != enable) { if (enable) { if (localLOGV) Log.v(TAG, "setting lockscreen timer"); mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout); } else { if (localLOGV) Log.v(TAG, "clearing lockscreen timer"); mHandler.removeCallbacks(mScreenLockTimeout); } mLockScreenTimerActive = enable; } } } /** {@inheritDoc} */ public void enableScreenAfterBoot() { readLidState(); applyLidSwitchState(); updateRotation(true); } private void applyLidSwitchState() { if (mLidState == LID_CLOSED && mLidControlsSleep) { mPowerManager.goToSleep(SystemClock.uptimeMillis()); } } void updateRotation(boolean alwaysSendConfiguration) { try { //set orientation on WindowManager mWindowManager.updateRotation(alwaysSendConfiguration, false); } catch (RemoteException e) { // Ignore } } void updateRotation(boolean alwaysSendConfiguration, boolean forceRelayout) { try { //set orientation on WindowManager mWindowManager.updateRotation(alwaysSendConfiguration, forceRelayout); } catch (RemoteException e) { // Ignore } } void startDockOrHome() { // We don't have dock home anymore. Home is home. If you lived here, you'd be home by now. mContext.startActivityAsUser(mHomeIntent, UserHandle.CURRENT); } /** * goes to the home screen * @return whether it did anything */ boolean goHome() { if (false) { // This code always brings home to the front. try { ActivityManagerNative.getDefault().stopAppSwitches(); } catch (RemoteException e) { } sendCloseSystemWindows(); startDockOrHome(); } else { // This code brings home to the front or, if it is already // at the front, puts the device to sleep. try { if (SystemProperties.getInt("persist.sys.uts-test-mode", 0) == 1) { /// Roll back EndcallBehavior as the cupcake design to pass P1 lab entry. Log.d(TAG, "UTS-TEST-MODE"); } else { ActivityManagerNative.getDefault().stopAppSwitches(); sendCloseSystemWindows(); } int result = ActivityManagerNative.getDefault() .startActivityAsUser(null, mHomeIntent, mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()), null, null, 0, ActivityManager.START_FLAG_ONLY_IF_NEEDED, null, null, null, UserHandle.USER_CURRENT); if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) { return false; } } catch (RemoteException ex) { // bummer, the activity manager, which is in this process, is dead } } return true; } public void setCurrentOrientationLw(int newOrientation) { synchronized (mLock) { if (newOrientation != mCurrentAppOrientation) { mCurrentAppOrientation = newOrientation; updateOrientationListenerLp(); } } } private void performAuditoryFeedbackForAccessibilityIfNeed() { if (!isGlobalAccessibilityGestureEnabled()) { return; } AudioManager audioManager = (AudioManager) mContext.getSystemService( Context.AUDIO_SERVICE); if (audioManager.isSilentMode()) { return; } Ringtone ringTone = RingtoneManager.getRingtone(mContext, Settings.System.DEFAULT_NOTIFICATION_URI); ringTone.setStreamType(AudioManager.STREAM_MUSIC); ringTone.play(); } private boolean isGlobalAccessibilityGestureEnabled() { return Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED, 0) == 1; } public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) { if (!mVibrator.hasVibrator()) { return false; } final boolean hapticsDisabled = Settings.System.getIntForUser(mContext.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 0, UserHandle.USER_CURRENT) == 0; if (!always && (hapticsDisabled || mKeyguardMediator.isShowingAndNotHidden())) { return false; } long[] pattern = null; switch (effectId) { case HapticFeedbackConstants.LONG_PRESS: pattern = mLongPressVibePattern; break; case HapticFeedbackConstants.VIRTUAL_KEY: pattern = mVirtualKeyVibePattern; break; case HapticFeedbackConstants.KEYBOARD_TAP: pattern = mKeyboardTapVibePattern; break; case HapticFeedbackConstants.SAFE_MODE_DISABLED: pattern = mSafeModeDisabledVibePattern; break; case HapticFeedbackConstants.SAFE_MODE_ENABLED: pattern = mSafeModeEnabledVibePattern; break; default: return false; } if (pattern.length == 1) { // One-shot vibration mVibrator.vibrate(pattern[0]); } else { // Pattern vibration mVibrator.vibrate(pattern, -1); } return true; } @Override public void keepScreenOnStartedLw() { } @Override public void keepScreenOnStoppedLw() { if (mKeyguardMediator != null && !mKeyguardMediator.isShowingAndNotHidden()) { long curTime = SystemClock.uptimeMillis(); mPowerManager.userActivity(curTime, false); } } private int updateSystemUiVisibilityLw() { // If there is no window focused, there will be nobody to handle the events // anyway, so just hang on in whatever state we're in until things settle down. if (mFocusedWindow == null) { return 0; } if (mFocusedWindow.getAttrs().type == TYPE_KEYGUARD && mHideLockScreen == true) { // We are updating at a point where the keyguard has gotten // focus, but we were last in a state where the top window is // hiding it. This is probably because the keyguard as been // shown while the top window was displayed, so we want to ignore // it here because this is just a very transient change and it // will quickly lose focus once it correctly gets hidden. return 0; } final int visibility = mFocusedWindow.getSystemUiVisibility() & ~mResettingSystemUiFlags & ~mForceClearedSystemUiFlags; int diff = visibility ^ mLastSystemUiFlags; final boolean needsMenu = mFocusedWindow.getNeedsMenuLw(mTopFullscreenOpaqueWindowState); if (diff == 0 && mLastFocusNeedsMenu == needsMenu && mFocusedApp == mFocusedWindow.getAppToken()) { return 0; } mLastSystemUiFlags = visibility; mLastFocusNeedsMenu = needsMenu; mFocusedApp = mFocusedWindow.getAppToken(); mHandler.post(new Runnable() { public void run() { try { IStatusBarService statusbar = getStatusBarService(); if (statusbar != null) { statusbar.setSystemUiVisibility(visibility, 0xffffffff); statusbar.topAppWindowChanged(needsMenu); } } catch (RemoteException e) { // re-acquire status bar service next time it is needed. mStatusBarService = null; } } }); return diff; } // Use this instead of checking config_showNavigationBar so that it can be consistently // overridden by qemu.hw.mainkeys in the emulator. public boolean hasNavigationBar() { return mHasNavigationBar; } @Override public void setLastInputMethodWindowLw(WindowState ime, WindowState target) { mLastInputMethodWindow = ime; mLastInputMethodTargetWindow = target; } @Override public boolean canMagnifyWindowLw(WindowManager.LayoutParams attrs) { switch (attrs.type) { case WindowManager.LayoutParams.TYPE_INPUT_METHOD: case WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG: case WindowManager.LayoutParams.TYPE_NAVIGATION_BAR: case WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY: { return false; } } return true; } @Override public void setCurrentUserLw(int newUserId) { if (mKeyguardMediator != null) { mKeyguardMediator.setCurrentUser(newUserId); } if (mStatusBarService != null) { try { mStatusBarService.setCurrentUser(newUserId); } catch (RemoteException e) { // oh well } } setLastInputMethodWindowLw(null, null); } @Override public void showAssistant() { mKeyguardMediator.showAssistant(); } @Override public void dump(String prefix, PrintWriter pw, String[] args) { pw.print(prefix); pw.print("mSafeMode="); pw.print(mSafeMode); pw.print(" mSystemReady="); pw.print(mSystemReady); pw.print(" mSystemBooted="); pw.println(mSystemBooted); pw.print(prefix); pw.print("mLidState="); pw.print(mLidState); pw.print(" mLidOpenRotation="); pw.print(mLidOpenRotation); pw.print(" mHdmiPlugged="); pw.println(mHdmiPlugged); if (mLastSystemUiFlags != 0 || mResettingSystemUiFlags != 0 || mForceClearedSystemUiFlags != 0) { pw.print(prefix); pw.print("mLastSystemUiFlags=0x"); pw.print(Integer.toHexString(mLastSystemUiFlags)); pw.print(" mResettingSystemUiFlags=0x"); pw.print(Integer.toHexString(mResettingSystemUiFlags)); pw.print(" mForceClearedSystemUiFlags=0x"); pw.println(Integer.toHexString(mForceClearedSystemUiFlags)); } if (mLastFocusNeedsMenu) { pw.print(prefix); pw.print("mLastFocusNeedsMenu="); pw.println(mLastFocusNeedsMenu); } pw.print(prefix); pw.print("mDockMode="); pw.print(mDockMode); pw.print(" mCarDockRotation="); pw.print(mCarDockRotation); pw.print(" mDeskDockRotation="); pw.println(mDeskDockRotation); pw.print(prefix); pw.print("mUserRotationMode="); pw.print(mUserRotationMode); pw.print(" mUserRotation="); pw.print(mUserRotation); pw.print(" mAllowAllRotations="); pw.println(mAllowAllRotations); pw.print(prefix); pw.print("mCurrentAppOrientation="); pw.println(mCurrentAppOrientation); pw.print(prefix); pw.print("mCarDockEnablesAccelerometer="); pw.print(mCarDockEnablesAccelerometer); pw.print(" mDeskDockEnablesAccelerometer="); pw.println(mDeskDockEnablesAccelerometer); pw.print(prefix); pw.print("mLidKeyboardAccessibility="); pw.print(mLidKeyboardAccessibility); pw.print(" mLidNavigationAccessibility="); pw.print(mLidNavigationAccessibility); pw.print(" mLidControlsSleep="); pw.println(mLidControlsSleep); pw.print(prefix); pw.print("mLongPressOnPowerBehavior="); pw.print(mLongPressOnPowerBehavior); pw.print(" mHasSoftInput="); pw.println(mHasSoftInput); pw.print(prefix); pw.print("mScreenOnEarly="); pw.print(mScreenOnEarly); pw.print(" mScreenOnFully="); pw.print(mScreenOnFully); pw.print(" mOrientationSensorEnabled="); pw.println(mOrientationSensorEnabled); pw.print(prefix); pw.print("mUnrestrictedScreen=("); pw.print(mUnrestrictedScreenLeft); pw.print(","); pw.print(mUnrestrictedScreenTop); pw.print(") "); pw.print(mUnrestrictedScreenWidth); pw.print("x"); pw.println(mUnrestrictedScreenHeight); pw.print(prefix); pw.print("mRestrictedScreen=("); pw.print(mRestrictedScreenLeft); pw.print(","); pw.print(mRestrictedScreenTop); pw.print(") "); pw.print(mRestrictedScreenWidth); pw.print("x"); pw.println(mRestrictedScreenHeight); pw.print(prefix); pw.print("mStableFullscreen=("); pw.print(mStableFullscreenLeft); pw.print(","); pw.print(mStableFullscreenTop); pw.print(")-("); pw.print(mStableFullscreenRight); pw.print(","); pw.print(mStableFullscreenBottom); pw.println(")"); pw.print(prefix); pw.print("mStable=("); pw.print(mStableLeft); pw.print(","); pw.print(mStableTop); pw.print(")-("); pw.print(mStableRight); pw.print(","); pw.print(mStableBottom); pw.println(")"); pw.print(prefix); pw.print("mSystem=("); pw.print(mSystemLeft); pw.print(","); pw.print(mSystemTop); pw.print(")-("); pw.print(mSystemRight); pw.print(","); pw.print(mSystemBottom); pw.println(")"); pw.print(prefix); pw.print("mCur=("); pw.print(mCurLeft); pw.print(","); pw.print(mCurTop); pw.print(")-("); pw.print(mCurRight); pw.print(","); pw.print(mCurBottom); pw.println(")"); pw.print(prefix); pw.print("mContent=("); pw.print(mContentLeft); pw.print(","); pw.print(mContentTop); pw.print(")-("); pw.print(mContentRight); pw.print(","); pw.print(mContentBottom); pw.println(")"); pw.print(prefix); pw.print("mDock=("); pw.print(mDockLeft); pw.print(","); pw.print(mDockTop); pw.print(")-("); pw.print(mDockRight); pw.print(","); pw.print(mDockBottom); pw.println(")"); pw.print(prefix); pw.print("mDockLayer="); pw.print(mDockLayer); pw.print(" mStatusBarLayer="); pw.println(mStatusBarLayer); pw.print(prefix); pw.print("mShowingLockscreen="); pw.print(mShowingLockscreen); pw.print(" mShowingDream="); pw.print(mShowingDream); pw.print(" mDreamingLockscreen="); pw.println(mDreamingLockscreen); if (mLastInputMethodWindow != null) { pw.print(prefix); pw.print("mLastInputMethodWindow="); pw.println(mLastInputMethodWindow); } if (mLastInputMethodTargetWindow != null) { pw.print(prefix); pw.print("mLastInputMethodTargetWindow="); pw.println(mLastInputMethodTargetWindow); } if (mStatusBar != null) { pw.print(prefix); pw.print("mStatusBar="); pw.println(mStatusBar); } if (mNavigationBar != null) { pw.print(prefix); pw.print("mNavigationBar="); pw.println(mNavigationBar); } if (mKeyguard != null) { pw.print(prefix); pw.print("mKeyguard="); pw.println(mKeyguard); } if (mFocusedWindow != null) { pw.print(prefix); pw.print("mFocusedWindow="); pw.println(mFocusedWindow); } if (mFocusedApp != null) { pw.print(prefix); pw.print("mFocusedApp="); pw.println(mFocusedApp); } if (mWinDismissingKeyguard != null) { pw.print(prefix); pw.print("mWinDismissingKeyguard="); pw.println(mWinDismissingKeyguard); } if (mTopFullscreenOpaqueWindowState != null) { pw.print(prefix); pw.print("mTopFullscreenOpaqueWindowState="); pw.println(mTopFullscreenOpaqueWindowState); } pw.print(prefix); pw.print("mTopIsFullscreen="); pw.print(mTopIsFullscreen); pw.print(" mHideLockScreen="); pw.println(mHideLockScreen); pw.print(prefix); pw.print("mForceStatusBar="); pw.print(mForceStatusBar); pw.print(" mForceStatusBarFromKeyguard="); pw.println(mForceStatusBarFromKeyguard); pw.print(prefix); pw.print("mDismissKeyguard="); pw.print(mDismissKeyguard); pw.print(" mWinDismissingKeyguard="); pw.print(mWinDismissingKeyguard); pw.print(" mHomePressed="); pw.println(mHomePressed); pw.print(prefix); pw.print("mAllowLockscreenWhenOn="); pw.print(mAllowLockscreenWhenOn); pw.print(" mLockScreenTimeout="); pw.print(mLockScreenTimeout); pw.print(" mLockScreenTimerActive="); pw.println(mLockScreenTimerActive); pw.print(prefix); pw.print("mEndcallBehavior="); pw.print(mEndcallBehavior); pw.print(" mIncallPowerBehavior="); pw.print(mIncallPowerBehavior); pw.print(" mLongPressOnHomeBehavior="); pw.println(mLongPressOnHomeBehavior); pw.print(prefix); pw.print("mLandscapeRotation="); pw.print(mLandscapeRotation); pw.print(" mSeascapeRotation="); pw.println(mSeascapeRotation); pw.print(prefix); pw.print("mPortraitRotation="); pw.print(mPortraitRotation); pw.print(" mUpsideDownRotation="); pw.println(mUpsideDownRotation); pw.print(prefix); pw.print("mHdmiRotation="); pw.print(mHdmiRotation); pw.print(" mHdmiRotationLock="); pw.println(mHdmiRotationLock); } }
true
true
public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags) { final boolean keyguardOn = keyguardOn(); final int keyCode = event.getKeyCode(); final int repeatCount = event.getRepeatCount(); final int metaState = event.getMetaState(); final int flags = event.getFlags(); final boolean down = event.getAction() == KeyEvent.ACTION_DOWN; final boolean canceled = event.isCanceled(); if (DEBUG_INPUT) { Log.d(TAG, "interceptKeyTi keyCode=" + keyCode + " down=" + down + " repeatCount=" + repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed + " canceled=" + canceled); } // If we think we might have a volume down & power key chord on the way // but we're not sure, then tell the dispatcher to wait a little while and // try again later before dispatching. if (mScreenshotChordEnabled && (flags & KeyEvent.FLAG_FALLBACK) == 0) { if (mVolumeDownKeyTriggered && !mPowerKeyTriggered) { final long now = SystemClock.uptimeMillis(); final long timeoutTime = mVolumeDownKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS; if (now < timeoutTime) { return timeoutTime - now; } } if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN && mVolumeDownKeyConsumedByScreenshotChord) { if (!down) { mVolumeDownKeyConsumedByScreenshotChord = false; } return -1; } } // First we always handle the home key here, so applications // can never break it, although if keyguard is on, we do let // it handle it, because that gives us the correct 5 second // timeout. if (keyCode == KeyEvent.KEYCODE_HOME) { // If we have released the home key, and didn't do anything else // while it was pressed, then it is time to go home! if (!down) { final boolean homeWasLongPressed = mHomeLongPressed; mHomePressed = false; mHomeLongPressed = false; if (!homeWasLongPressed) { if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI) { try { IStatusBarService statusbar = getStatusBarService(); if (statusbar != null) { statusbar.cancelPreloadRecentApps(); } } catch (RemoteException e) { Slog.e(TAG, "RemoteException when showing recent apps", e); // re-acquire status bar service next time it is needed. mStatusBarService = null; } } mHomePressed = false; if (!canceled) { // If an incoming call is ringing, HOME is totally disabled. // (The user is already on the InCallScreen at this point, // and his ONLY options are to answer or reject the call.) boolean incomingRinging = false; try { ITelephony telephonyService = getTelephonyService(); if (telephonyService != null) { incomingRinging = telephonyService.isRinging(); } } catch (RemoteException ex) { Log.w(TAG, "RemoteException from getPhoneInterface()", ex); } if (incomingRinging) { Log.i(TAG, "Ignoring HOME; there's a ringing incoming call."); } else { launchHomeFromHotKey(); } } else { Log.i(TAG, "Ignoring HOME; event canceled."); } return -1; } } // If a system window has focus, then it doesn't make sense // right now to interact with applications. WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null; if (attrs != null) { final int type = attrs.type; if (type == WindowManager.LayoutParams.TYPE_KEYGUARD || type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG) { // the "app" is keyguard, so give it the key return 0; } final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length; for (int i=0; i<typeCount; i++) { if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) { // don't do anything, but also don't pass it to the app return -1; } } } if (down) { if (!mHomePressed && mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI) { try { IStatusBarService statusbar = getStatusBarService(); if (statusbar != null) { statusbar.preloadRecentApps(); } } catch (RemoteException e) { Slog.e(TAG, "RemoteException when preloading recent apps", e); // re-acquire status bar service next time it is needed. mStatusBarService = null; } } if (repeatCount == 0) { mHomePressed = true; } else if ((event.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0) { if (!keyguardOn) { handleLongPressOnHome(); } } } return -1; } else if (keyCode == KeyEvent.KEYCODE_MENU) { // Hijack modified menu keys for debugging features final int chordBug = KeyEvent.META_SHIFT_ON; if (down && repeatCount == 0) { if (mEnableShiftMenuBugReports && (metaState & chordBug) == chordBug) { Intent intent = new Intent(Intent.ACTION_BUG_REPORT); mContext.sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT, null, null, null, 0, null, null); return -1; } else if (SHOW_PROCESSES_ON_ALT_MENU && (metaState & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON) { Intent service = new Intent(); service.setClassName(mContext, "com.android.server.LoadAverageService"); ContentResolver res = mContext.getContentResolver(); boolean shown = Settings.Global.getInt( res, Settings.Global.SHOW_PROCESSES, 0) != 0; if (!shown) { mContext.startService(service); } else { mContext.stopService(service); } Settings.Global.putInt( res, Settings.Global.SHOW_PROCESSES, shown ? 0 : 1); return -1; } } } else if (keyCode == KeyEvent.KEYCODE_SEARCH) { if (down) { if (repeatCount == 0) { mSearchKeyShortcutPending = true; mConsumeSearchKeyUp = false; } } else { mSearchKeyShortcutPending = false; if (mConsumeSearchKeyUp) { mConsumeSearchKeyUp = false; return -1; } } return 0; } else if (keyCode == KeyEvent.KEYCODE_APP_SWITCH) { if (down && repeatCount == 0 && !keyguardOn) { showOrHideRecentAppsDialog(RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS); } return -1; } else if (keyCode == KeyEvent.KEYCODE_ASSIST) { if (down) { if (repeatCount == 0) { mAssistKeyLongPressed = false; } else if (repeatCount == 1) { mAssistKeyLongPressed = true; if (!keyguardOn) { launchAssistLongPressAction(); } } } else { if (mAssistKeyLongPressed) { mAssistKeyLongPressed = false; } else { if (!keyguardOn) { launchAssistAction(); } } } return -1; } // Shortcuts are invoked through Search+key, so intercept those here // Any printing key that is chorded with Search should be consumed // even if no shortcut was invoked. This prevents text from being // inadvertently inserted when using a keyboard that has built-in macro // shortcut keys (that emit Search+x) and some of them are not registered. if (mSearchKeyShortcutPending) { final KeyCharacterMap kcm = event.getKeyCharacterMap(); if (kcm.isPrintingKey(keyCode)) { mConsumeSearchKeyUp = true; mSearchKeyShortcutPending = false; if (down && repeatCount == 0 && !keyguardOn) { Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState); if (shortcutIntent != null) { shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { mContext.startActivity(shortcutIntent); } catch (ActivityNotFoundException ex) { Slog.w(TAG, "Dropping shortcut key combination because " + "the activity to which it is registered was not found: " + "SEARCH+" + KeyEvent.keyCodeToString(keyCode), ex); } } else { Slog.i(TAG, "Dropping unregistered shortcut key combination: " + "SEARCH+" + KeyEvent.keyCodeToString(keyCode)); } } return -1; } } // Invoke shortcuts using Meta. if (down && repeatCount == 0 && !keyguardOn && (metaState & KeyEvent.META_META_ON) != 0) { final KeyCharacterMap kcm = event.getKeyCharacterMap(); if (kcm.isPrintingKey(keyCode)) { Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState & ~(KeyEvent.META_META_ON | KeyEvent.META_META_LEFT_ON | KeyEvent.META_META_RIGHT_ON)); if (shortcutIntent != null) { shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { mContext.startActivity(shortcutIntent); } catch (ActivityNotFoundException ex) { Slog.w(TAG, "Dropping shortcut key combination because " + "the activity to which it is registered was not found: " + "META+" + KeyEvent.keyCodeToString(keyCode), ex); } return -1; } } } // Handle application launch keys. if (down && repeatCount == 0 && !keyguardOn) { String category = sApplicationLaunchKeyCategories.get(keyCode); if (category != null) { Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, category); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { mContext.startActivity(intent); } catch (ActivityNotFoundException ex) { Slog.w(TAG, "Dropping application launch key because " + "the activity to which it is registered was not found: " + "keyCode=" + keyCode + ", category=" + category, ex); } return -1; } } // Display task switcher for ALT-TAB or Meta-TAB. if (down && repeatCount == 0 && keyCode == KeyEvent.KEYCODE_TAB) { if (mRecentAppsDialogHeldModifiers == 0 && !keyguardOn) { final int shiftlessModifiers = event.getModifiers() & ~KeyEvent.META_SHIFT_MASK; if (KeyEvent.metaStateHasModifiers(shiftlessModifiers, KeyEvent.META_ALT_ON) || KeyEvent.metaStateHasModifiers( shiftlessModifiers, KeyEvent.META_META_ON)) { mRecentAppsDialogHeldModifiers = shiftlessModifiers; showOrHideRecentAppsDialog(RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW); return -1; } } } else if (!down && mRecentAppsDialogHeldModifiers != 0 && (metaState & mRecentAppsDialogHeldModifiers) == 0) { mRecentAppsDialogHeldModifiers = 0; showOrHideRecentAppsDialog(keyguardOn ? RECENT_APPS_BEHAVIOR_DISMISS : RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH); } // Handle keyboard language switching. if (down && repeatCount == 0 && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH || (keyCode == KeyEvent.KEYCODE_SPACE && (metaState & KeyEvent.META_CTRL_MASK) != 0))) { int direction = (metaState & KeyEvent.META_SHIFT_MASK) != 0 ? -1 : 1; mWindowManagerFuncs.switchKeyboardLayout(event.getDeviceId(), direction); return -1; } if (mLanguageSwitchKeyPressed && !down && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH || keyCode == KeyEvent.KEYCODE_SPACE)) { mLanguageSwitchKeyPressed = false; return -1; } // Let the application handle the key. return 0; }
public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags) { final boolean keyguardOn = keyguardOn(); final int keyCode = event.getKeyCode(); final int repeatCount = event.getRepeatCount(); final int metaState = event.getMetaState(); final int flags = event.getFlags(); final boolean down = event.getAction() == KeyEvent.ACTION_DOWN; final boolean canceled = event.isCanceled(); if (DEBUG_INPUT) { Log.d(TAG, "interceptKeyTi keyCode=" + keyCode + " down=" + down + " repeatCount=" + repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed + " canceled=" + canceled); } // If we think we might have a volume down & power key chord on the way // but we're not sure, then tell the dispatcher to wait a little while and // try again later before dispatching. if (mScreenshotChordEnabled && (flags & KeyEvent.FLAG_FALLBACK) == 0) { if (mVolumeDownKeyTriggered && !mPowerKeyTriggered) { final long now = SystemClock.uptimeMillis(); final long timeoutTime = mVolumeDownKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS; if (now < timeoutTime) { return timeoutTime - now; } } if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN && mVolumeDownKeyConsumedByScreenshotChord) { if (!down) { mVolumeDownKeyConsumedByScreenshotChord = false; } return -1; } } // First we always handle the home key here, so applications // can never break it, although if keyguard is on, we do let // it handle it, because that gives us the correct 5 second // timeout. if (keyCode == KeyEvent.KEYCODE_HOME) { // If we have released the home key, and didn't do anything else // while it was pressed, then it is time to go home! if (!down && mHomePressed) { final boolean homeWasLongPressed = mHomeLongPressed; mHomePressed = false; mHomeLongPressed = false; if (!homeWasLongPressed) { if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI) { try { IStatusBarService statusbar = getStatusBarService(); if (statusbar != null) { statusbar.cancelPreloadRecentApps(); } } catch (RemoteException e) { Slog.e(TAG, "RemoteException when showing recent apps", e); // re-acquire status bar service next time it is needed. mStatusBarService = null; } } mHomePressed = false; if (!canceled) { // If an incoming call is ringing, HOME is totally disabled. // (The user is already on the InCallScreen at this point, // and his ONLY options are to answer or reject the call.) boolean incomingRinging = false; try { ITelephony telephonyService = getTelephonyService(); if (telephonyService != null) { incomingRinging = telephonyService.isRinging(); } } catch (RemoteException ex) { Log.w(TAG, "RemoteException from getPhoneInterface()", ex); } if (incomingRinging) { Log.i(TAG, "Ignoring HOME; there's a ringing incoming call."); } else { launchHomeFromHotKey(); } } else { Log.i(TAG, "Ignoring HOME; event canceled."); } return -1; } } // If a system window has focus, then it doesn't make sense // right now to interact with applications. WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null; if (attrs != null) { final int type = attrs.type; if (type == WindowManager.LayoutParams.TYPE_KEYGUARD || type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG) { // the "app" is keyguard, so give it the key return 0; } final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length; for (int i=0; i<typeCount; i++) { if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) { // don't do anything, but also don't pass it to the app return -1; } } } if (down) { if (!mHomePressed && mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI) { try { IStatusBarService statusbar = getStatusBarService(); if (statusbar != null) { statusbar.preloadRecentApps(); } } catch (RemoteException e) { Slog.e(TAG, "RemoteException when preloading recent apps", e); // re-acquire status bar service next time it is needed. mStatusBarService = null; } } if (repeatCount == 0) { mHomePressed = true; } else if ((event.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0) { if (!keyguardOn) { handleLongPressOnHome(); } } } return -1; } else if (keyCode == KeyEvent.KEYCODE_MENU) { // Hijack modified menu keys for debugging features final int chordBug = KeyEvent.META_SHIFT_ON; if (down && repeatCount == 0) { if (mEnableShiftMenuBugReports && (metaState & chordBug) == chordBug) { Intent intent = new Intent(Intent.ACTION_BUG_REPORT); mContext.sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT, null, null, null, 0, null, null); return -1; } else if (SHOW_PROCESSES_ON_ALT_MENU && (metaState & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON) { Intent service = new Intent(); service.setClassName(mContext, "com.android.server.LoadAverageService"); ContentResolver res = mContext.getContentResolver(); boolean shown = Settings.Global.getInt( res, Settings.Global.SHOW_PROCESSES, 0) != 0; if (!shown) { mContext.startService(service); } else { mContext.stopService(service); } Settings.Global.putInt( res, Settings.Global.SHOW_PROCESSES, shown ? 0 : 1); return -1; } } } else if (keyCode == KeyEvent.KEYCODE_SEARCH) { if (down) { if (repeatCount == 0) { mSearchKeyShortcutPending = true; mConsumeSearchKeyUp = false; } } else { mSearchKeyShortcutPending = false; if (mConsumeSearchKeyUp) { mConsumeSearchKeyUp = false; return -1; } } return 0; } else if (keyCode == KeyEvent.KEYCODE_APP_SWITCH) { if (down && repeatCount == 0 && !keyguardOn) { showOrHideRecentAppsDialog(RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS); } return -1; } else if (keyCode == KeyEvent.KEYCODE_ASSIST) { if (down) { if (repeatCount == 0) { mAssistKeyLongPressed = false; } else if (repeatCount == 1) { mAssistKeyLongPressed = true; if (!keyguardOn) { launchAssistLongPressAction(); } } } else { if (mAssistKeyLongPressed) { mAssistKeyLongPressed = false; } else { if (!keyguardOn) { launchAssistAction(); } } } return -1; } // Shortcuts are invoked through Search+key, so intercept those here // Any printing key that is chorded with Search should be consumed // even if no shortcut was invoked. This prevents text from being // inadvertently inserted when using a keyboard that has built-in macro // shortcut keys (that emit Search+x) and some of them are not registered. if (mSearchKeyShortcutPending) { final KeyCharacterMap kcm = event.getKeyCharacterMap(); if (kcm.isPrintingKey(keyCode)) { mConsumeSearchKeyUp = true; mSearchKeyShortcutPending = false; if (down && repeatCount == 0 && !keyguardOn) { Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState); if (shortcutIntent != null) { shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { mContext.startActivity(shortcutIntent); } catch (ActivityNotFoundException ex) { Slog.w(TAG, "Dropping shortcut key combination because " + "the activity to which it is registered was not found: " + "SEARCH+" + KeyEvent.keyCodeToString(keyCode), ex); } } else { Slog.i(TAG, "Dropping unregistered shortcut key combination: " + "SEARCH+" + KeyEvent.keyCodeToString(keyCode)); } } return -1; } } // Invoke shortcuts using Meta. if (down && repeatCount == 0 && !keyguardOn && (metaState & KeyEvent.META_META_ON) != 0) { final KeyCharacterMap kcm = event.getKeyCharacterMap(); if (kcm.isPrintingKey(keyCode)) { Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState & ~(KeyEvent.META_META_ON | KeyEvent.META_META_LEFT_ON | KeyEvent.META_META_RIGHT_ON)); if (shortcutIntent != null) { shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { mContext.startActivity(shortcutIntent); } catch (ActivityNotFoundException ex) { Slog.w(TAG, "Dropping shortcut key combination because " + "the activity to which it is registered was not found: " + "META+" + KeyEvent.keyCodeToString(keyCode), ex); } return -1; } } } // Handle application launch keys. if (down && repeatCount == 0 && !keyguardOn) { String category = sApplicationLaunchKeyCategories.get(keyCode); if (category != null) { Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, category); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { mContext.startActivity(intent); } catch (ActivityNotFoundException ex) { Slog.w(TAG, "Dropping application launch key because " + "the activity to which it is registered was not found: " + "keyCode=" + keyCode + ", category=" + category, ex); } return -1; } } // Display task switcher for ALT-TAB or Meta-TAB. if (down && repeatCount == 0 && keyCode == KeyEvent.KEYCODE_TAB) { if (mRecentAppsDialogHeldModifiers == 0 && !keyguardOn) { final int shiftlessModifiers = event.getModifiers() & ~KeyEvent.META_SHIFT_MASK; if (KeyEvent.metaStateHasModifiers(shiftlessModifiers, KeyEvent.META_ALT_ON) || KeyEvent.metaStateHasModifiers( shiftlessModifiers, KeyEvent.META_META_ON)) { mRecentAppsDialogHeldModifiers = shiftlessModifiers; showOrHideRecentAppsDialog(RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW); return -1; } } } else if (!down && mRecentAppsDialogHeldModifiers != 0 && (metaState & mRecentAppsDialogHeldModifiers) == 0) { mRecentAppsDialogHeldModifiers = 0; showOrHideRecentAppsDialog(keyguardOn ? RECENT_APPS_BEHAVIOR_DISMISS : RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH); } // Handle keyboard language switching. if (down && repeatCount == 0 && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH || (keyCode == KeyEvent.KEYCODE_SPACE && (metaState & KeyEvent.META_CTRL_MASK) != 0))) { int direction = (metaState & KeyEvent.META_SHIFT_MASK) != 0 ? -1 : 1; mWindowManagerFuncs.switchKeyboardLayout(event.getDeviceId(), direction); return -1; } if (mLanguageSwitchKeyPressed && !down && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH || keyCode == KeyEvent.KEYCODE_SPACE)) { mLanguageSwitchKeyPressed = false; return -1; } // Let the application handle the key. return 0; }
diff --git a/src/com/android/gallery3d/util/GalleryUtils.java b/src/com/android/gallery3d/util/GalleryUtils.java index 6a216cc7f..19b96923a 100644 --- a/src/com/android/gallery3d/util/GalleryUtils.java +++ b/src/com/android/gallery3d/util/GalleryUtils.java @@ -1,443 +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.gallery3d.util; import android.annotation.TargetApi; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.graphics.Color; import android.net.Uri; import android.os.ConditionVariable; import android.os.Environment; import android.os.StatFs; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.util.DisplayMetrics; import android.util.Log; import android.view.WindowManager; import com.android.gallery3d.R; import com.android.gallery3d.app.Gallery; import com.android.gallery3d.app.PackagesMonitor; import com.android.gallery3d.common.ApiHelper; import com.android.gallery3d.data.DataManager; import com.android.gallery3d.data.MediaItem; import com.android.gallery3d.ui.TiledScreenNail; import com.android.gallery3d.util.ThreadPool.CancelListener; import com.android.gallery3d.util.ThreadPool.JobContext; import java.io.File; import java.util.Arrays; import java.util.List; import java.util.Locale; public class GalleryUtils { private static final String TAG = "GalleryUtils"; private static final String MAPS_PACKAGE_NAME = "com.google.android.apps.maps"; private static final String MAPS_CLASS_NAME = "com.google.android.maps.MapsActivity"; private static final String CAMERA_LAUNCHER_NAME = "com.android.camera.CameraLauncher"; public static final String MIME_TYPE_IMAGE = "image/*"; public static final String MIME_TYPE_VIDEO = "video/*"; public static final String MIME_TYPE_PANORAMA360 = "application/vnd.google.panorama360+jpg"; public static final String MIME_TYPE_ALL = "*/*"; private static final String DIR_TYPE_IMAGE = "vnd.android.cursor.dir/image"; private static final String DIR_TYPE_VIDEO = "vnd.android.cursor.dir/video"; private static final String PREFIX_PHOTO_EDITOR_UPDATE = "editor-update-"; private static final String PREFIX_HAS_PHOTO_EDITOR = "has-editor-"; private static final String KEY_CAMERA_UPDATE = "camera-update"; private static final String KEY_HAS_CAMERA = "has-camera"; private static float sPixelDensity = -1f; private static boolean sCameraAvailableInitialized = false; private static boolean sCameraAvailable; public static void initialize(Context context) { DisplayMetrics metrics = new DisplayMetrics(); WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(metrics); sPixelDensity = metrics.density; Resources r = context.getResources(); TiledScreenNail.setPlaceholderColor(r.getColor( R.color.bitmap_screennail_placeholder)); initializeThumbnailSizes(metrics, r); } private static void initializeThumbnailSizes(DisplayMetrics metrics, Resources r) { int maxPixels = Math.max(metrics.heightPixels, metrics.widthPixels); // For screen-nails, we never need to completely fill the screen MediaItem.setThumbnailSizes(maxPixels / 2, maxPixels / 5); TiledScreenNail.setMaxSide(maxPixels / 2); } public static float[] intColorToFloatARGBArray(int from) { return new float[] { Color.alpha(from) / 255f, Color.red(from) / 255f, Color.green(from) / 255f, Color.blue(from) / 255f }; } public static float dpToPixel(float dp) { return sPixelDensity * dp; } public static int dpToPixel(int dp) { return Math.round(dpToPixel((float) dp)); } public static int meterToPixel(float meter) { // 1 meter = 39.37 inches, 1 inch = 160 dp. return Math.round(dpToPixel(meter * 39.37f * 160)); } public static byte[] getBytes(String in) { byte[] result = new byte[in.length() * 2]; int output = 0; for (char ch : in.toCharArray()) { result[output++] = (byte) (ch & 0xFF); result[output++] = (byte) (ch >> 8); } return result; } // Below are used the detect using database in the render thread. It only // works most of the time, but that's ok because it's for debugging only. private static volatile Thread sCurrentThread; private static volatile boolean sWarned; public static void setRenderThread() { sCurrentThread = Thread.currentThread(); } public static void assertNotInRenderThread() { if (!sWarned) { if (Thread.currentThread() == sCurrentThread) { sWarned = true; Log.w(TAG, new Throwable("Should not do this in render thread")); } } } private static final double RAD_PER_DEG = Math.PI / 180.0; private static final double EARTH_RADIUS_METERS = 6367000.0; public static double fastDistanceMeters(double latRad1, double lngRad1, double latRad2, double lngRad2) { if ((Math.abs(latRad1 - latRad2) > RAD_PER_DEG) || (Math.abs(lngRad1 - lngRad2) > RAD_PER_DEG)) { return accurateDistanceMeters(latRad1, lngRad1, latRad2, lngRad2); } // Approximate sin(x) = x. double sineLat = (latRad1 - latRad2); // Approximate sin(x) = x. double sineLng = (lngRad1 - lngRad2); // Approximate cos(lat1) * cos(lat2) using // cos((lat1 + lat2)/2) ^ 2 double cosTerms = Math.cos((latRad1 + latRad2) / 2.0); cosTerms = cosTerms * cosTerms; double trigTerm = sineLat * sineLat + cosTerms * sineLng * sineLng; trigTerm = Math.sqrt(trigTerm); // Approximate arcsin(x) = x return EARTH_RADIUS_METERS * trigTerm; } public static double accurateDistanceMeters(double lat1, double lng1, double lat2, double lng2) { double dlat = Math.sin(0.5 * (lat2 - lat1)); double dlng = Math.sin(0.5 * (lng2 - lng1)); double x = dlat * dlat + dlng * dlng * Math.cos(lat1) * Math.cos(lat2); return (2 * Math.atan2(Math.sqrt(x), Math.sqrt(Math.max(0.0, 1.0 - x)))) * EARTH_RADIUS_METERS; } public static final double toMile(double meter) { return meter / 1609; } // For debugging, it will block the caller for timeout millis. public static void fakeBusy(JobContext jc, int timeout) { final ConditionVariable cv = new ConditionVariable(); jc.setCancelListener(new CancelListener() { @Override public void onCancel() { cv.open(); } }); cv.block(timeout); jc.setCancelListener(null); } public static boolean isEditorAvailable(Context context, String mimeType) { int version = PackagesMonitor.getPackagesVersion(context); String updateKey = PREFIX_PHOTO_EDITOR_UPDATE + mimeType; String hasKey = PREFIX_HAS_PHOTO_EDITOR + mimeType; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (prefs.getInt(updateKey, 0) != version) { PackageManager packageManager = context.getPackageManager(); List<ResolveInfo> infos = packageManager.queryIntentActivities( new Intent(Intent.ACTION_EDIT).setType(mimeType), 0); prefs.edit().putInt(updateKey, version) .putBoolean(hasKey, !infos.isEmpty()) .commit(); } return prefs.getBoolean(hasKey, true); } public static boolean isAnyCameraAvailable(Context context) { int version = PackagesMonitor.getPackagesVersion(context); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (prefs.getInt(KEY_CAMERA_UPDATE, 0) != version) { PackageManager packageManager = context.getPackageManager(); List<ResolveInfo> infos = packageManager.queryIntentActivities( new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA), 0); prefs.edit().putInt(KEY_CAMERA_UPDATE, version) .putBoolean(KEY_HAS_CAMERA, !infos.isEmpty()) .commit(); } return prefs.getBoolean(KEY_HAS_CAMERA, true); } public static boolean isCameraAvailable(Context context) { if (sCameraAvailableInitialized) return sCameraAvailable; PackageManager pm = context.getPackageManager(); ComponentName name = new ComponentName(context, CAMERA_LAUNCHER_NAME); int state = pm.getComponentEnabledSetting(name); sCameraAvailableInitialized = true; sCameraAvailable = (state == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) || (state == PackageManager.COMPONENT_ENABLED_STATE_ENABLED); return sCameraAvailable; } public static void startCameraActivity(Context context) { Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA) .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } public static void startGalleryActivity(Context context) { Intent intent = new Intent(context, Gallery.class) .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } public static boolean isValidLocation(double latitude, double longitude) { // TODO: change || to && after we fix the default location issue return (latitude != MediaItem.INVALID_LATLNG || longitude != MediaItem.INVALID_LATLNG); } public static String formatLatitudeLongitude(String format, double latitude, double longitude) { // We need to specify the locale otherwise it may go wrong in some language // (e.g. Locale.FRENCH) return String.format(Locale.ENGLISH, format, latitude, longitude); } public static void showOnMap(Context context, double latitude, double longitude) { // We use isIntentResolved here, because startActivity could derive in ProxyLauncher // invocation, which makes an startActivity, and if the intent not exists we get a FC. // 1.- GMM with MapView // We don't use "geo:latitude,longitude" because it only centers // the MapView to the specified location, but we need a marker // for further operations (routing to/from). // The q=(lat, lng) syntax is suggested by geo-team. ComponentName gmmCompName = new ComponentName(MAPS_PACKAGE_NAME, MAPS_CLASS_NAME); String gmmUri = formatLatitudeLongitude("http://maps.google.com/maps?f=q&q=(%f,%f)", - 0.0d, 0.0d); + latitude, longitude); Intent gmmIntent = new Intent(); gmmIntent.setComponent(gmmCompName); gmmIntent.setData(Uri.parse(gmmUri)); gmmIntent.setAction(Intent.ACTION_VIEW); if (isIntentResolved(context, gmmIntent)) { context.startActivity(gmmIntent); return; } // 2.- Geolocation content provider Log.w(TAG, "GMM activity not found! Trying with geo scheme"); - String geoUri = formatLatitudeLongitude("geo:%f,%f", 0.0d, 0.0d); + String geoUri = formatLatitudeLongitude("geo:%f,%f", latitude, longitude); Intent geoIntent = new Intent(); geoIntent.setData(Uri.parse(geoUri)); geoIntent.setAction(Intent.ACTION_VIEW); if (isIntentResolved(context, geoIntent)) { context.startActivity(geoIntent); } // No maps. Why isGeolocationViewAvailable method not working? } public static boolean isGeolocationViewAvailable(Context context) { // 1.- GMM with MapView ComponentName gmmCompName = new ComponentName(MAPS_PACKAGE_NAME, MAPS_CLASS_NAME); String gmmUri = formatLatitudeLongitude("http://maps.google.com/maps?f=q&q=(%f,%f)", 0.0d, 0.0d); Intent gmmIntent = new Intent(); gmmIntent.setComponent(gmmCompName); gmmIntent.setData(Uri.parse(gmmUri)); gmmIntent.setAction(Intent.ACTION_VIEW); // 2.- Geolocation content provider String geoUri = formatLatitudeLongitude("geo:%f,%f", 0.0d, 0.0d); Intent geoIntent = new Intent(); geoIntent.setData(Uri.parse(geoUri)); geoIntent.setAction(Intent.ACTION_VIEW); // Should be one of: gmm or geo content provider return isIntentResolved(context, gmmIntent) || isIntentResolved(context, geoIntent); } private static boolean isIntentResolved(Context context, Intent intent) { final PackageManager pckMgr = context.getPackageManager(); List<ResolveInfo> infos = pckMgr.queryIntentActivities (intent, PackageManager.GET_RESOLVED_FILTER); return infos != null && infos.size() > 0; } public static void setViewPointMatrix( float matrix[], float x, float y, float z) { // The matrix is // -z, 0, x, 0 // 0, -z, y, 0 // 0, 0, 1, 0 // 0, 0, 1, -z Arrays.fill(matrix, 0, 16, 0); matrix[0] = matrix[5] = matrix[15] = -z; matrix[8] = x; matrix[9] = y; matrix[10] = matrix[11] = 1; } public static int getBucketId(String path) { return path.toLowerCase().hashCode(); } // Return the local path that matches the given bucketId. If no match is // found, return null public static String searchDirForPath(File dir, int bucketId) { File[] files = dir.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { String path = file.getAbsolutePath(); if (GalleryUtils.getBucketId(path) == bucketId) { return path; } else { path = searchDirForPath(file, bucketId); if (path != null) return path; } } } } return null; } // Returns a (localized) string for the given duration (in seconds). public static String formatDuration(final Context context, int duration) { int h = duration / 3600; int m = (duration - h * 3600) / 60; int s = duration - (h * 3600 + m * 60); String durationValue; if (h == 0) { durationValue = String.format(context.getString(R.string.details_ms), m, s); } else { durationValue = String.format(context.getString(R.string.details_hms), h, m, s); } return durationValue; } @TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB) public static int determineTypeBits(Context context, Intent intent) { int typeBits = 0; String type = intent.resolveType(context); if (MIME_TYPE_ALL.equals(type)) { typeBits = DataManager.INCLUDE_ALL; } else if (MIME_TYPE_IMAGE.equals(type) || DIR_TYPE_IMAGE.equals(type)) { typeBits = DataManager.INCLUDE_IMAGE; } else if (MIME_TYPE_VIDEO.equals(type) || DIR_TYPE_VIDEO.equals(type)) { typeBits = DataManager.INCLUDE_VIDEO; } else { typeBits = DataManager.INCLUDE_ALL; } if (ApiHelper.HAS_INTENT_EXTRA_LOCAL_ONLY) { if (intent.getBooleanExtra(Intent.EXTRA_LOCAL_ONLY, false)) { typeBits |= DataManager.INCLUDE_LOCAL_ONLY; } } return typeBits; } public static int getSelectionModePrompt(int typeBits) { if ((typeBits & DataManager.INCLUDE_VIDEO) != 0) { return (typeBits & DataManager.INCLUDE_IMAGE) == 0 ? R.string.select_video : R.string.select_item; } return R.string.select_image; } public static boolean hasSpaceForSize(long size) { String state = Environment.getExternalStorageState(); if (!Environment.MEDIA_MOUNTED.equals(state)) { return false; } String path = Environment.getExternalStorageDirectory().getPath(); try { StatFs stat = new StatFs(path); return stat.getAvailableBlocks() * (long) stat.getBlockSize() > size; } catch (Exception e) { Log.i(TAG, "Fail to access external storage", e); } return false; } public static boolean isPanorama(MediaItem item) { if (item == null) return false; int w = item.getWidth(); int h = item.getHeight(); return (h > 0 && w / h >= 2); } }
false
true
public static void showOnMap(Context context, double latitude, double longitude) { // We use isIntentResolved here, because startActivity could derive in ProxyLauncher // invocation, which makes an startActivity, and if the intent not exists we get a FC. // 1.- GMM with MapView // We don't use "geo:latitude,longitude" because it only centers // the MapView to the specified location, but we need a marker // for further operations (routing to/from). // The q=(lat, lng) syntax is suggested by geo-team. ComponentName gmmCompName = new ComponentName(MAPS_PACKAGE_NAME, MAPS_CLASS_NAME); String gmmUri = formatLatitudeLongitude("http://maps.google.com/maps?f=q&q=(%f,%f)", 0.0d, 0.0d); Intent gmmIntent = new Intent(); gmmIntent.setComponent(gmmCompName); gmmIntent.setData(Uri.parse(gmmUri)); gmmIntent.setAction(Intent.ACTION_VIEW); if (isIntentResolved(context, gmmIntent)) { context.startActivity(gmmIntent); return; } // 2.- Geolocation content provider Log.w(TAG, "GMM activity not found! Trying with geo scheme"); String geoUri = formatLatitudeLongitude("geo:%f,%f", 0.0d, 0.0d); Intent geoIntent = new Intent(); geoIntent.setData(Uri.parse(geoUri)); geoIntent.setAction(Intent.ACTION_VIEW); if (isIntentResolved(context, geoIntent)) { context.startActivity(geoIntent); } // No maps. Why isGeolocationViewAvailable method not working? }
public static void showOnMap(Context context, double latitude, double longitude) { // We use isIntentResolved here, because startActivity could derive in ProxyLauncher // invocation, which makes an startActivity, and if the intent not exists we get a FC. // 1.- GMM with MapView // We don't use "geo:latitude,longitude" because it only centers // the MapView to the specified location, but we need a marker // for further operations (routing to/from). // The q=(lat, lng) syntax is suggested by geo-team. ComponentName gmmCompName = new ComponentName(MAPS_PACKAGE_NAME, MAPS_CLASS_NAME); String gmmUri = formatLatitudeLongitude("http://maps.google.com/maps?f=q&q=(%f,%f)", latitude, longitude); Intent gmmIntent = new Intent(); gmmIntent.setComponent(gmmCompName); gmmIntent.setData(Uri.parse(gmmUri)); gmmIntent.setAction(Intent.ACTION_VIEW); if (isIntentResolved(context, gmmIntent)) { context.startActivity(gmmIntent); return; } // 2.- Geolocation content provider Log.w(TAG, "GMM activity not found! Trying with geo scheme"); String geoUri = formatLatitudeLongitude("geo:%f,%f", latitude, longitude); Intent geoIntent = new Intent(); geoIntent.setData(Uri.parse(geoUri)); geoIntent.setAction(Intent.ACTION_VIEW); if (isIntentResolved(context, geoIntent)) { context.startActivity(geoIntent); } // No maps. Why isGeolocationViewAvailable method not working? }
diff --git a/CopProject/Cop/src/main/java/pro/kornev/kcar/cop/UsbDevicesActivity.java b/CopProject/Cop/src/main/java/pro/kornev/kcar/cop/UsbDevicesActivity.java index f16057d..46d7507 100644 --- a/CopProject/Cop/src/main/java/pro/kornev/kcar/cop/UsbDevicesActivity.java +++ b/CopProject/Cop/src/main/java/pro/kornev/kcar/cop/UsbDevicesActivity.java @@ -1,48 +1,49 @@ package pro.kornev.kcar.cop; import android.content.Context; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbManager; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.HashMap; import java.util.Map; public class UsbDevicesActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.usb_devices_activity); refresh(); } public void refreshButtonClick(View v) { refresh(); } public void devicesListClick(View v) { } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.usb_devices, menu); return true; } private void refresh() { UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE); Map<String, UsbDevice> usbList = manager.getDeviceList(); if (usbList==null || usbList.isEmpty()) return; ListView devicesList = (ListView)findViewById(R.id.uaDevicesList); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.abc_action_menu_item_layout, (String[])usbList.keySet().toArray()); + devicesList.setAdapter(adapter); } }
true
true
private void refresh() { UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE); Map<String, UsbDevice> usbList = manager.getDeviceList(); if (usbList==null || usbList.isEmpty()) return; ListView devicesList = (ListView)findViewById(R.id.uaDevicesList); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.abc_action_menu_item_layout, (String[])usbList.keySet().toArray()); }
private void refresh() { UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE); Map<String, UsbDevice> usbList = manager.getDeviceList(); if (usbList==null || usbList.isEmpty()) return; ListView devicesList = (ListView)findViewById(R.id.uaDevicesList); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.abc_action_menu_item_layout, (String[])usbList.keySet().toArray()); devicesList.setAdapter(adapter); }
diff --git a/DNA.java b/DNA.java index 4f29885..9c8d6b1 100644 --- a/DNA.java +++ b/DNA.java @@ -1,81 +1,81 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; // intended to check consistency public class DNA { Client client; BlockingQueue<String> source; static enum Command { UP, DOWN, LEFT, RIGHT, QUIT }; static Map<String, Command> commands; DNA(Client client) { this.client = client; this.source = this.client.addListener(); this.client.write("dnalab;"); } public boolean handleCommand(String data) { Command cmd = commands.get(data); if (cmd == null) { return false; } handleCommand(cmd); return true; } public boolean closed() { return (this.source == null); } private void handleCommand(Command cmd) { switch (cmd) { case LEFT: this.client.write("se;"); this.client.write("ga;"); break; case RIGHT: this.client.write("a;"); this.client.write("ba;"); break; case UP: this.client.write("la;"); this.client.write("pr;"); break; case DOWN: this.client.write("ty;"); this.client.write("ma;"); break; case QUIT: + this.client.write("quit;"); this.source = null; this.client = null; - this.client.write("quit;"); return; } try { while (this.source.poll(500, TimeUnit.MILLISECONDS) != null) { // will handle result here } } catch (InterruptedException e) { throw new RuntimeException(e); } } static { commands = new HashMap<String, Command>(); commands.put("l;", Command.LEFT); commands.put("r;", Command.RIGHT); commands.put("u;", Command.UP); commands.put("d;", Command.DOWN); commands.put("quit;", Command.QUIT); commands.put("q;", Command.QUIT); } }
false
true
private void handleCommand(Command cmd) { switch (cmd) { case LEFT: this.client.write("se;"); this.client.write("ga;"); break; case RIGHT: this.client.write("a;"); this.client.write("ba;"); break; case UP: this.client.write("la;"); this.client.write("pr;"); break; case DOWN: this.client.write("ty;"); this.client.write("ma;"); break; case QUIT: this.source = null; this.client = null; this.client.write("quit;"); return; } try { while (this.source.poll(500, TimeUnit.MILLISECONDS) != null) { // will handle result here } } catch (InterruptedException e) { throw new RuntimeException(e); } }
private void handleCommand(Command cmd) { switch (cmd) { case LEFT: this.client.write("se;"); this.client.write("ga;"); break; case RIGHT: this.client.write("a;"); this.client.write("ba;"); break; case UP: this.client.write("la;"); this.client.write("pr;"); break; case DOWN: this.client.write("ty;"); this.client.write("ma;"); break; case QUIT: this.client.write("quit;"); this.source = null; this.client = null; return; } try { while (this.source.poll(500, TimeUnit.MILLISECONDS) != null) { // will handle result here } } catch (InterruptedException e) { throw new RuntimeException(e); } }
diff --git a/biz.aQute.resolve/src/biz/aQute/resolve/internal/BndrunResolveContext.java b/biz.aQute.resolve/src/biz/aQute/resolve/internal/BndrunResolveContext.java index c41d625e6..cd54e8841 100644 --- a/biz.aQute.resolve/src/biz/aQute/resolve/internal/BndrunResolveContext.java +++ b/biz.aQute.resolve/src/biz/aQute/resolve/internal/BndrunResolveContext.java @@ -1,671 +1,671 @@ package biz.aQute.resolve.internal; import static org.osgi.framework.namespace.BundleNamespace.BUNDLE_NAMESPACE; import static org.osgi.framework.namespace.PackageNamespace.PACKAGE_NAMESPACE; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.Version; import org.osgi.framework.namespace.BundleNamespace; import org.osgi.framework.namespace.IdentityNamespace; import org.osgi.framework.namespace.PackageNamespace; import org.osgi.namespace.contract.ContractNamespace; import org.osgi.resource.Capability; import org.osgi.resource.Namespace; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; import org.osgi.resource.Wiring; import org.osgi.service.log.LogService; import org.osgi.service.repository.Repository; import org.osgi.service.resolver.HostedCapability; import org.osgi.service.resolver.ResolveContext; import aQute.bnd.build.model.BndEditModel; import aQute.bnd.build.model.EE; import aQute.bnd.build.model.clauses.ExportedPackage; import aQute.bnd.deployer.repository.MapToDictionaryAdapter; import aQute.bnd.header.Attrs; import aQute.bnd.header.Parameters; import aQute.bnd.osgi.Constants; import aQute.bnd.osgi.Processor; import aQute.bnd.osgi.resource.CapReqBuilder; import aQute.bnd.osgi.resource.Filters; import aQute.bnd.osgi.resource.ResourceBuilder; import aQute.bnd.service.Registry; import aQute.bnd.service.resolve.hook.ResolverHook; import aQute.libg.filters.AndFilter; import aQute.libg.filters.Filter; import aQute.libg.filters.LiteralFilter; import aQute.libg.filters.SimpleFilter; public class BndrunResolveContext extends ResolveContext { private static final String CONTRACT_OSGI_FRAMEWORK = "OSGiFramework"; private static final String IDENTITY_INITIAL_RESOURCE = "<<INITIAL>>"; public static final String RUN_EFFECTIVE_INSTRUCTION = "-resolve.effective"; public static final String PROP_RESOLVE_PREFERENCES = "-resolve.preferences"; private final List<Repository> repos = new LinkedList<Repository>(); private final ConcurrentMap<Resource,Integer> resourcePriorities = new ConcurrentHashMap<Resource,Integer>(); private final Map<Requirement,List<Capability>> mandatoryRequirements = new HashMap<Requirement,List<Capability>>(); private final Map<Requirement,List<Capability>> optionalRequirements = new HashMap<Requirement,List<Capability>>(); private final Map<CacheKey,List<Capability>> providerCache = new HashMap<CacheKey,List<Capability>>(); private final Comparator<Capability> capabilityComparator = new CapabilityComparator(); private final BndEditModel runModel; private final Registry registry; private final LogService log; private boolean initialised = false; private Resource frameworkResource = null; private Version frameworkResourceVersion = null; private FrameworkResourceRepository frameworkResourceRepo; private Resource inputRequirementsResource = null; private EE ee; private Set<String> effectiveSet; private List<ExportedPackage> sysPkgsExtra; private Parameters sysCapsExtraParams; private Parameters resolvePrefs; public BndrunResolveContext(BndEditModel runModel, Registry registry, LogService log) { this.runModel = runModel; this.registry = registry; this.log = log; } protected synchronized void init() { if (initialised) return; loadEE(); loadSystemPackagesExtra(); loadSystemCapabilitiesExtra(); loadRepositories(); loadEffectiveSet(); findFramework(); constructInputRequirements(); loadPreferences(); initialised = true; } private void loadEE() { EE tmp = runModel.getEE(); ee = (tmp != null) ? tmp : EE.JavaSE_1_6; } private void loadSystemPackagesExtra() { sysPkgsExtra = runModel.getSystemPackages(); } private void loadSystemCapabilitiesExtra() { String header = (String) runModel.genericGet(Constants.RUNSYSTEMCAPABILITIES); if (header != null) { Processor processor = new Processor(); try { processor.setProperty(Constants.RUNSYSTEMCAPABILITIES, header); String processedHeader = processor.getProperty(Constants.RUNSYSTEMCAPABILITIES); sysCapsExtraParams = new Parameters(processedHeader); } finally { processor.close(); } } else { sysCapsExtraParams = null; } } private void loadRepositories() { // Get all of the repositories from the plugin registry List<Repository> allRepos = registry.getPlugins(Repository.class); // Reorder/filter if specified by the run model List<String> repoNames = runModel.getRunRepos(); if (repoNames == null) { // No filter, use all repos.addAll(allRepos); } else { // Map the repository names... Map<String,Repository> repoNameMap = new HashMap<String,Repository>(allRepos.size()); for (Repository repo : allRepos) repoNameMap.put(repo.toString(), repo); // Create the result list for (String repoName : repoNames) { Repository repo = repoNameMap.get(repoName); if (repo != null) repos.add(repo); } } } private void loadEffectiveSet() { String effective = (String) runModel.genericGet(RUN_EFFECTIVE_INSTRUCTION); if (effective == null) effectiveSet = null; else { effectiveSet = new HashSet<String>(); for (Entry<String,Attrs> entry : new Parameters(effective).entrySet()) effectiveSet.add(entry.getKey()); } } private void findFramework() { String header = runModel.getRunFw(); if (header == null) return; // Get the identity and version of the requested JAR Parameters params = new Parameters(header); if (params.size() > 1) throw new IllegalArgumentException("Cannot specify more than one OSGi Framework."); Entry<String,Attrs> entry = params.entrySet().iterator().next(); String identity = entry.getKey(); String versionStr = entry.getValue().get("version"); // Construct a filter & requirement to find matches Filter filter = new SimpleFilter(IdentityNamespace.IDENTITY_NAMESPACE, identity); if (versionStr != null) filter = new AndFilter().addChild(filter).addChild(new LiteralFilter(Filters.fromVersionRange(versionStr))); Requirement frameworkReq = new CapReqBuilder(IdentityNamespace.IDENTITY_NAMESPACE).addDirective(Namespace.REQUIREMENT_FILTER_DIRECTIVE, filter.toString()).buildSyntheticRequirement(); // Iterate over repos looking for matches for (Repository repo : repos) { Map<Requirement,Collection<Capability>> providers = repo.findProviders(Collections.singletonList(frameworkReq)); Collection<Capability> frameworkCaps = providers.get(frameworkReq); if (frameworkCaps != null) { for (Capability frameworkCap : frameworkCaps) { if (findFrameworkContractCapability(frameworkCap.getResource()) != null) { Version foundVersion = toVersion(frameworkCap.getAttributes().get(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE)); if (foundVersion != null) { if (frameworkResourceVersion == null || (foundVersion.compareTo(frameworkResourceVersion) > 0)) { frameworkResource = frameworkCap.getResource(); frameworkResourceVersion = foundVersion; frameworkResourceRepo = new FrameworkResourceRepository(frameworkResource, ee, sysPkgsExtra, sysCapsExtraParams); } } } } } } } private void constructInputRequirements() { List<Requirement> requires = runModel.getRunRequires(); if (requires == null || requires.isEmpty()) { inputRequirementsResource = null; } else { ResourceBuilder resBuilder = new ResourceBuilder(); CapReqBuilder identity = new CapReqBuilder(IdentityNamespace.IDENTITY_NAMESPACE).addAttribute(IdentityNamespace.IDENTITY_NAMESPACE, IDENTITY_INITIAL_RESOURCE); resBuilder.addCapability(identity); for (Requirement req : requires) { resBuilder.addRequirement(req); } inputRequirementsResource = resBuilder.build(); } } private void loadPreferences() { String prefsStr = (String) runModel.genericGet(PROP_RESOLVE_PREFERENCES); if (prefsStr == null) prefsStr = ""; resolvePrefs = new Parameters(prefsStr); } public static boolean isInputRequirementResource(Resource resource) { Capability id = resource.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE).get(0); return IDENTITY_INITIAL_RESOURCE.equals(id.getAttributes().get(IdentityNamespace.IDENTITY_NAMESPACE)); } private static Version toVersion(Object object) throws IllegalArgumentException { if (object == null) return null; if (object instanceof Version) return (Version) object; if (object instanceof String) return Version.parseVersion((String) object); throw new IllegalArgumentException(MessageFormat.format("Cannot convert type {0} to Version.", object.getClass().getName())); } private static Capability findFrameworkContractCapability(Resource resource) { List<Capability> contractCaps = resource.getCapabilities(ContractNamespace.CONTRACT_NAMESPACE); if (contractCaps != null) for (Capability cap : contractCaps) { if (CONTRACT_OSGI_FRAMEWORK.equals(cap.getAttributes().get(ContractNamespace.CONTRACT_NAMESPACE))) return cap; } return null; } public void addRepository(Repository repo) { repos.add(repo); } @Override public Collection<Resource> getMandatoryResources() { init(); if (frameworkResource == null) throw new IllegalStateException(MessageFormat.format("Could not find OSGi framework matching {0}.", runModel.getRunFw())); List<Resource> resources = new ArrayList<Resource>(); resources.add(frameworkResource); if (inputRequirementsResource != null) resources.add(inputRequirementsResource); return resources; } @Override public List<Capability> findProviders(Requirement requirement) { init(); List<Capability> result; CacheKey cacheKey = getCacheKey(requirement); List<Capability> cached = providerCache.get(cacheKey); if (cached != null) { - result = cached; + result = new ArrayList<Capability>(cached); } else { // First stage: framework and self-capabilities. This should never be reordered by preferences or resolver // hooks LinkedHashSet<Capability> firstStageResult = new LinkedHashSet<Capability>(); // The selected OSGi framework always has the first chance to provide the capabilities if (frameworkResourceRepo != null) { Map<Requirement,Collection<Capability>> providers = frameworkResourceRepo.findProviders(Collections.singleton(requirement)); Collection<Capability> capabilities = providers.get(requirement); if (capabilities != null && !capabilities.isEmpty()) { firstStageResult.addAll(capabilities); } } // Next find out if the requirement is satisfied by a capability on the same resource Resource resource = requirement.getResource(); if (resource != null) { List<Capability> selfCaps = resource.getCapabilities(requirement.getNamespace()); if (selfCaps != null) { for (Capability selfCap : selfCaps) { if (matches(requirement, selfCap)) firstStageResult.add(selfCap); } } } // Second stage results: repository contents; may be reordered. LinkedHashSet<Capability> secondStageResult = new LinkedHashSet<Capability>(); // Iterate over the repos int order = 0; ArrayList<Capability> repoCapabilities = new ArrayList<Capability>(); for (Repository repo : repos) { repoCapabilities.clear(); Map<Requirement,Collection<Capability>> providers = repo.findProviders(Collections.singleton(requirement)); Collection<Capability> capabilities = providers.get(requirement); if (capabilities != null && !capabilities.isEmpty()) { repoCapabilities.ensureCapacity(capabilities.size()); for (Capability capability : capabilities) { if (isPermitted(capability.getResource())) { repoCapabilities.add(capability); setResourcePriority(order, capability.getResource()); } } if (!repoCapabilities.isEmpty()) { Collections.sort(repoCapabilities, capabilityComparator); secondStageResult.addAll(repoCapabilities); } } order++; } // Convert second-stage results to a list and post-process ArrayList<Capability> secondStageList = new ArrayList<Capability>(secondStageResult); // Post-processing second stage results postProcessProviders(requirement, secondStageList); // Prepare final result if (Namespace.RESOLUTION_OPTIONAL.equals(requirement.getDirectives().get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE))) { // Only return the framework and self-capabilities when asked for an optional requirement result = new ArrayList<Capability>(firstStageResult); // If the framework couldn't provide the requirement then save the list of potential providers // to the side, in order to work out the optional resources later. if (result.isEmpty()) optionalRequirements.put(requirement, secondStageList); Collections.sort(result, capabilityComparator); } else { // Concatenate both stages, eliminating duplicates between the two firstStageResult.addAll(secondStageList); result = new ArrayList<Capability>(firstStageResult); // Record as a mandatory requirement mandatoryRequirements.put(requirement, result); } providerCache.put(cacheKey, result); } return result; } private boolean matches(Requirement requirement, Capability selfCap) { boolean match = false; try { String filterStr = requirement.getDirectives().get(Namespace.REQUIREMENT_FILTER_DIRECTIVE); org.osgi.framework.Filter filter = filterStr != null ? org.osgi.framework.FrameworkUtil.createFilter(filterStr) : null; if (filter == null) match = true; else match = filter.match(new MapToDictionaryAdapter(selfCap.getAttributes())); } catch (InvalidSyntaxException e) { log.log(LogService.LOG_ERROR, "Invalid filter directive on requirement: " + requirement, e); } return match; } private static CacheKey getCacheKey(Requirement requirement) { return new CacheKey(requirement.getNamespace(), requirement.getDirectives().get("filter"), requirement.getAttributes()); } protected void postProcessProviders(Requirement requirement, List<Capability> candidates) { if (candidates.size() == 0) return; // Process the resolve preferences if (resolvePrefs != null && !resolvePrefs.isEmpty()) { List<Capability> insertions = new LinkedList<Capability>(); for (Iterator<Capability> iterator = candidates.iterator(); iterator.hasNext();) { Capability cap = iterator.next(); if (resolvePrefs.containsKey(getResourceIdentity(cap.getResource()))) { iterator.remove(); insertions.add(cap); } } if (!insertions.isEmpty()) candidates.addAll(0, insertions); } // Call resolver hooks for (ResolverHook resolverHook : registry.getPlugins(ResolverHook.class)) { resolverHook.filterMatches(requirement, candidates); } } private static String getResourceIdentity(Resource resource) throws IllegalArgumentException { List<Capability> identities = resource.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE); if (identities == null || identities.size() != 1) throw new IllegalArgumentException("Resource element does not contain exactly one identity capability"); Object idObj = identities.get(0).getAttributes().get(IdentityNamespace.IDENTITY_NAMESPACE); if (idObj == null || !(idObj instanceof String)) throw new IllegalArgumentException("Resource identity capability does not have a string identity attribute"); return (String) idObj; } Resource getFrameworkResource() { return frameworkResource; } static Version getVersion(Capability cap, String attr) { Object versionatt = cap.getAttributes().get(attr); if (versionatt instanceof Version) return (Version) versionatt; else if (versionatt instanceof String) return Version.parseVersion((String) versionatt); else return Version.emptyVersion; } private void setResourcePriority(int priority, Resource resource) { resourcePriorities.putIfAbsent(resource, priority); } private boolean isPermitted(Resource resource) { // OSGi frameworks cannot be selected as ordinary resources Capability fwkCap = findFrameworkContractCapability(resource); if (fwkCap != null) { return false; } // Remove osgi.core and any ee JAR List<Capability> idCaps = resource.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE); if (idCaps == null || idCaps.isEmpty()) { log.log(LogService.LOG_ERROR, "Resource is missing an identity capability (osgi.identity)."); return false; } if (idCaps.size() > 1) { log.log(LogService.LOG_ERROR, "Resource has more than one identity capability (osgi.identity)."); return false; } String identity = (String) idCaps.get(0).getAttributes().get(IdentityNamespace.IDENTITY_NAMESPACE); if (identity == null) { log.log(LogService.LOG_ERROR, "Resource is missing an identity capability (osgi.identity)."); return false; } if ("osgi.core".equals(identity)) return false; if (identity.startsWith("ee.")) return false; return true; } @Override public int insertHostedCapability(List<Capability> caps, HostedCapability hc) { Integer prioObj = resourcePriorities.get(hc.getResource()); int priority = prioObj != null ? prioObj.intValue() : Integer.MAX_VALUE; for (int i = 0; i < caps.size(); i++) { Capability c = caps.get(i); Integer otherPrioObj = resourcePriorities.get(c.getResource()); int otherPriority = otherPrioObj != null ? otherPrioObj.intValue() : 0; if (otherPriority > priority) { caps.add(i, hc); return i; } } caps.add(hc); return caps.size() - 1; } @Override public boolean isEffective(Requirement requirement) { init(); String effective = requirement.getDirectives().get(Namespace.REQUIREMENT_EFFECTIVE_DIRECTIVE); if (effective == null || Namespace.EFFECTIVE_RESOLVE.equals(effective)) return true; if (effectiveSet != null && effectiveSet.contains(effective)) return true; return false; } @Override public Map<Resource,Wiring> getWirings() { return Collections.emptyMap(); } public boolean isInputRequirementsResource(Resource resource) { return resource == inputRequirementsResource; } public boolean isFrameworkResource(Resource resource) { return resource == frameworkResource; } public Map<Requirement,List<Capability>> getMandatoryRequirements() { return mandatoryRequirements; } public Map<Requirement,List<Capability>> getOptionalRequirements() { return optionalRequirements; } private static class CacheKey { final String namespace; final String filter; final Map<String,Object> attributes; final int hashcode; CacheKey(String namespace, String filter, Map<String,Object> attributes) { this.namespace = namespace; this.filter = filter; this.attributes = attributes; this.hashcode = calculateHashCode(namespace, filter, attributes); } private static int calculateHashCode(String namespace, String filter, Map<String,Object> attributes) { final int prime = 31; int result = 1; result = prime * result + ((attributes == null) ? 0 : attributes.hashCode()); result = prime * result + ((filter == null) ? 0 : filter.hashCode()); result = prime * result + ((namespace == null) ? 0 : namespace.hashCode()); return result; } @Override public int hashCode() { return hashcode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CacheKey other = (CacheKey) obj; if (attributes == null) { if (other.attributes != null) return false; } else if (!attributes.equals(other.attributes)) return false; if (filter == null) { if (other.filter != null) return false; } else if (!filter.equals(other.filter)) return false; if (namespace == null) { if (other.namespace != null) return false; } else if (!namespace.equals(other.namespace)) return false; return true; } } private class CapabilityComparator implements Comparator<Capability> { public CapabilityComparator() {} public int compare(Capability o1, Capability o2) { Resource res1 = o1.getResource(); Resource res2 = o2.getResource(); // 1. Framework bundle if (res1 == getFrameworkResource()) return -1; if (res2 == getFrameworkResource()) return +1; // 2. Wired Map<Resource,Wiring> wirings = getWirings(); Wiring w1 = wirings.get(res1); Wiring w2 = wirings.get(res2); if (w1 != null && w2 == null) return -1; if (w1 == null && w2 != null) return +1; // 3. Input requirements if (isInputRequirementResource(res1)) { if (!isInputRequirementResource(res2)) return -1; } if (isInputRequirementResource(res2)) { if (!isInputRequirementResource(res1)) return +1; } // 4. Higher package version String ns1 = o1.getNamespace(); String ns2 = o2.getNamespace(); if (PACKAGE_NAMESPACE.equals(ns1) && PACKAGE_NAMESPACE.equals(ns2)) { Version v1 = getVersion(o1, PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE); Version v2 = getVersion(o2, PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE); if (!v1.equals(v2)) return v2.compareTo(v1); } // 5. Higher resource version if (BUNDLE_NAMESPACE.equals(ns1) && BUNDLE_NAMESPACE.equals(ns2)) { Version v1 = getVersion(o1, BundleNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE); Version v2 = getVersion(o2, BundleNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE); if (!v1.equals(v2)) return v2.compareTo(v1); } else if (IdentityNamespace.IDENTITY_NAMESPACE.equals(ns1) && IdentityNamespace.IDENTITY_NAMESPACE.equals(ns2)) { Version v1 = getVersion(o1, IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE); Version v2 = getVersion(o2, IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE); if (!v1.equals(v2)) return v2.compareTo(v1); } // 6. Same package version, higher bundle version if (PACKAGE_NAMESPACE.equals(ns1) && PACKAGE_NAMESPACE.equals(ns2)) { String bsn1 = (String) o1.getAttributes().get(Constants.BUNDLE_SYMBOLIC_NAME_ATTRIBUTE); String bsn2 = (String) o2.getAttributes().get(Constants.BUNDLE_SYMBOLIC_NAME_ATTRIBUTE); if (bsn1 != null && bsn1.equals(bsn2)) { Version v1 = getVersion(o1, BundleNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE); Version v2 = getVersion(o2, BundleNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE); if (!v1.equals(v2)) return v2.compareTo(v1); } } // 7. The resource with most capabilities return res2.getCapabilities(null).size() - res1.getCapabilities(null).size(); } } }
true
true
public List<Capability> findProviders(Requirement requirement) { init(); List<Capability> result; CacheKey cacheKey = getCacheKey(requirement); List<Capability> cached = providerCache.get(cacheKey); if (cached != null) { result = cached; } else { // First stage: framework and self-capabilities. This should never be reordered by preferences or resolver // hooks LinkedHashSet<Capability> firstStageResult = new LinkedHashSet<Capability>(); // The selected OSGi framework always has the first chance to provide the capabilities if (frameworkResourceRepo != null) { Map<Requirement,Collection<Capability>> providers = frameworkResourceRepo.findProviders(Collections.singleton(requirement)); Collection<Capability> capabilities = providers.get(requirement); if (capabilities != null && !capabilities.isEmpty()) { firstStageResult.addAll(capabilities); } } // Next find out if the requirement is satisfied by a capability on the same resource Resource resource = requirement.getResource(); if (resource != null) { List<Capability> selfCaps = resource.getCapabilities(requirement.getNamespace()); if (selfCaps != null) { for (Capability selfCap : selfCaps) { if (matches(requirement, selfCap)) firstStageResult.add(selfCap); } } } // Second stage results: repository contents; may be reordered. LinkedHashSet<Capability> secondStageResult = new LinkedHashSet<Capability>(); // Iterate over the repos int order = 0; ArrayList<Capability> repoCapabilities = new ArrayList<Capability>(); for (Repository repo : repos) { repoCapabilities.clear(); Map<Requirement,Collection<Capability>> providers = repo.findProviders(Collections.singleton(requirement)); Collection<Capability> capabilities = providers.get(requirement); if (capabilities != null && !capabilities.isEmpty()) { repoCapabilities.ensureCapacity(capabilities.size()); for (Capability capability : capabilities) { if (isPermitted(capability.getResource())) { repoCapabilities.add(capability); setResourcePriority(order, capability.getResource()); } } if (!repoCapabilities.isEmpty()) { Collections.sort(repoCapabilities, capabilityComparator); secondStageResult.addAll(repoCapabilities); } } order++; } // Convert second-stage results to a list and post-process ArrayList<Capability> secondStageList = new ArrayList<Capability>(secondStageResult); // Post-processing second stage results postProcessProviders(requirement, secondStageList); // Prepare final result if (Namespace.RESOLUTION_OPTIONAL.equals(requirement.getDirectives().get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE))) { // Only return the framework and self-capabilities when asked for an optional requirement result = new ArrayList<Capability>(firstStageResult); // If the framework couldn't provide the requirement then save the list of potential providers // to the side, in order to work out the optional resources later. if (result.isEmpty()) optionalRequirements.put(requirement, secondStageList); Collections.sort(result, capabilityComparator); } else { // Concatenate both stages, eliminating duplicates between the two firstStageResult.addAll(secondStageList); result = new ArrayList<Capability>(firstStageResult); // Record as a mandatory requirement mandatoryRequirements.put(requirement, result); } providerCache.put(cacheKey, result); } return result; }
public List<Capability> findProviders(Requirement requirement) { init(); List<Capability> result; CacheKey cacheKey = getCacheKey(requirement); List<Capability> cached = providerCache.get(cacheKey); if (cached != null) { result = new ArrayList<Capability>(cached); } else { // First stage: framework and self-capabilities. This should never be reordered by preferences or resolver // hooks LinkedHashSet<Capability> firstStageResult = new LinkedHashSet<Capability>(); // The selected OSGi framework always has the first chance to provide the capabilities if (frameworkResourceRepo != null) { Map<Requirement,Collection<Capability>> providers = frameworkResourceRepo.findProviders(Collections.singleton(requirement)); Collection<Capability> capabilities = providers.get(requirement); if (capabilities != null && !capabilities.isEmpty()) { firstStageResult.addAll(capabilities); } } // Next find out if the requirement is satisfied by a capability on the same resource Resource resource = requirement.getResource(); if (resource != null) { List<Capability> selfCaps = resource.getCapabilities(requirement.getNamespace()); if (selfCaps != null) { for (Capability selfCap : selfCaps) { if (matches(requirement, selfCap)) firstStageResult.add(selfCap); } } } // Second stage results: repository contents; may be reordered. LinkedHashSet<Capability> secondStageResult = new LinkedHashSet<Capability>(); // Iterate over the repos int order = 0; ArrayList<Capability> repoCapabilities = new ArrayList<Capability>(); for (Repository repo : repos) { repoCapabilities.clear(); Map<Requirement,Collection<Capability>> providers = repo.findProviders(Collections.singleton(requirement)); Collection<Capability> capabilities = providers.get(requirement); if (capabilities != null && !capabilities.isEmpty()) { repoCapabilities.ensureCapacity(capabilities.size()); for (Capability capability : capabilities) { if (isPermitted(capability.getResource())) { repoCapabilities.add(capability); setResourcePriority(order, capability.getResource()); } } if (!repoCapabilities.isEmpty()) { Collections.sort(repoCapabilities, capabilityComparator); secondStageResult.addAll(repoCapabilities); } } order++; } // Convert second-stage results to a list and post-process ArrayList<Capability> secondStageList = new ArrayList<Capability>(secondStageResult); // Post-processing second stage results postProcessProviders(requirement, secondStageList); // Prepare final result if (Namespace.RESOLUTION_OPTIONAL.equals(requirement.getDirectives().get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE))) { // Only return the framework and self-capabilities when asked for an optional requirement result = new ArrayList<Capability>(firstStageResult); // If the framework couldn't provide the requirement then save the list of potential providers // to the side, in order to work out the optional resources later. if (result.isEmpty()) optionalRequirements.put(requirement, secondStageList); Collections.sort(result, capabilityComparator); } else { // Concatenate both stages, eliminating duplicates between the two firstStageResult.addAll(secondStageList); result = new ArrayList<Capability>(firstStageResult); // Record as a mandatory requirement mandatoryRequirements.put(requirement, result); } providerCache.put(cacheKey, result); } return result; }
diff --git a/Awful.apk/src/main/java/com/ferg/awfulapp/ForumsIndexActivity.java b/Awful.apk/src/main/java/com/ferg/awfulapp/ForumsIndexActivity.java index 4ed7cd96..86831413 100644 --- a/Awful.apk/src/main/java/com/ferg/awfulapp/ForumsIndexActivity.java +++ b/Awful.apk/src/main/java/com/ferg/awfulapp/ForumsIndexActivity.java @@ -1,923 +1,923 @@ /** * ***************************************************************************** * Copyright (c) 2011, Scott Ferguson * All rights reserved. * <p/> * 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 software nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * <p/> * THIS SOFTWARE IS PROVIDED BY SCOTT FERGUSON ''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 SCOTT FERGUSON BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ***************************************************************************** */ package com.ferg.awfulapp; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.content.res.TypedArray; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.GestureDetector; import android.view.Gravity; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.androidquery.AQuery; import com.ferg.awfulapp.constants.Constants; import com.ferg.awfulapp.dialog.LogOutDialog; import com.ferg.awfulapp.preferences.AwfulPreferences; import com.ferg.awfulapp.preferences.SettingsActivity; import com.ferg.awfulapp.provider.ColorProvider; import com.ferg.awfulapp.provider.StringProvider; import com.ferg.awfulapp.thread.AwfulURL; import com.ferg.awfulapp.util.AwfulUtils; import com.ferg.awfulapp.widget.ToggleViewPager; import java.lang.reflect.Method; //import com.ToxicBakery.viewpager.transforms.*; public class ForumsIndexActivity extends AwfulActivity { protected static final String TAG = "ForumsIndexActivity"; private static final int DEFAULT_HIDE_DELAY = 300; private static final int MESSAGE_HIDING = 0; private static final int MESSAGE_VISIBLE_CHANGE_IN_PROGRESS = 1; private ForumsIndexFragment mIndexFragment = null; private ForumDisplayFragment mForumFragment = null; private ThreadDisplayFragment mThreadFragment = null; private boolean skipLoad = false; private boolean isTablet; private AwfulURL url = new AwfulURL(); private Handler mHandler = new Handler(); private ToggleViewPager mViewPager; private View mDecorView; private ForumPagerAdapter pagerAdapter; private Toolbar mToolbar; private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mDrawerToggle; private int mNavForumId = Constants.USERCP_ID; private int mNavThreadId = 0; private int mForumId = Constants.USERCP_ID; private int mForumPage = 1; private int mThreadId = 0; private int mThreadPage = 1; private boolean mPrimeRecreate = false; private GestureDetector mImmersionGestureDetector = null; private boolean mIgnoreFling; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); isTablet = AwfulUtils.isTablet(this); int initialPage; if (savedInstanceState != null) { mForumId = savedInstanceState.getInt(Constants.FORUM_ID, mForumId); mForumPage = savedInstanceState.getInt(Constants.FORUM_PAGE, mForumPage); setThreadPage(savedInstanceState.getInt(Constants.THREAD_PAGE, 1)); setThreadId(savedInstanceState.getInt(Constants.THREAD_ID, 0)); initialPage = savedInstanceState.getInt("viewPage", -1); } else { initialPage = parseNewIntent(getIntent()); } setContentView(R.layout.forum_index_activity); mViewPager = (ToggleViewPager) findViewById(R.id.forum_index_pager); mViewPager.setSwipeEnabled(!mPrefs.lockScrolling); if (!isTablet && !mPrefs.transformer.equals("Disabled")) { mViewPager.setPageTransformer(true, AwfulUtils.getViewPagerTransformer()); } mViewPager.setOffscreenPageLimit(2); if (isTablet) { mViewPager.setPageMargin(1); //TODO what color should it use here? mViewPager.setPageMarginDrawable(new ColorDrawable(ColorProvider.getActionbarColor())); } pagerAdapter = new ForumPagerAdapter(getSupportFragmentManager()); mViewPager.setAdapter(pagerAdapter); mViewPager.setOnPageChangeListener(pagerAdapter); if (initialPage >= 0) { mViewPager.setCurrentItem(initialPage); } mToolbar = (Toolbar) findViewById(R.id.awful_toolbar); setSupportActionBar(mToolbar); setNavigationDrawer(); setActionBar(); checkIntentExtras(); setupImmersion(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @SuppressLint("NewApi") private void setupImmersion() { if (AwfulUtils.isKitKat() && mPrefs.immersionMode) { mDecorView = getWindow().getDecorView(); mDecorView.setOnSystemUiVisibilityChangeListener( new View.OnSystemUiVisibilityChangeListener() { @Override public void onSystemUiVisibilityChange(int flags) { boolean visible = (flags & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0; if (visible) { // Add some delay so the act of swiping to bring system UI into view doesn't turn it back off mHideHandler.removeMessages(MESSAGE_VISIBLE_CHANGE_IN_PROGRESS); mHideHandler.sendEmptyMessageDelayed(MESSAGE_VISIBLE_CHANGE_IN_PROGRESS, 800); mIgnoreFling = true; } } }); mImmersionGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (mIgnoreFling) return true; boolean visible = (mDecorView.getSystemUiVisibility() & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0; if (visible) { hideSystemUi(); } return true; } }); showSystemUi(); } } public void setNavigationDrawer() { final Activity self = this; RelativeLayout navIndexLayout = (RelativeLayout) findViewById(R.id.sidebar_index); if (null != navIndexLayout) { TextView navIndex = (TextView) navIndexLayout.findViewById(R.id.drawer_text); navIndexLayout.setVisibility(View.VISIBLE); navIndex.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { displayForumIndex(); mDrawerLayout.closeDrawers(); } }); navIndex.setText("The SA Forums"); } RelativeLayout navForumLayout = (RelativeLayout) findViewById(R.id.sidebar_forum); if (null != navForumLayout) { TextView navForum = (TextView) navForumLayout.findViewById(R.id.drawer_text); if (mNavForumId != 0) { navForumLayout.setVisibility(View.VISIBLE); navForum.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { displayForum(mNavForumId, 1); mDrawerLayout.closeDrawers(); } }); navForum.setText(StringProvider.getForumName(this, mNavForumId)); } else { navForumLayout.setVisibility(View.GONE); } } RelativeLayout navThreadLayout = (RelativeLayout) findViewById(R.id.sidebar_thread); if (null != navThreadLayout) { if (mNavThreadId != 0) { TextView navThread = (TextView) navThreadLayout.findViewById(R.id.drawer_text); Log.d(TAG, "NavThread, Navforum: " + mNavThreadId + " " + mNavForumId); - navThread.setVisibility(View.VISIBLE); + navThreadLayout.setVisibility(View.VISIBLE); navThread.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { displayThread(mNavThreadId, mThreadPage, mNavForumId, mForumPage, false); mDrawerLayout.closeDrawers(); } }); navThread.setText(StringProvider.getThreadName(this, mNavThreadId)); } else { navThreadLayout.setVisibility(View.GONE); } } mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ mToolbar, /* nav drawer icon to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description */ R.string.drawer_close /* "close drawer" description */ ); mDrawerLayout.setDrawerListener(mDrawerToggle); TextView username = (TextView) findViewById(R.id.sidebar_username); if (null != username) { username.setText(mPrefs.username); } ImageView avatar = (ImageView) findViewById(R.id.sidebar_avatar); if (null != avatar) { AQuery aq = new AQuery(this); if (null != mPrefs.userTitle) { if (!("".equals(mPrefs.userTitle))) { aq.id(R.id.sidebar_avatar).image(mPrefs.userTitle); } else { aq.id(R.id.sidebar_avatar).image(R.drawable.icon); } } } RelativeLayout logoutLayout = (RelativeLayout) findViewById(R.id.sidebar_logout); if (null != logoutLayout) { TextView logout = (TextView) logoutLayout.findViewById(R.id.drawer_text); logout.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mDrawerLayout.closeDrawers(); new LogOutDialog(self).show(); } }); logout.setText(getResources().getText(R.string.logout)); logoutLayout.setVisibility(View.VISIBLE); ImageView logoutImage = (ImageView) logoutLayout.findViewById(R.id.drawer_icon); int[] attrs = { R.attr.iconMenuLogoutDark }; TypedArray ta = logoutImage.getContext().getTheme().obtainStyledAttributes(attrs); logoutImage.setImageDrawable(ta.getDrawable(0)); logoutImage.setVisibility(View.VISIBLE); } RelativeLayout messagesLayout = (RelativeLayout) findViewById(R.id.sidebar_pm); if (null != messagesLayout) { TextView messages = (TextView) messagesLayout.findViewById(R.id.drawer_text); messages.setEnabled(mPrefs.hasPlatinum); messagesLayout.setVisibility(mPrefs.hasPlatinum ? View.VISIBLE : View.GONE); messages.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mDrawerLayout.closeDrawers(); startActivity(new Intent().setClass(self, PrivateMessageActivity.class)); } }); messages.setText(getResources().getText(R.string.private_message)); ImageView messagesImage = (ImageView) messagesLayout.findViewById(R.id.drawer_icon); int[] attrs = { R.attr.iconMenuMailDark }; TypedArray ta = messagesImage.getContext().getTheme().obtainStyledAttributes(attrs); messagesImage.setImageDrawable(ta.getDrawable(0)); messagesImage.setVisibility(View.VISIBLE); } RelativeLayout bookmarksLayout = (RelativeLayout) findViewById(R.id.sidebar_bookmarks); if (null != bookmarksLayout) { TextView bookmarks = (TextView) bookmarksLayout.findViewById(R.id.drawer_text); bookmarks.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mDrawerLayout.closeDrawers(); startActivity(new Intent().setClass(self, ForumsIndexActivity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) .putExtra(Constants.FORUM_ID, Constants.USERCP_ID) .putExtra(Constants.FORUM_PAGE, 1)); } }); bookmarks.setText(getResources().getText(R.string.user_cp)); bookmarksLayout.setVisibility((Constants.USERCP_ID == mNavForumId ? View.GONE : View.VISIBLE)); ImageView bookmarksImage = (ImageView) bookmarksLayout.findViewById(R.id.drawer_icon); int[] attrs = { R.attr.iconMenuBookmarkDark }; TypedArray ta = bookmarksImage.getContext().getTheme().obtainStyledAttributes(attrs); bookmarksImage.setImageDrawable(ta.getDrawable(0)); bookmarksImage.setVisibility(View.VISIBLE); } RelativeLayout settingsLayout = (RelativeLayout) findViewById(R.id.sidebar_settings); if (null != settingsLayout) { TextView settings = (TextView) settingsLayout.findViewById(R.id.drawer_text); settings.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mDrawerLayout.closeDrawers(); startActivity(new Intent().setClass(self, SettingsActivity.class)); } }); settings.setText(getResources().getText(R.string.settings)); settingsLayout.setVisibility(View.VISIBLE); ImageView settingsImage = (ImageView) settingsLayout.findViewById(R.id.drawer_icon); int[] attrs = { R.attr.iconMenuSettingsDark }; TypedArray ta = settingsImage.getContext().getTheme().obtainStyledAttributes(attrs); settingsImage.setImageDrawable(ta.getDrawable(0)); settingsImage.setVisibility(View.VISIBLE); } mDrawerToggle.syncState(); } @Override @SuppressLint("NewApi") public boolean dispatchTouchEvent(MotionEvent e) { if (AwfulUtils.isKitKat() && mPrefs.immersionMode) { super.dispatchTouchEvent(e); return mImmersionGestureDetector.onTouchEvent(e); } return super.dispatchTouchEvent(e); } private final Handler mHideHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == MESSAGE_HIDING) { hideSystemUi(); } else if (msg.what == MESSAGE_VISIBLE_CHANGE_IN_PROGRESS) { mIgnoreFling = false; } } }; /** * Hide the system UI. * @param delayMillis - delay in milliseconds before hiding. */ public void delayedHide(int delayMillis) { mHideHandler.removeMessages(MESSAGE_HIDING); mHideHandler.sendEmptyMessageDelayed(MESSAGE_HIDING, delayMillis); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (AwfulUtils.isKitKat() && mPrefs.immersionMode) { // When the window loses focus (e.g. the action overflow is shown), // cancel any pending hide action. When the window gains focus, // hide the system UI. if (hasFocus) { delayedHide(DEFAULT_HIDE_DELAY); } else { mHideHandler.removeMessages(0); } } } @SuppressLint("NewApi") private void showSystemUi() { if (AwfulUtils.isKitKat() && mPrefs.immersionMode) { mDecorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); } } @SuppressLint("NewApi") private void hideSystemUi() { if (AwfulUtils.isKitKat() && mPrefs.immersionMode) { mDecorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); if (DEBUG) Log.e(TAG, "onNewIntent"); setIntent(intent); int initialPage = parseNewIntent(intent); if (mViewPager != null && pagerAdapter != null && pagerAdapter.getCount() >= initialPage && initialPage >= 0) { mViewPager.setCurrentItem(initialPage); } if (mForumFragment != null) { mForumFragment.openForum(mForumId, mForumPage); } if (mThreadFragment != null) { if (url.isThread() || url.isPost()) { mThreadFragment.openThread(url); } else if (intent.getIntExtra(Constants.THREAD_ID, 0) > 0) { mThreadFragment.openThread(mThreadId, mThreadPage); } } } private int parseNewIntent(Intent intent) { int initialPage = -1; mForumId = getIntent().getIntExtra(Constants.FORUM_ID, mForumId); mForumPage = getIntent().getIntExtra(Constants.FORUM_PAGE, mForumPage); setThreadPage(getIntent().getIntExtra(Constants.THREAD_PAGE, mThreadPage)); setThreadId(getIntent().getIntExtra(Constants.THREAD_ID, mThreadId)); if (mForumId == 2) {//workaround for old userCP ID, ugh. the old id still appears if someone created a bookmark launch shortcut prior to b23 mForumId = Constants.USERCP_ID;//should never have used 2 as a hard-coded forum-id, what a horror. } if (getIntent().getData() != null && getIntent().getData().getScheme().equals("http")) { url = AwfulURL.parse(getIntent().getDataString()); switch (url.getType()) { case FORUM: mForumId = (int) url.getId(); mForumPage = (int) url.getPage(); break; case THREAD: if (!url.isRedirect()) { setThreadPage((int) url.getPage()); setThreadId((int) url.getId()); } break; case POST: break; case INDEX: displayForumIndex(); break; default: } } if (intent.getIntExtra(Constants.FORUM_ID, 0) > 1 || url.isForum()) { initialPage = isTablet ? 0 : 1; } else { skipLoad = !isTablet; } if (intent.getIntExtra(Constants.THREAD_ID, 0) > 0 || url.isRedirect() || url.isThread()) { initialPage = 2; } return initialPage; } @Override protected void onResume() { super.onResume(); if (mPrimeRecreate) { mPrimeRecreate = false; Intent intent = getIntent(); finish(); startActivity(intent); } switch (mPrefs.alertIDShown + 1) { case 1: new AlertDialog.Builder(this). setTitle(getString(R.string.alert_title_1)) .setMessage(getString(R.string.alert_message_1)) .setPositiveButton(getString(R.string.alert_ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setNegativeButton(getString(R.string.alert_settings), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); startActivity(new Intent().setClass(ForumsIndexActivity.this, SettingsActivity.class)); } }) .show(); mPrefs.setIntegerPreference("alert_id_shown", 1); break; } } @Override protected void onPause() { super.onPause(); if (mForumFragment != null) { mForumId = mForumFragment.getForumId(); mForumPage = mForumFragment.getPage(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(Constants.FORUM_ID, mForumId); outState.putInt(Constants.FORUM_PAGE, mForumPage); outState.putInt(Constants.THREAD_ID, mThreadId); outState.putInt(Constants.THREAD_PAGE, mThreadPage); if (mViewPager != null) { outState.putInt("viewPage", mViewPager.getCurrentItem()); } } private void checkIntentExtras() { if (getIntent().hasExtra(Constants.SHORTCUT)) { if (getIntent().getBooleanExtra(Constants.SHORTCUT, false)) { displayForum(Constants.USERCP_ID, 1); } } } public int getThreadId() { return mThreadId; } public int getThreadPage() { return mThreadPage; } public void setThreadId(int threadId) { int oldThreadId = mThreadId; mThreadId = threadId; mNavThreadId = threadId; if ((oldThreadId < 1 || threadId < 1) && threadId != oldThreadId && pagerAdapter != null) { pagerAdapter.notifyDataSetChanged();//notify pager adapter so it'll show/hide the thread view } } public void setThreadPage(int page) { mThreadPage = page; } public class ForumPagerAdapter extends FragmentStatePagerAdapter implements ViewPager.OnPageChangeListener { public ForumPagerAdapter(FragmentManager fm) { super(fm); } private AwfulFragment visible; @Override public void onPageSelected(int arg0) { if (DEBUG) Log.i(TAG, "onPageSelected: " + arg0); if (visible != null) { visible.onPageHidden(); } AwfulFragment apf = (AwfulFragment) getItem(arg0); if (apf != null) { setActionbarTitle(apf.getTitle(), null); apf.onPageVisible(); setProgress(apf.getProgressPercent()); } visible = apf; } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageScrollStateChanged(int state) { } @Override public Fragment getItem(int ix) { switch (ix) { case 0: if (mIndexFragment == null) { mIndexFragment = new ForumsIndexFragment(); } return mIndexFragment; case 1: if (mForumFragment == null) { mForumFragment = new ForumDisplayFragment(mForumId, mForumPage, skipLoad); } return mForumFragment; case 2: if (mThreadFragment == null) { mThreadFragment = new ThreadDisplayFragment(); } return mThreadFragment; } Log.e(TAG, "ERROR: asked for too many fragments in ForumPagerAdapter.getItem"); return null; } @Override public Object instantiateItem(ViewGroup container, int position) { Object frag = super.instantiateItem(container, position); if (frag instanceof ForumsIndexFragment) { mIndexFragment = (ForumsIndexFragment) frag; } if (frag instanceof ForumDisplayFragment) { mForumFragment = (ForumDisplayFragment) frag; } if (frag instanceof ThreadDisplayFragment) { mThreadFragment = (ThreadDisplayFragment) frag; } return frag; } @Override public int getCount() { if (getThreadId() < 1) { return 2; } return 3; } @Override public int getItemPosition(Object object) { if (mIndexFragment != null && mIndexFragment.equals(object)) { return 0; } if (mForumFragment != null && mForumFragment.equals(object)) { return 1; } if (mThreadFragment != null && mThreadFragment.equals(object)) { return 2; } return super.getItemPosition(object); } @Override public float getPageWidth(int position) { if (isTablet) { switch (position) { case 0: return 0.4f; case 1: return 0.6f; case 2: return 1f; } } return super.getPageWidth(position); } } @Override public void setActionbarTitle(String aTitle, Object requestor) { if (requestor != null && mViewPager != null) { //This will only honor the request if the requestor is the currently active view. if (requestor instanceof AwfulFragment && isFragmentVisible((AwfulFragment) requestor)) { super.setActionbarTitle(aTitle, requestor); } else { if (DEBUG) Log.i(TAG, "Failed setActionbarTitle: " + aTitle + " - " + requestor.toString()); } } else { super.setActionbarTitle(aTitle, requestor); } } @Override public void onBackPressed() { if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) { mDrawerLayout.closeDrawers(); } else { if (mViewPager != null && mViewPager.getCurrentItem() > 0) { if (!((AwfulFragment) pagerAdapter.getItem(mViewPager.getCurrentItem())).onBackPressed()) { mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1); } } else { super.onBackPressed(); } } } @Override public void displayForum(int id, int page) { Log.d(TAG, "displayForum " + id); mForumId = id; mForumPage = page; setNavigationDrawer(); if (mForumFragment != null) { mForumFragment.openForum(id, page); if (mViewPager != null) { mViewPager.setCurrentItem(pagerAdapter.getItemPosition(mForumFragment)); } } } @Override public boolean isFragmentVisible(AwfulFragment awfulFragment) { if (awfulFragment != null && mViewPager != null && pagerAdapter != null) { if (isTablet) { int itemPos = pagerAdapter.getItemPosition(awfulFragment); return itemPos == mViewPager.getCurrentItem() || itemPos == mViewPager.getCurrentItem() + 1; } else { return pagerAdapter.getItemPosition(awfulFragment) == mViewPager.getCurrentItem(); } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case android.R.id.home: // if(mViewPager != null && mViewPager.getCurrentItem() > 0){ // if(mViewPager.getCurrentItem() == 2 && mThreadFragment != null && mThreadFragment.getParentForumId() > 0){ // displayForum(mThreadFragment.getParentForumId(), 1); // }else{ // mViewPager.setCurrentItem(mViewPager.getCurrentItem()-1); // } // return true; // } // break; // default: // break; // } if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } @Override public boolean onMenuOpened(int featureId, Menu menu) { if(featureId == Window.FEATURE_ACTION_BAR && menu != null){ if(menu.getClass().getSimpleName().equals("MenuBuilder")){ try{ Method m = menu.getClass().getDeclaredMethod( "setOptionalIconsVisible", Boolean.TYPE); m.setAccessible(true); m.invoke(menu, true); } catch(NoSuchMethodException e){ Log.e(TAG, "onMenuOpened", e); } catch(Exception e){ throw new RuntimeException(e); } } } return super.onMenuOpened(featureId, menu); } @Override public void displayThread(int id, int page, int forumId, int forumPg, boolean forceReload) { Log.d(TAG, "displayThread " + id + " " + forumId); if (mViewPager != null) { if (mThreadFragment != null) { if (!forceReload && getThreadId() == id && getThreadPage() == page) { setThreadId(mNavThreadId); setNavForumId(mThreadFragment.getParentForumId()); setNavigationDrawer(); } else { mThreadFragment.openThread(id, page); mViewPager.getAdapter().notifyDataSetChanged(); } } else { setThreadPage(page); setThreadId(id); } mViewPager.setCurrentItem(pagerAdapter.getItemPosition(mThreadFragment)); } else { super.displayThread(id, page, forumId, forumPg, forceReload); } } @Override public void displayUserCP() { displayForum(Constants.USERCP_ID, 1); } @Override public void displayForumIndex() { if (mViewPager != null) { mViewPager.setCurrentItem(0); } } @Override protected void onActivityResult(int request, int result, Intent intent) { if (DEBUG) Log.e(TAG, "onActivityResult: " + request + " result: " + result); super.onActivityResult(request, result, intent); if (request == Constants.LOGIN_ACTIVITY_REQUEST && result == Activity.RESULT_OK) { mHandler.postDelayed(new Runnable() { @Override public void run() { if (mIndexFragment != null) { mIndexFragment.refresh(); } } }, 1000); } } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (mPrefs.volumeScroll && pagerAdapter.getItem(mViewPager.getCurrentItem()) != null && ((AwfulFragment) pagerAdapter.getItem(mViewPager.getCurrentItem())).volumeScroll(event)) { return true; } return super.dispatchKeyEvent(event); } @Override public void onPreferenceChange(AwfulPreferences prefs,String key) { super.onPreferenceChange(prefs, key); if (prefs.immersionMode && mDecorView == null) { setupImmersion(); } if (mViewPager != null) { mViewPager.setSwipeEnabled(!prefs.lockScrolling); } if (mDrawerLayout != null) { ImageView avatar = (ImageView) findViewById(R.id.sidebar_avatar); if (null != avatar) { AQuery aq = new AQuery(this); if (null != mPrefs.userTitle) { aq.id(R.id.sidebar_avatar).image(mPrefs.userTitle); } else { aq.id(R.id.sidebar_avatar).image(R.drawable.icon); } } } mViewPager.setPageTransformer(true, AwfulUtils.getViewPagerTransformer()); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); boolean oldTab = isTablet; isTablet = AwfulUtils.isTablet(this); if (oldTab != isTablet && mViewPager != null) { if (isTablet) { mViewPager.setPageMargin(1); //TODO what color should it use here? mViewPager.setPageMarginDrawable(new ColorDrawable(ColorProvider.getActionbarColor())); } else { mViewPager.setPageMargin(0); } mViewPager.setAdapter(pagerAdapter); } mDrawerToggle.onConfigurationChanged(newConfig); } public void setNavForumId(int forumId) { this.mNavForumId = forumId; } public void setNavThreadId(int threadId) { this.mNavThreadId = threadId; } @Override public void afterThemeChange() { this.mPrimeRecreate = true; } public void preventSwipe() { this.mViewPager.setSwipeEnabled(false); } public void reenableSwipe() { this.mViewPager.setSwipeEnabled(true); } }
true
true
public void setNavigationDrawer() { final Activity self = this; RelativeLayout navIndexLayout = (RelativeLayout) findViewById(R.id.sidebar_index); if (null != navIndexLayout) { TextView navIndex = (TextView) navIndexLayout.findViewById(R.id.drawer_text); navIndexLayout.setVisibility(View.VISIBLE); navIndex.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { displayForumIndex(); mDrawerLayout.closeDrawers(); } }); navIndex.setText("The SA Forums"); } RelativeLayout navForumLayout = (RelativeLayout) findViewById(R.id.sidebar_forum); if (null != navForumLayout) { TextView navForum = (TextView) navForumLayout.findViewById(R.id.drawer_text); if (mNavForumId != 0) { navForumLayout.setVisibility(View.VISIBLE); navForum.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { displayForum(mNavForumId, 1); mDrawerLayout.closeDrawers(); } }); navForum.setText(StringProvider.getForumName(this, mNavForumId)); } else { navForumLayout.setVisibility(View.GONE); } } RelativeLayout navThreadLayout = (RelativeLayout) findViewById(R.id.sidebar_thread); if (null != navThreadLayout) { if (mNavThreadId != 0) { TextView navThread = (TextView) navThreadLayout.findViewById(R.id.drawer_text); Log.d(TAG, "NavThread, Navforum: " + mNavThreadId + " " + mNavForumId); navThread.setVisibility(View.VISIBLE); navThread.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { displayThread(mNavThreadId, mThreadPage, mNavForumId, mForumPage, false); mDrawerLayout.closeDrawers(); } }); navThread.setText(StringProvider.getThreadName(this, mNavThreadId)); } else { navThreadLayout.setVisibility(View.GONE); } } mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ mToolbar, /* nav drawer icon to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description */ R.string.drawer_close /* "close drawer" description */ ); mDrawerLayout.setDrawerListener(mDrawerToggle); TextView username = (TextView) findViewById(R.id.sidebar_username); if (null != username) { username.setText(mPrefs.username); } ImageView avatar = (ImageView) findViewById(R.id.sidebar_avatar); if (null != avatar) { AQuery aq = new AQuery(this); if (null != mPrefs.userTitle) { if (!("".equals(mPrefs.userTitle))) { aq.id(R.id.sidebar_avatar).image(mPrefs.userTitle); } else { aq.id(R.id.sidebar_avatar).image(R.drawable.icon); } } } RelativeLayout logoutLayout = (RelativeLayout) findViewById(R.id.sidebar_logout); if (null != logoutLayout) { TextView logout = (TextView) logoutLayout.findViewById(R.id.drawer_text); logout.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mDrawerLayout.closeDrawers(); new LogOutDialog(self).show(); } }); logout.setText(getResources().getText(R.string.logout)); logoutLayout.setVisibility(View.VISIBLE); ImageView logoutImage = (ImageView) logoutLayout.findViewById(R.id.drawer_icon); int[] attrs = { R.attr.iconMenuLogoutDark }; TypedArray ta = logoutImage.getContext().getTheme().obtainStyledAttributes(attrs); logoutImage.setImageDrawable(ta.getDrawable(0)); logoutImage.setVisibility(View.VISIBLE); } RelativeLayout messagesLayout = (RelativeLayout) findViewById(R.id.sidebar_pm); if (null != messagesLayout) { TextView messages = (TextView) messagesLayout.findViewById(R.id.drawer_text); messages.setEnabled(mPrefs.hasPlatinum); messagesLayout.setVisibility(mPrefs.hasPlatinum ? View.VISIBLE : View.GONE); messages.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mDrawerLayout.closeDrawers(); startActivity(new Intent().setClass(self, PrivateMessageActivity.class)); } }); messages.setText(getResources().getText(R.string.private_message)); ImageView messagesImage = (ImageView) messagesLayout.findViewById(R.id.drawer_icon); int[] attrs = { R.attr.iconMenuMailDark }; TypedArray ta = messagesImage.getContext().getTheme().obtainStyledAttributes(attrs); messagesImage.setImageDrawable(ta.getDrawable(0)); messagesImage.setVisibility(View.VISIBLE); } RelativeLayout bookmarksLayout = (RelativeLayout) findViewById(R.id.sidebar_bookmarks); if (null != bookmarksLayout) { TextView bookmarks = (TextView) bookmarksLayout.findViewById(R.id.drawer_text); bookmarks.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mDrawerLayout.closeDrawers(); startActivity(new Intent().setClass(self, ForumsIndexActivity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) .putExtra(Constants.FORUM_ID, Constants.USERCP_ID) .putExtra(Constants.FORUM_PAGE, 1)); } }); bookmarks.setText(getResources().getText(R.string.user_cp)); bookmarksLayout.setVisibility((Constants.USERCP_ID == mNavForumId ? View.GONE : View.VISIBLE)); ImageView bookmarksImage = (ImageView) bookmarksLayout.findViewById(R.id.drawer_icon); int[] attrs = { R.attr.iconMenuBookmarkDark }; TypedArray ta = bookmarksImage.getContext().getTheme().obtainStyledAttributes(attrs); bookmarksImage.setImageDrawable(ta.getDrawable(0)); bookmarksImage.setVisibility(View.VISIBLE); } RelativeLayout settingsLayout = (RelativeLayout) findViewById(R.id.sidebar_settings); if (null != settingsLayout) { TextView settings = (TextView) settingsLayout.findViewById(R.id.drawer_text); settings.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mDrawerLayout.closeDrawers(); startActivity(new Intent().setClass(self, SettingsActivity.class)); } }); settings.setText(getResources().getText(R.string.settings)); settingsLayout.setVisibility(View.VISIBLE); ImageView settingsImage = (ImageView) settingsLayout.findViewById(R.id.drawer_icon); int[] attrs = { R.attr.iconMenuSettingsDark }; TypedArray ta = settingsImage.getContext().getTheme().obtainStyledAttributes(attrs); settingsImage.setImageDrawable(ta.getDrawable(0)); settingsImage.setVisibility(View.VISIBLE); } mDrawerToggle.syncState(); }
public void setNavigationDrawer() { final Activity self = this; RelativeLayout navIndexLayout = (RelativeLayout) findViewById(R.id.sidebar_index); if (null != navIndexLayout) { TextView navIndex = (TextView) navIndexLayout.findViewById(R.id.drawer_text); navIndexLayout.setVisibility(View.VISIBLE); navIndex.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { displayForumIndex(); mDrawerLayout.closeDrawers(); } }); navIndex.setText("The SA Forums"); } RelativeLayout navForumLayout = (RelativeLayout) findViewById(R.id.sidebar_forum); if (null != navForumLayout) { TextView navForum = (TextView) navForumLayout.findViewById(R.id.drawer_text); if (mNavForumId != 0) { navForumLayout.setVisibility(View.VISIBLE); navForum.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { displayForum(mNavForumId, 1); mDrawerLayout.closeDrawers(); } }); navForum.setText(StringProvider.getForumName(this, mNavForumId)); } else { navForumLayout.setVisibility(View.GONE); } } RelativeLayout navThreadLayout = (RelativeLayout) findViewById(R.id.sidebar_thread); if (null != navThreadLayout) { if (mNavThreadId != 0) { TextView navThread = (TextView) navThreadLayout.findViewById(R.id.drawer_text); Log.d(TAG, "NavThread, Navforum: " + mNavThreadId + " " + mNavForumId); navThreadLayout.setVisibility(View.VISIBLE); navThread.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { displayThread(mNavThreadId, mThreadPage, mNavForumId, mForumPage, false); mDrawerLayout.closeDrawers(); } }); navThread.setText(StringProvider.getThreadName(this, mNavThreadId)); } else { navThreadLayout.setVisibility(View.GONE); } } mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ mToolbar, /* nav drawer icon to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description */ R.string.drawer_close /* "close drawer" description */ ); mDrawerLayout.setDrawerListener(mDrawerToggle); TextView username = (TextView) findViewById(R.id.sidebar_username); if (null != username) { username.setText(mPrefs.username); } ImageView avatar = (ImageView) findViewById(R.id.sidebar_avatar); if (null != avatar) { AQuery aq = new AQuery(this); if (null != mPrefs.userTitle) { if (!("".equals(mPrefs.userTitle))) { aq.id(R.id.sidebar_avatar).image(mPrefs.userTitle); } else { aq.id(R.id.sidebar_avatar).image(R.drawable.icon); } } } RelativeLayout logoutLayout = (RelativeLayout) findViewById(R.id.sidebar_logout); if (null != logoutLayout) { TextView logout = (TextView) logoutLayout.findViewById(R.id.drawer_text); logout.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mDrawerLayout.closeDrawers(); new LogOutDialog(self).show(); } }); logout.setText(getResources().getText(R.string.logout)); logoutLayout.setVisibility(View.VISIBLE); ImageView logoutImage = (ImageView) logoutLayout.findViewById(R.id.drawer_icon); int[] attrs = { R.attr.iconMenuLogoutDark }; TypedArray ta = logoutImage.getContext().getTheme().obtainStyledAttributes(attrs); logoutImage.setImageDrawable(ta.getDrawable(0)); logoutImage.setVisibility(View.VISIBLE); } RelativeLayout messagesLayout = (RelativeLayout) findViewById(R.id.sidebar_pm); if (null != messagesLayout) { TextView messages = (TextView) messagesLayout.findViewById(R.id.drawer_text); messages.setEnabled(mPrefs.hasPlatinum); messagesLayout.setVisibility(mPrefs.hasPlatinum ? View.VISIBLE : View.GONE); messages.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mDrawerLayout.closeDrawers(); startActivity(new Intent().setClass(self, PrivateMessageActivity.class)); } }); messages.setText(getResources().getText(R.string.private_message)); ImageView messagesImage = (ImageView) messagesLayout.findViewById(R.id.drawer_icon); int[] attrs = { R.attr.iconMenuMailDark }; TypedArray ta = messagesImage.getContext().getTheme().obtainStyledAttributes(attrs); messagesImage.setImageDrawable(ta.getDrawable(0)); messagesImage.setVisibility(View.VISIBLE); } RelativeLayout bookmarksLayout = (RelativeLayout) findViewById(R.id.sidebar_bookmarks); if (null != bookmarksLayout) { TextView bookmarks = (TextView) bookmarksLayout.findViewById(R.id.drawer_text); bookmarks.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mDrawerLayout.closeDrawers(); startActivity(new Intent().setClass(self, ForumsIndexActivity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) .putExtra(Constants.FORUM_ID, Constants.USERCP_ID) .putExtra(Constants.FORUM_PAGE, 1)); } }); bookmarks.setText(getResources().getText(R.string.user_cp)); bookmarksLayout.setVisibility((Constants.USERCP_ID == mNavForumId ? View.GONE : View.VISIBLE)); ImageView bookmarksImage = (ImageView) bookmarksLayout.findViewById(R.id.drawer_icon); int[] attrs = { R.attr.iconMenuBookmarkDark }; TypedArray ta = bookmarksImage.getContext().getTheme().obtainStyledAttributes(attrs); bookmarksImage.setImageDrawable(ta.getDrawable(0)); bookmarksImage.setVisibility(View.VISIBLE); } RelativeLayout settingsLayout = (RelativeLayout) findViewById(R.id.sidebar_settings); if (null != settingsLayout) { TextView settings = (TextView) settingsLayout.findViewById(R.id.drawer_text); settings.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mDrawerLayout.closeDrawers(); startActivity(new Intent().setClass(self, SettingsActivity.class)); } }); settings.setText(getResources().getText(R.string.settings)); settingsLayout.setVisibility(View.VISIBLE); ImageView settingsImage = (ImageView) settingsLayout.findViewById(R.id.drawer_icon); int[] attrs = { R.attr.iconMenuSettingsDark }; TypedArray ta = settingsImage.getContext().getTheme().obtainStyledAttributes(attrs); settingsImage.setImageDrawable(ta.getDrawable(0)); settingsImage.setVisibility(View.VISIBLE); } mDrawerToggle.syncState(); }
diff --git a/src/main/java/com/greatmancode/craftconomy3/commands/SpoutCommandManager.java b/src/main/java/com/greatmancode/craftconomy3/commands/SpoutCommandManager.java index 86f0401..1251373 100644 --- a/src/main/java/com/greatmancode/craftconomy3/commands/SpoutCommandManager.java +++ b/src/main/java/com/greatmancode/craftconomy3/commands/SpoutCommandManager.java @@ -1,92 +1,92 @@ /* * This file is part of Craftconomy3. * * Copyright (c) 2011-2012, Greatman <http://github.com/greatman/> * * Craftconomy3 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. * * Craftconomy3 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 Craftconomy3. If not, see <http://www.gnu.org/licenses/>. */ package com.greatmancode.craftconomy3.commands; import org.spout.api.chat.ChatArguments; import org.spout.api.command.Command; import org.spout.api.command.CommandContext; import org.spout.api.command.CommandExecutor; import org.spout.api.command.CommandSource; import org.spout.api.exception.CommandException; import org.spout.api.player.Player; import com.greatmancode.craftconomy3.Caller; import com.greatmancode.craftconomy3.Common; import com.greatmancode.craftconomy3.CC3SpoutLoader; /** * Handle the commands for the Spout server. * @author greatman * */ public class SpoutCommandManager implements CommandExecutor, CommandManager { public SpoutCommandManager() { CC3SpoutLoader.getInstance().getEngine().getRootCommand().addSubCommand(CC3SpoutLoader.getInstance(), "money").setHelp("Money Related Commands").setExecutor(this); } @Override public boolean processCommand(CommandSource source, Command command, CommandContext args) throws CommandException { CraftconomyCommand cmd = null; if (command.getPreferredName().equals("money")) { if (args.length() == 0) { cmd = Common.getInstance().getCommandManager().getMoneyCmdList().get(""); } else { Common.getInstance().getCommandManager().getMoneyCmdList().get(args.getString(0)); } } else if (command.getPreferredName().equals("bank")) { if (args.length() == 0) { cmd = Common.getInstance().getCommandManager().getBankCmdList().get(""); } else { Common.getInstance().getCommandManager().getBankCmdList().get(args.getString(0)); } } if (cmd != null) { if (cmd.playerOnly()) { if (!(source instanceof Player)) { source.sendMessage(ChatArguments.fromString(Caller.CHAT_PREFIX + "{{DARK_RED}}Only a player can use this command!")); return true; } } if (!(source instanceof Player) || cmd.permission(source.getName())) { String[] newargs; if (args.length() == 0) { newargs = new String[0]; } else { newargs = new String[args.length() - 1]; for (int i = 1; i <= newargs.length; i++) { newargs[i - 1] = args.getString(i); } } if (newargs.length >= cmd.minArgs() && newargs.length <= cmd.maxArgs()) { - source.sendMessage(ChatArguments.fromString(Caller.CHAT_PREFIX + cmd.help())); + cmd.execute(source.getName(), newargs); return true; } - cmd.execute(source.getName(), newargs); + source.sendMessage(ChatArguments.fromString(Caller.CHAT_PREFIX + cmd.help())); return true; } else { source.sendMessage(ChatArguments.fromString(Caller.CHAT_PREFIX + "{{DARK_RED}}Not enough permissions!")); return true; } } return false; } }
false
true
public boolean processCommand(CommandSource source, Command command, CommandContext args) throws CommandException { CraftconomyCommand cmd = null; if (command.getPreferredName().equals("money")) { if (args.length() == 0) { cmd = Common.getInstance().getCommandManager().getMoneyCmdList().get(""); } else { Common.getInstance().getCommandManager().getMoneyCmdList().get(args.getString(0)); } } else if (command.getPreferredName().equals("bank")) { if (args.length() == 0) { cmd = Common.getInstance().getCommandManager().getBankCmdList().get(""); } else { Common.getInstance().getCommandManager().getBankCmdList().get(args.getString(0)); } } if (cmd != null) { if (cmd.playerOnly()) { if (!(source instanceof Player)) { source.sendMessage(ChatArguments.fromString(Caller.CHAT_PREFIX + "{{DARK_RED}}Only a player can use this command!")); return true; } } if (!(source instanceof Player) || cmd.permission(source.getName())) { String[] newargs; if (args.length() == 0) { newargs = new String[0]; } else { newargs = new String[args.length() - 1]; for (int i = 1; i <= newargs.length; i++) { newargs[i - 1] = args.getString(i); } } if (newargs.length >= cmd.minArgs() && newargs.length <= cmd.maxArgs()) { source.sendMessage(ChatArguments.fromString(Caller.CHAT_PREFIX + cmd.help())); return true; } cmd.execute(source.getName(), newargs); return true; } else { source.sendMessage(ChatArguments.fromString(Caller.CHAT_PREFIX + "{{DARK_RED}}Not enough permissions!")); return true; } } return false; }
public boolean processCommand(CommandSource source, Command command, CommandContext args) throws CommandException { CraftconomyCommand cmd = null; if (command.getPreferredName().equals("money")) { if (args.length() == 0) { cmd = Common.getInstance().getCommandManager().getMoneyCmdList().get(""); } else { Common.getInstance().getCommandManager().getMoneyCmdList().get(args.getString(0)); } } else if (command.getPreferredName().equals("bank")) { if (args.length() == 0) { cmd = Common.getInstance().getCommandManager().getBankCmdList().get(""); } else { Common.getInstance().getCommandManager().getBankCmdList().get(args.getString(0)); } } if (cmd != null) { if (cmd.playerOnly()) { if (!(source instanceof Player)) { source.sendMessage(ChatArguments.fromString(Caller.CHAT_PREFIX + "{{DARK_RED}}Only a player can use this command!")); return true; } } if (!(source instanceof Player) || cmd.permission(source.getName())) { String[] newargs; if (args.length() == 0) { newargs = new String[0]; } else { newargs = new String[args.length() - 1]; for (int i = 1; i <= newargs.length; i++) { newargs[i - 1] = args.getString(i); } } if (newargs.length >= cmd.minArgs() && newargs.length <= cmd.maxArgs()) { cmd.execute(source.getName(), newargs); return true; } source.sendMessage(ChatArguments.fromString(Caller.CHAT_PREFIX + cmd.help())); return true; } else { source.sendMessage(ChatArguments.fromString(Caller.CHAT_PREFIX + "{{DARK_RED}}Not enough permissions!")); return true; } } return false; }
diff --git a/src/com/flaptor/util/parser/PdfParser.java b/src/com/flaptor/util/parser/PdfParser.java index ad7f8c1..25a956f 100644 --- a/src/com/flaptor/util/parser/PdfParser.java +++ b/src/com/flaptor/util/parser/PdfParser.java @@ -1,49 +1,49 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.flaptor.util.parser; import com.flaptor.util.Execute; import java.io.ByteArrayInputStream; import org.pdfbox.encryption.DocumentEncryption; import org.pdfbox.pdfparser.PDFParser; import org.pdfbox.pdmodel.PDDocument; import org.pdfbox.pdmodel.PDDocumentInformation; import org.pdfbox.util.PDFTextStripper; /** * * @author jorge */ public class PdfParser implements IParser { - public ParseOutput parse(String url, byte[] content, String encoding) throws Exception { + public ParseOutput parse(String url, byte[] content) throws Exception { ParseOutput output = null; PDDocument pdf = null; try { PDFParser parser = new PDFParser(new ByteArrayInputStream(content)); parser.parse(); pdf = parser.getPDDocument(); PDFTextStripper stripper = new PDFTextStripper(); String text = stripper.getText(pdf); PDDocumentInformation info = pdf.getDocumentInformation(); String title = info.getTitle(); output = new ParseOutput(url); output.addFieldString(ParseOutput.CONTENT, text); output.setTitle(title); //System.out.println("ENCODING: "+encoding); //System.out.println("TITLE: "+title); //System.out.println("TEXT: "+text); //System.out.println("LEN: "+text.length()); } finally { Execute.close(pdf); Execute.close(output); } return output; } }
true
true
public ParseOutput parse(String url, byte[] content, String encoding) throws Exception { ParseOutput output = null; PDDocument pdf = null; try { PDFParser parser = new PDFParser(new ByteArrayInputStream(content)); parser.parse(); pdf = parser.getPDDocument(); PDFTextStripper stripper = new PDFTextStripper(); String text = stripper.getText(pdf); PDDocumentInformation info = pdf.getDocumentInformation(); String title = info.getTitle(); output = new ParseOutput(url); output.addFieldString(ParseOutput.CONTENT, text); output.setTitle(title); //System.out.println("ENCODING: "+encoding); //System.out.println("TITLE: "+title); //System.out.println("TEXT: "+text); //System.out.println("LEN: "+text.length()); } finally { Execute.close(pdf); Execute.close(output); } return output; }
public ParseOutput parse(String url, byte[] content) throws Exception { ParseOutput output = null; PDDocument pdf = null; try { PDFParser parser = new PDFParser(new ByteArrayInputStream(content)); parser.parse(); pdf = parser.getPDDocument(); PDFTextStripper stripper = new PDFTextStripper(); String text = stripper.getText(pdf); PDDocumentInformation info = pdf.getDocumentInformation(); String title = info.getTitle(); output = new ParseOutput(url); output.addFieldString(ParseOutput.CONTENT, text); output.setTitle(title); //System.out.println("ENCODING: "+encoding); //System.out.println("TITLE: "+title); //System.out.println("TEXT: "+text); //System.out.println("LEN: "+text.length()); } finally { Execute.close(pdf); Execute.close(output); } return output; }